Postgres jsonb array: query for non-empty intersection

馋奶兔 提交于 2019-12-23 18:56:40

问题


Suppose I have a JSONB column called value in a table t, and inside of these blobs of JSON is a tags field which is a list of strings.

I'd like to make a query for any of these JSON blobs tagged "foo" or "bar".

So suppose the table data looks like this:

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

I want to write some sort of query like this:

select value from t where value->'tags' NONEMPTY_INTERSECTION '["foo", "bar"]'

Such that the result will be:

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

Is there an actual query that will accomplish this, and is there any way that it could possibly be fast?


回答1:


SELECT DISTINCT t.value
FROM t, jsonb_array_elements(t.value->'tags') tags
WHERE tags.value <@ '["foo", "bar"]'::jsonb;



回答2:


The operator I was looking for is ?|, which can be used like so:

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

Tested as follows:

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)


来源:https://stackoverflow.com/questions/39480816/postgres-jsonb-array-query-for-non-empty-intersection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!