简体   繁体   English

如何在 Rails 6 上的 Ruby 上正确查询 Postgresql JSONB 哈希数组?

[英]How to properly query Postgresql JSONB array of hashes on Ruby on Rails 6?

This is my column:这是我的专栏:

[
  { id: 1, value: 1, complete: true }, 
  { id: 2, value: 1, complete: false },
  { id: 3, value: 1, complete: true } 
]

First, is there a "correct" way to work with a jsonb scheme?首先,是否有使用 jsonb 方案的“正确”方式? should I redesign to work with a single json instead of the array of hashes?我应该重新设计以使用单个 json 而不是哈希数组吗?

I have about 200 entries on the database, the column status has 200 of those itens.我在数据库中有大约 200 个条目,列状态有 200 个条目。

  • How would I perform a query to get the count of true/false?我将如何执行查询以获取真/假计数?
  • How can I query for ALL complete itens?如何查询所有完整的项目? I can query for the database rows in which the json has an item complete, but I can't query for all the itens, in all rows of the database that are complete.我可以查询 json 具有完整项目的数据库行,但我无法查询数据库中所有完整行中的所有项目。

Appreciate the help, thank you感谢帮助,谢谢

Aha: I found it here:啊哈:我在这里找到的:

https://levelup.gitconnected.com/how-to-query-a-json-array-of-objects-as-a-recordset-in-postgresql-a81acec9fbc5 https://levelup.gitconnected.com/how-to-query-a-json-array-of-objects-as-a-recordset-in-postgresql-a81acec9fbc5

Say your dataset is like this:假设您的数据集是这样的:

[{
  "productid": "3",
  "name": "Virtual Keyboard",
  "price": "150.00"
}, {
  "productid": "1",
  "name": "Dell 123 Laptop Computer",
  "price": "1300.00"
},
{
  "productid": "8",
  "name": "LG Ultrawide Monitor",
  "price": "190.00"
}]

The proper way to count it, is like this:计算它的正确方法是这样的:

select items.name, count(*) as num from 
purchases,jsonb_to_recordset(purchases.items_purchased) as items(name text)
group by items.name
order by num Desc

Works like a charm and is extremely fast.像魅力一样工作,速度非常快。 To do it in Rails, you need to use Model.find_by_sql(....) and indicate your select therem.要在 Rails 中执行此操作,您需要使用 Model.find_by_sql(....) 并指出您的 select 。 I'm sure there are probably better ways to do it.我确信可能有更好的方法来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM