我有一个名为“Leads”的表,其结构如下:
# == Schema Information
#
# Table name: leads
#
# id :integer not null, primary key
# data :jsonb not null
# state :string
# priority :string
# lead_no :string
# user_id :integer
# location_place_id :string
# uuid :string
# agent_id :integer
# location_coordinates :geography point, 4326
# location :jsonb not null
# user_details :jsonb not null
# inventory_id :integer
# source_details :jsonb not null
# connect_details :jsonb not null
# referral_details :jsonb not null
# process_details :jsonb not null
# tags :jsonb not null
# created_at :datetime
# updated_at :datetime
# name :string
user_details jsonb列以{name : "John Doe", country : "IN", phone_no : "123456789"}的形式存储数据。 我想使用ILIKE针对名称键查询我的数据库列:
Lead.where("user_details->>name ILIKE ?","john%")
为了实现这一点,我创建了如下的迁移:
class AddIndexUserNameOnLeads < ActiveRecord::Migration[5.2]
def up
execute("CREATE INDEX leads_user_details_name_idx ON leads USING gin((user_details->>'name') gin_trgm_ops)")
end
def down
execute("DROP INDEX leads_user_details_name_idx")
end
end
这将创建所需的索引。我已经在之前的迁移中启用了pg_trgm扩展。我的structure.sql看起来像: 此外,相应的schema.rb会为leads表添加以下行 -
t.index "((user_details ->> 'name'::text)) gin_trgm_ops", name: "leads_user_details_name_idx", using: :gin
另一方面,如果我为整个"user_details"列创建一个gin索引,然后使用"@> {name: "john"}.to_json"进行查询,它将使用索引进行扫描。
我的Rails版本是5.2.0,PostgreSQL版本是12.5。如何在这种情况下使用ILIKE查询?我做错了什么?如果需要,我很乐意提供更多详细信息。