[英]Rails and Postgres, group by hstore
I have an 'Audit' model with name:string and data:hstore attributes - as follows: 我有一个具有名称:string和数据:hstore属性的“审核”模型-如下:
#<Audit
id: 1,
name: "my audit",
data: {"publisher"=>"some publisher", "display_version"=>"17.012.20098"},
created_at: "2017-10-10 13:09:56",
updated_at: "2017-10-10 13:09:56">
I want to produce a report that contains 3 columns: name, display_version, count 我想生成一个包含3列的报告:名称,display_version,计数
To achieve this I assume that I need to group by "name" and "data -> 'display_version'" 为此,我假设我需要按“名称”和“数据->'display_version'”分组
I am struggling with the query and AR syntax. 我正在努力查询和AR语法。
What I have so far is: 到目前为止,我有:
Parent.audits.group(:name, :data -> 'display_version)'
Even this doesn't work. 即使这样也不行。 Can someone help?
有人可以帮忙吗? I have searched for examples without any luck.
我搜索了没有运气的例子。
You can pass a string containing the SQL grouping expression to group
so you could say: 你可以通过包含SQL分组表达式为字符串
group
,所以你可以说:
Parent.audits.group(%q{name, data -> 'display_version'})
or: 要么:
Parent.audits.group(%q{audits.name, audits.data -> 'display_version'})
And then you could throw a #count
call on the end to get the data you want: 然后,您可以在最后抛出
#count
调用以获取所需的数据:
Parent.audits.group(%q{name, data -> 'display_version'}).count
Use jsonb
instead of hstore
(for a variety of reasons) 使用
jsonb
代替hstore
(出于多种原因)
'Audit' model with name:string and data:jsonb 名称:字符串和数据:jsonb的“审计”模型
Audit.rb Audit.rb
store_accessor :data, :publisher, :display_version
Then try: 然后尝试:
Parent.audits.pluck(:name, :publisher, :display_version)
Good Resource on JSONB and Postgresql 有关JSONB和Postgresql的良好资源
hstore columns don't allow a nested structure;
hstore列不允许使用嵌套结构; they also store all values as strings, which will require type coercion on both database and application layers.
它们还将所有值存储为字符串,这将需要在数据库层和应用程序层上进行类型强制转换。 With json/jsonb columns you don't have this problem;
使用json / jsonb列,您就不会遇到这个问题; numbers (integers/float), booleans, arrays, strings and nulls are accepted, and you can even nest structures in any way you want.
数字(整数/浮点数),布尔值,数组,字符串和null都是可以接受的,甚至您可以按任何需要嵌套结构。
The recommendation is that you stop using hstore in favor of jsonb;
建议您停止使用hstore来支持jsonb; just remember that you have to use PostgreSQL 9.4+ for this to work.
只要记住您必须使用PostgreSQL 9.4+才能工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.