2016-09-14 67 views
1

假設我在表t中有一個名爲value的JSONB列,並且這些這些blob中的JSON是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

[查詢JSONB與數組字段]的可能的複製(http://stackoverflow.com/questions/39480863/querying-jsonb-with-array-fields) – Agzam

回答

0

我尋找操作是?|,其可用於像這樣:

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

如下測試:

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;