Using jsonb (PostgreSQL), how do I retrieve items with a certain value that's saved as an array?

Deadly 提交于 2019-12-14 02:23:13

问题


I'm trying to find all recipes in a certain category, where the key/value data is recorded in a PostgreSQL's jsonb column (and the value is saved as an array).

For example, say I have "data" as my jsonb column in the "recipes" table, and I have three entries like so:

"Recipe 1" contains a "data" with key/value of: "category_ids"=>[123, 4059]
"Recipe 2" contains a "data" with key/value of: "category_ids"=>[405, 543]
"Recipe 3" contains a "data" with key/value of: "category_ids"=>[567, 982]

I want to retrieve only items that contain the "405" category id value (i.e. only Recipe 2 above)

This is what I have so far using Ruby on Rails to query the PostgreSQL database:

Recipe.where("(data ->> 'category_ids') LIKE '%405%'")

However, that retrieves both "Recipe 1" and "Recipe 2" because they both contain "405" text.

What query should I use to correctly retrieve recipes with the "405" category id only?


回答1:


You can also directly use IN along with json_array_elements:

Recipe.where("'405' IN (SELECT json_array_elements(data->'category_ids')::text)")

And if your column is a jsonb column, you can similarly do:

Recipe.where("'405' IN (SELECT jsonb_array_elements(data->'category_ids')::text)")



回答2:


you need ANY function. Something like

select * from t where '405' = any (
  ARRAY(
    SELECT e::text FROM json_array_elements(data->'category_ids') e
  )
);

or

select * from t where '405' = any (
  ARRAY(
    SELECT e::text FROM jsonb_array_elements(data->'category_ids') e
  )
);

if your type is jsonb (higher than 9.3 postgres version)

http://sqlfiddle.com/#!15/1a895/1




回答3:


You can use unnest function available. More details can be check here : Postgresql Functions & Operators.



来源:https://stackoverflow.com/questions/37123173/using-jsonb-postgresql-how-do-i-retrieve-items-with-a-certain-value-thats-sa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!