如何通过哈希值在JSON哈希数组中进行搜索?

mam*_*oha 6 ruby postgresql json ruby-on-rails

我使用Postgres的JSON数据类型来存储一些信息.

例如,我的模型User包含一个字段locations,该字段包含一个json文档(包含键和值对的对象数组),格式如下:

[{"name": "Location 1", kind: "house"},
 {"name": "Location 2", kind: "house"},
 {"name": "Location 3", kind: "office"},
 ...
 {"name": "Location X", kind: "house"}
]
Run Code Online (Sandbox Code Playgroud)

我想查询.whereJSON数据类型.

我想查询至少有一个位置的用户kind = office.

谢谢!

And*_*eko 8

我想查询具有类型位置的用户 office

# if locations is jsonb type
User.where('locations @> ?', { kind: 'office' }.to_json)
# if locations is json type
User.where("locations->>'kind' = 'office'")
# if locations is array of hashes
User.where('locations @> ?', [{ kind: 'office' }].to_json)
Run Code Online (Sandbox Code Playgroud)

  • 不管怎样,谢谢你的帮助。我将数据从 json 迁移到 jsonb。这对我有用 `User.where('locations @> ?', [{ kind: 'office' }].to_json)` (2认同)

seq*_*elo 5

我混合使用了上述答案。这是我的工作代码:

User.where("locations::jsonb @> ?", [{kind: 'office'}].to_json)
Run Code Online (Sandbox Code Playgroud)

作为一个说明,locationsJSONUser表(不JSONB数据类型)