JSON演算子を使用するよりも高い価格を見つける

Aug 20 2020

Json:

 "availability": [
      {
        "qty": 25,
        "price": 3599,
        "is_available": true
      },
      {
        "qty": 72,
        "price": 3599,
        },
         "is_available": true
   ]

value = " 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);