问题描述
Json:
"availability": [
{
"qty": 25,"price": 3599,"is_available": true
},{
"qty": 72,},"is_available": true
]
如果我要查找值为=“ 3599 ”的价格,请使用以下查询:
select *
from product
where to_tsvector(product.data #>> '{availability}') @@ to_tsquery('3599')
或此查询:
SELECT *
FROM product
WHERE product.data @> '{"availability": [ { "price": 3599} ] }';
好。很好。
但是我还需要找到价格> 1000
我尝试这个:
select *
from product
where to_tsvector(product.data #>> '{availability}') @@ to_tsquery('>1000')
但是结果为空(没有找到)。
解决方法
全文搜索是这种查询的错误工具。
在Postgres 12中,您可以使用JSON / Path表达式:
select *
from product
where data @@ '$.availability[*].price > 100';
对于较旧的Postgres版本,您需要取消嵌套该数组:
select *
from product
where exists (select *
from jsonb_array_elements(data -> 'availability') as x(item)
where (x.item ->> 'price')::int > 100);