ค้นหาราคาที่สูงกว่าการใช้ตัวดำเนินการ 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} ] }';
ดี. มันทำงานได้ดี
แต่ฉันต้องหาราคา> 1,000 ด้วย
ฉันลองสิ่งนี้:
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);