Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres jsonb array: query for non-empty intersection

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?

like image 892
Dan Burton Avatar asked Sep 18 '25 12:09

Dan Burton


1 Answers

SELECT DISTINCT t.value
FROM t, jsonb_array_elements(t.value->'tags') tags
WHERE tags.value <@ '["foo", "bar"]'::jsonb;
like image 71
Patrick Avatar answered Sep 21 '25 05:09

Patrick