2016-09-26 9 views
0

のJSON配列で二回表示される場合:私は二回{ "type": "foo" }表示された場合はtrueを返すPostgreSQLの関数を作成したいと思いますチェックオブジェクトキーは、次のようになりますjsonb配列を指定したオブジェクト

[ 
    { "type": "foo", "desc": "example" }, 

    { "type": "foo", "desc": "second example" }, 

    { "type": "bar", "desc": "third example" } 
] 

を。

+0

私は、各オブジェクトが異なるという例を明確にしました。 –

答えて

1

使用jsonb_array_elements()、例えば:

with data(js) as (
    select 
     '[ 
     { "type": "foo", "desc": "example" }, 
     { "type": "foo", "desc": "second example" }, 
     { "type": "bar", "desc": "third example" } 
     ]'::jsonb 
) 
select elem->>'type' as "type", count(elem->'type') 
from data, jsonb_array_elements(js) elem 
group by 1; 

type | count 
------+------- 
foo |  2 
bar |  1 
(2 rows)  

関数は次のようになります。

create or replace function check_duplicates(source jsonb, key text) 
returns boolean language sql as $$ 
    select max(count) > 1 
    from (
     select count(elem->key) 
     from jsonb_array_elements(source) elem 
     group by elem->key 
     ) s 
$$; 

使用法:

with data(js) as (
    select 
     '[ 
     { "type": "foo", "desc": "example" }, 
     { "type": "foo", "desc": "second example" }, 
     { "type": "bar", "desc": "third example" } 
     ]'::jsonb 
) 
select check_duplicates(js, 'type') 
from data; 

check_duplicates 
------------------ 
t 
(1 row) 
0

はここでそれを行う機能です。

CREATE OR REPLACE FUNCTION more_than_two_foos(s jsonb) RETURNS bool AS $$ 
DECLARE 
    c integer; 
BEGIN 
    SELECT count(*) 
    FROM (
     SELECT 1 
     FROM jsonb_array_elements(s) 
     WHERE value->>'type'='foo' 
     LIMIT 2 
    ) t 
    INTO c; 
    RETURN c>=2; 
END; 
$$ LANGUAGE plpgsql IMMUTABLE STRICT; 

そしてここではいくつかの例です:

$ SELECT more_than_two_foos('[ 
    { "type": "foo", "desc": "example" }, 
    { "type": "foo", "desc": "second example" }, 
    { "type": "bar", "desc": "third example" } 
]'); 
more_than_two_foos 
-------------------- 
t 
(1 row) 

$ SELECT more_than_two_foos('[ 
    { "type": "foo", "desc": "second example" }, 
    { "type": "bar", "desc": "third example" } 
]'); 
more_than_two_foos 
-------------------- 
f 
(1 row) 

アイデアそれはjsonb_array_elementsを使用してjsonb配列の要素を通過し、fooに等しいtypeを持つ要素を数えるということです。

+0

この機能でクエリを高速化するインデックスを作成する方法はありますか? –

+0

これは単なる関数であり、テーブルのクエリを行わないため、インデックスの影響を受けません。一般に、私は、あなたが手元にあるプロパティを満たす行の検索をスピードアップするために使用できるインデックスがあることは疑いの余地があります。 – redneb

関連する問題