2016-09-14 10 views
1

テーブルtvalueというJSONB列があり、JSONのこれらのBLOBの内側に文字列のリストであるtagsフィールドがあるとします。Postgres jsonb配列:空でない交差のクエリ

"foo"または"bar"というタグが付けられたこれらのJSONブロブのいずれかのクエリを作成したいと思います。私はこのようなクエリのいくつかの並べ替えを書きたい

value 
--------------------- 
{"tags": ["other"]} 
{"tags": ["foo", "quux"]} 
{"tags": ["baz", "bar"]} 
{"tags": ["bar", "foo"]} 
{"tags": []} 

ので、テーブルのデータは次のようになりますと仮定

結果がされるように
select value from t where value->'tags' NONEMPTY_INTERSECTION '["foo", "bar"]' 

value 
----------------------- 
{"tags": ["foo", "quux"]} 
{"tags": ["baz", "bar"]} 
{"tags": ["bar", "foo"]} 

これを達成するための実際のクエリはありますか?高速である可能性があります。

+0

可能な複製を(http://stackoverflow.com/questions/39480863/querying-jsonb-with-array-fields) – Agzam

答えて

0

私が探していたオペレータはそうのように使用することができる?|である:

select t.value from t where value->'tags' ?| array['foo','bar']; 

次のようにテストした:[配列フィールドとJSONBを照会]の

danburton=# select * from jsonb_test; 
      value 
--------------------------- 
{"tags": ["foo"]} 
{"tags": ["other"]} 
{"tags": ["foo", "quux"]} 
{"tags": ["baz", "bar"]} 
{"tags": ["bar", "foo"]} 
{"tags": []} 
(6 rows) 

danburton=# select jsonb_test.value from jsonb_test where value->'tags' ?| array['foo','bar']; 
      value 
--------------------------- 
{"tags": ["foo"]} 
{"tags": ["foo", "quux"]} 
{"tags": ["baz", "bar"]} 
{"tags": ["bar", "foo"]} 
(4 rows) 
2
SELECT DISTINCT t.value 
FROM t, jsonb_array_elements(t.value->'tags') tags 
WHERE tags.value <@ '["foo", "bar"]'::jsonb; 
関連する問題