【问题标题】:Why isn't Postgres using my gin index?为什么 Postgres 不使用我的 gin 索引?
【发布时间】:2016-02-09 18:37:08
【问题描述】:

有了这张桌子:

=> \d "user"
                                          Table "public.user"
        Column        |            Type             |                     Modifiers                     
----------------------+-----------------------------+---------------------------------------------------
 id                   | integer                     | not null default nextval('user_id_seq'::regclass)
 email                | character varying(255)      | 
Indexes:
    "user_pkey" PRIMARY KEY, btree (id)
    "user_email_key" UNIQUE CONSTRAINT, btree (email)
    "user_email_idx" gin (email gin_trgm_ops)

此查询未使用 gin 索引:

=> explain select email from "user" where email ilike '%j%';
                          QUERY PLAN                          
--------------------------------------------------------------
 Seq Scan on "user"  (cost=0.00..3986.42 rows=11886 width=22)
   Filter: ((email)::text ~~* '%j%'::text)
(2 rows)

为什么?

【问题讨论】:

    标签: postgresql database-indexes


    【解决方案1】:

    https://hashrocket.com/blog/posts/exploring-postgres-gin-index

    注意事项 这种方法的唯一缺点是输入查询必须至少包含 3 个字母,因为 Postgres 需要能够从输入查询中提取至少一个三元组才能使用我们的三元组索引。

    【讨论】:

    • 哈哈!就是这样。 explain select email from "user" where email ilike '%jjb%'; 发现“对“用户”进行位图堆扫描(成本=28.02..49.45 行=11 宽度=22)”
    • 实际上输入必须像%abc% %aba% 所以它并不总是三个字符。
    【解决方案2】:

    因为您实际上并未使用 trigram 索引或您的 postgres

    select email from "user" where similarity(email, 'xyz@gmail.com') > 0.5;
    

    0.5 是您的阈值,0-完全不同,1-完全匹配

    UPD:考虑你给1个字符作为匹配词,因为一个符号可以匹配很多文档,它可能会表现出很差的性能

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 1970-01-01
      • 2015-10-18
      • 2014-02-06
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多