一、jsonb

# 新增
add_column :shi_tis, :setting, :jsonb, default: {}

# stringjsonb
def change
  change_column :users, :setting, :jsonb, using: 'setting::jsonb', default: {}
end

# 加索引
add_index :users, :setting, using: :gin # 这样就为setting jsonb字段创建一个索引
# 后续就可以利用这个索引快速查询内部字段值:
User.where("setting->>'name' = ?", 'LiLei')
# 如果字段较大,也可以只为某个内部路径添加索引:
add_index :users, ("setting->'name'"), using: :gin

jsonb查询

 #<User:0x000000010b37ebd0> {
                :id => 2,
             :mobile => nil,
        :setting => {
            "name" => "LiLei",
            "age" => 2,
            "wechat" => { "nickname" => "sky", "openid" => 'x23212x' } 
        }
 }
User.where("setting @> ?", { name: 'LiLei' }.to_json)
User.where("setting ->> 'name' = ?", 'LiLei')
User.where("setting -> 'wechat' = ?", { nickname: 'sky' }.to_json)
User.where("setting -> 'wechat' ->> 'nickname' = ?", 'sky')

json和jsonb字段在Postgres数据库层面有以下区别:

二、Array

create_table :books do |t|
  t.string 'title'
  t.string 'tags', array: true
  t.integer 'ratings', array: true
end
add_index :books, :tags, using: 'gin'
add_index :books, :ratings, using: 'gin'
Book.create title: "Brave New World",
            tags: ["fantasy", "fiction"],
            ratings: [4, 5]

# 包含fantasytags
Book.where("'fantasy' = ANY (tags)")

# 包含["fantasy", "fiction"]2个
Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])

# 匹配["fantasy", "fiction"]中任意一个
Book.where("tags && ARRAY[?]::varchar[]", ["fantasy", "fiction"])

## Books with 3 or more ratings
Book.where("array_length(ratings, 1) >= 3")

原文地址:https://blog.csdn.net/qq_41037744/article/details/134634893

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_35626.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注