简体   繁体   中英

How can I query a jsonb array to find if it contains a value from a query list?

Currently my table looks something like this

 id |                 companies                 
----+-------------------------------------------------------------------
  1 | {"companies": [{"name": "Google", "industry": "TECH"}, 
    |                {"name": "FOX News", "industry": "MEDIA"}]}
----+--------------------------------------------------------------------
  2 | {"companies": [{"name": "Honda", "industry": "AUTO"}]}
----+--------------------------------------------------------------------
  3 | {"companies": [{"name": "Nike", "industry": "SPORTS"}]}

I want to grab all the rows were the companies JSONB array contains a company with industry in a the list ["TECH", "SPORTS"] .

In this example, the query would return rows 1 and 3.

I'm unsure of how to do this due to the nesting involved.

You can use jsonb_array_elements() and exists :

select t.*
from mytable t
where exists (
    select 1
    from jsonb_array_elements(t.companies -> 'companies') x(obj)
    where x.obj ->> 'industry' in ('TECH', 'SPORTS')
)

Another way to write this, is to use the contains operator @>

select *
from the_table t
where t.companies -> 'companies' @> '[{"industry": "TECH"}]'
   or t.companies -> 'companies' @> '[{"industry": "SPORTS"}]'

This could make use of a GIN index on companies

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM