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

12

我正在使用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"}
]

我想在JSON数据类型上使用 .where 进行查询。

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

谢谢!


1
这可能会对你有所帮助:http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails - Jayaprakash
5个回答

18
我想查询拥有类型为“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)

@>jsonb 操作符,不幸的是,我只有 json - Anton Maminov
1
我已经尝试过了,但它不起作用。它总是返回一个空结果。 - Anton Maminov
我认为问题在于_哈希_数组。 - Anton Maminov
@mamantoha 应该只是 locations,而不是一个变量。已编辑。 - Andrey Deineko
2
无论如何,感谢您的帮助。我将我的数据从JSON迁移到了JSONB。这对我很有效:User.where('locations @> ?', [{ kind: 'office' }].to_json) - Anton Maminov
显示剩余4条评论

6
我使用了以上回答的混合。这是我的工作代码:
User.where("locations::jsonb @> ?", [{kind: 'office'}].to_json)

作为一个注解,locationsUser 表的一个 JSON 列(不是 JSONB 数据类型)。

4

基于JSONB数组中对象值的过滤器

如果您想要在Rails与Postgres中基于数组中jsonb对象的值进行过滤,可以使用以下示例。

假设您有一个Product模型:

Product.select("*").from(
  Product.select("*, jsonb_array_elements(registers) as register")
).where("(register ->> 'price')::numeric >= 1.50")

在上面的示例中,我们选择价格大于或等于1.50的所有产品。

为此,我们使用:

我在子查询中应用了缩进,只是为了更好的可读性。

之后,您可以将其放入作用域或使用其他最佳实践。


3

来源:https://www.postgresql.org/docs/current/static/functions-json.html

JSON函数是PostgreSQL中处理JSON数据类型的函数集合。这些函数可以用于解析、操作和查询JSON数据。在使用这些函数时,应该注意JSON数据格式的规范性和正确性,以免出现错误。
User.where("name::jsonb -> 'location' ->> 'kind' = ?", 'office')

2

我来发表一下我的看法:

我有一个包含键和数组的JSON模型,它的结构如下:

ModelObj: attribute: { key: [val0, val1, val2, val3] }

我需要查找所有具有某些属性的对象,例如,数组中键为val3的属性。我将属性类型更改为jsonb,并且以下是我的查找方式:

Model.where('attribute @> ?', {key: ['val3']}.to_json)

也许对某些人有用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接