查找价格高于使用JSON运算符

问题描述

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);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...