简体   繁体   中英

Postgres Nested JSONB Query

I have a JSONB column, data, in the orders table:

# orders.data

{
  discount_codes: [
    { code: 'foo' },
    { code: 'bar'}
  ]
}

# codes_array: ['foo', 'bar', 'baz']

I'm trying to select "orders where discount_codes contain a code in codes_array". I could not figure out how to write this query exactly. I read about the [*] operator but am unsure how to use it in this context.

This only searches the first element of discount_codes:

SELECT *
FROM ORDERS
WHERE data->'discount_codes'->0->'code' ?| array['foo','bar','baz']

This only searches for 'foo'.

SELECT *
FROM ORDERS
WHERE data @@ '$.discount_codes[*].code == "foo"'

I've been reading the docs https://www.postgresql.org/docs/12/functions-json.html#FUNCTIONS-SQLJSON-PATH but I'm a bit lost.

You can extract all codes into an array, then apply the ?| operator on that array:

select *
from orders
where jsonb_path_query_array(data, '$.discount_codes[*].code') ?| array['foo','bar','baz'] 

The expression jsonb_path_query_array(data, '$.discount_codes[*].code') returns ["foo", "bar"] for your sample JSON

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