【问题标题】:postgresql pg_trgm speed up by where conditionspostgresql pg_trgm 通过 where 条件加速
【发布时间】:2017-08-16 05:41:21
【问题描述】:

我使用 pg_trgm 扩展来检查文本列的相似性。我想通过使用附加条件来加速它,但没有成功。速度是一样的。这是我的例子:

    create table test (
    id serial,
    descr text,
    yesno text,
    truefalse boolean
    );
    insert into test SELECT generate_series(1,1000000) AS id, 
md5(random()::text) AS descr ; 
    update test set yesno = 'yes' where id < 500000;
    update test set yesno = 'no' where id > 499999;
    update test set truefalse = true where id < 100000;
    update test set truefalse = false where id > 99999;
    CREATE INDEX test_trgm_idx ON test USING gist (descr gist_trgm_ops);

所以,当我执行查询时,我是否使用 where 子句是没有区别的。

 select descr <->  '65c141ee1fdeb269d2e393cb1d3e1c09' 
 as dist, descr, yesno, truefalse from test 
   where 
   yesno = 'yes'
   and 
   truefalse = true 
order by dist 
limit 10;

这样对吗?

【问题讨论】:

  • 好吧,yesnotruefalse 上没有任何索引。因此,我认为 Postgres 必须扫描以应用此 WHERE 条件,这可能需要一些资源。此外,留下的记录数量可能仍然相当大,在这两种情况下,Postgres 都必须按dist 排序才能应用LIMIT 子句。
  • @TimBiegeleisen,我为布尔列添加了索引,它不会影响...
  • 布尔列只有两个可能的值,所以基数很高,因此索引可能没有帮助。

标签: postgresql pg-trgm


【解决方案1】:

创建测试数据后,请执行ANALYZE 以确保更新统计信息。然后您可以使用EXPLAIN 查找。

在我的机器上,它对 test_trgm_idx 进行索引扫描以按顺序扫描行,以便在达到限制时停止。使用 where 实际上需要做更多的工作,因为它必须在达到限制之前扫描更多行,认为时间差异并不明显。

【讨论】:

  • 我运行分析,然后解释。行数减少了 10 倍,但成本保持不变。执行时间也是如此...
猜你喜欢
  • 2023-04-10
  • 2017-10-09
  • 2011-12-28
  • 2018-02-06
  • 2022-10-24
  • 1970-01-01
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多