【问题标题】:Index jsonb column keys using GIN and pg_trgm, for ILIKE queries in Rails使用 GIN 和 pg_trgm 索引 jsonb 列键,用于 Rails 中的 ILIKE 查询
【发布时间】:2021-10-04 21:43:51
【问题描述】:

我有一个表格“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 为潜在客户表添加了以下行 -

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 查询?我哪里错了?如有必要,我很乐意提供更多详细信息。

【问题讨论】:

  • 不要将文本作为文本图像发布。发布文本。
  • 下次我一定会牢记这一点。非常感谢您的回答!

标签: ruby-on-rails postgresql database-indexes pg-trgm


【解决方案1】:

另一种方法是告诉您的索引已经使用大写或小写对值进行排序,这样您就可以在查询中简单地使用LIKE

CREATE INDEX leads_user_details_name_idx ON leads 
USING gin(lower(user_details->>'name') gin_trgm_ops);

当查询这个 jsonb 键时,你必须使用相同的函数。这样做查询计划器将找到您的部分索引:

SELECT * FROM leads
WHERE lower(user_details->>'name') ~~ '%doe%';

演示:db&lt;&gt;fiddle

【讨论】:

    【解决方案2】:

    您的表可能太小而无法进行索引扫描。看起来它只有 269 行。您可以set enable_seqscan=off 看看它是否使用索引。或者您可以只向表中添加实际数量的行(然后 VACUUM ANALYZE)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-12
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多