JSONB中的通配符

时间:2016-10-11 18:16:22

标签: postgresql jsonb

寻找通配符运算符来查询JSONB数据类型。例如:

$> Campaign.find(43).style_item_map

{"0"=>{"items"=>[876, 875], "style"=>"First", "featured"=>[876, 875]}, "1"=>{"items"=>[999, 998], "style"=>"Secondary",
"featured"=>[]}}

正在寻找这样的查询:(%不在这里工作)

Campaign.where("style_item_map @> '{\"%\":{\"items\": [876]}}'")

1 个答案:

答案 0 :(得分:1)

我假设您需要对此类文档使用jsonb_each两次:

WITH t(style_item_map) AS ( VALUES
  ('{
  "0": {
    "items":[876, 875],
    "style":"First",
    "featured":[876, 875]
  },
  "1": {
    "items":[999, 998],
    "style":"Secondary",
   "featured":[]
   }
}'::JSONB)
)
SELECT
  item.key,
  inner_item
FROM t,
    jsonb_each(t.style_item_map) item,
    jsonb_each(item.value) inner_item
WHERE
  inner_item.key = 'items'
AND
  inner_item.value @> '[876]';

结果:

 key |      inner_item      
-----+----------------------
 0   | (items,"[876, 875]")
(1 row)