JSON 연산자를 사용하는 것보다 더 큰 가격 찾기

Aug 20 2020

Json :

 "availability": [
      {
        "qty": 25,
        "price": 3599,
        "is_available": true
      },
      {
        "qty": 72,
        "price": 3599,
        },
         "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')

그러나 결과는 비어 있습니다 (아무것도 찾을 수 없음).

답변

3 a_horse_with_no_name Aug 20 2020 at 12:33

전체 텍스트 검색은 이러한 종류의 쿼리에 대해 잘못된 도구입니다.

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