2016-09-14 92 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;