Postgres JSON数据类型Rails查询

穆罕默德·玛哈拉维(Mohamed El Mahallawy):

我正在使用Postgres的json数据类型,但想对嵌套在json中的数据进行查询/排序。

我想订购或查询json数据类型上的.where。例如,我要查询关注者数量> 500的用户,或者要按关注者或关注者数量进行订购。

谢谢!

例:

model User

data: {
     "photos"=>[
       {"type"=>"facebook", "type_id"=>"facebook", "type_name"=>"Facebook", "url"=>"facebook.com"}
      ], 
     "social_profiles"=>[
         {"type"=>"vimeo", "type_id"=>"vimeo", "type_name"=>"Vimeo", "url"=>"http://vimeo.com/", "username"=>"v", "id"=>"1"},
         {"bio"=>"I am not a person, but a series of plants", "followers"=>1500, "following"=>240, "type"=>"twitter", "type_id"=>"twitter", "type_name"=>"Twitter", "url"=>"http://www.twitter.com/", "username"=>"123", "id"=>"123"}
     ]
}
穆罕默德·玛哈拉维(Mohamed El Mahallawy):

对于任何偶然发现的人。我想出了一个使用ActiveRecord和Postgres的JSON数据类型的查询列表。随时对其进行编辑以使其更加清晰。

以下使用的JSON运算符的文档:https : //www.postgresql.org/docs/current/functions-json.html

# Sort based on the Hstore data:
Post.order("data->'hello' DESC")
=> #<ActiveRecord::Relation [
    #<Post id: 4, data: {"hi"=>"23", "hello"=>"22"}>, 
    #<Post id: 3, data: {"hi"=>"13", "hello"=>"21"}>, 
    #<Post id: 2, data: {"hi"=>"3", "hello"=>"2"}>, 
    #<Post id: 1, data: {"hi"=>"2", "hello"=>"1"}>]> 

# Where inside a JSON object:
Record.where("data ->> 'likelihood' = '0.89'")

# Example json object:
r.column_data
=> {"data1"=>[1, 2, 3], 
    "data2"=>"data2-3", 
    "array"=>[{"hello"=>1}, {"hi"=>2}], 
    "nest"=>{"nest1"=>"yes"}} 

# Nested search:
Record.where("column_data -> 'nest' ->> 'nest1' = 'yes' ")

# Search within array:
Record.where("column_data #>> '{data1,1}' = '2' ")

# Search within a value that's an array:
Record.where("column_data #> '{array,0}' ->> 'hello' = '1' ")
# this only find for one element of the array. 

# All elements:
Record.where("column_data ->> 'array' LIKE '%hello%' ") # bad
Record.where("column_data ->> 'array' LIKE ?", "%hello%") # good

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

尝试使用Sequelize查询Postgres JSON数据类型

按JSON数据类型postgres排序

在postgres和rails中的数组,json和hstore数据类型之间进行选择

Postgres数据类型转换

如何修剪Postgres的JSON数据类型中的空格?

在Postgres中获取JSON字段的数据类型

在Slick,Scala中处理Postgres json数据类型

Postgres查询json数据

Postgres C 扩展数据类型定义

在两个简单的postgres表(使用macaddr数据类型)上加快嵌套循环查询

如何获取Postgres中的自定义查询返回的列名和数据类型?

Rails / Postgres嵌套JSON查询

如何在Rails 6中使用Postgres interval数据类型

postgres:如何将hstore转换为JSON数据类型

如何使用Springboot和Hibernate在DTO和Aggentity类中映射Postgres JSON数据类型

Postgres中的GROUP BY-JSON数据类型不相等吗?

是否可以编写数据类型Converter来处理Postgres JSON列?

如何在JSON Postgres数据类型列中搜索特定的字符串?

使用诸如ltree,json之类的postgres数据类型是否与NoSQL有关?

Npgsql代码首先无法使用Postgres13映射JSON数据类型

Rails 4迁移以将列数据类型从字符串更改为整数,并返回保留数据(postgres)

Rails JSON查询与其他数据类型组合

如何将MySql数据库的JSON文本更改为Postgres SQL的JSON数据类型

Knex在Postgres中创建POINT数据类型

如何使用Postgres的JSONB数据类型与JPA?

固定大小字符串的Postgres数据类型

如何在Postgres中级联表的列的数据类型

H2 - Postgres 模式支持 net 数据类型

如何使用go pg CRUD Postgres Point数据类型