簡體   English   中英

如何通過哈希值在JSON哈希數組中進行搜索?

[英]How do I search within an JSON array of hashes by hash values?

我使用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位置的用戶。

謝謝!

我想查詢有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)

資料來源: https//www.postgresql.org/docs/current/static/functions-json.html

User.where("name::jsonb -> 'location' ->> 'kind' = ?", 'office')

只是給我兩分錢:

我有一個帶有密鑰和內部數組的JSON模型,所以它看起來像這樣:

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

我需要找到所有對象,例如,鍵中的鍵具有val3的屬性。 我將屬性類型更改為jsonb,這就是我找到它的方式:

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

也許這對那里的人有用。

基於數組JSONB內對象的值進行過濾

如果你想根據postgres在Rails中的數組內的對象(jsonb)的值制作過濾器,你可以使用類似下面的例子。

假設您有產品型號:

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

在上面的示例中,我們選擇價格大於或等於1.50的所有產品。

為此,我們使用:

我在子查詢中應用ident只是為了獲得最佳可讀性。

您可以將其放入范圍或使用其他最佳實踐。

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

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

作為注釋, locationsUser表的JSON列(不是JSONB數據類型)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM