【问题标题】:Why is postgres not using a BTree index for a like 'CONSTANT_PREFIX_%' criteria?为什么 postgres 不将 BTree 索引用于类似 'CONSTANT_PREFIX_%' 的标准?
【发布时间】:2016-05-23 20:24:53
【问题描述】:

我有一个带有 B-Tree 索引的表:

CREATE INDEX idx_test_report_accession on test_report (accession);

我用解释运行以下查询:

"QUERY PLAN"
"Seq Scan on public.test_report r  (cost=0.00..705829.12 rows=30694 width=1140) (actual time=0.143..6253.818 rows=11094 loops=1)"
"  Output: detected_transcript_translation_id, peptide_spectrum_match_id, accession, peptide, modified_sequence, var_mod, spectrum_title, spectrum_file, confidence, mz, retention_time, precursor_mz_error_ppm, sample_name, transcript, gene_symbol, prot_seq, ref_based_location, external_identifier, experiment_name, report_filename, line_number, experiment_path"
"  Filter: (r.accession ~~ 'IP_%'::text)"
"  Rows Removed by Filter: 4296116"
"Planning time: 1.331 ms"
"Execution time: 6255.560 ms"

似乎认为表中只有30694行,决定不使用索引。鉴于 like 通配符是后缀,我认为没有理由不使用索引...

行数为:

SELECT count(*) from test_report r;
4307210

匹配的行数非常少:

SELECT count(*) from test_report r WHERE r.accession like 'IP_%';
11094

注意事项:

  • Postgres 版本为 9.4

【问题讨论】:

  • 请显示explain (analyze, verbose)的输出。另外:您的确切 Postgres 版本是什么?旧版本需要 text_pattern_ops 用于 create index
  • @a_horse:有什么变化吗?据我所知,text_pattern_ops 对于 Unicode 整理的字段仍然是必需的。
  • 感谢@a_horse_with_no_name,我增加了解释的详细程度,并按照您的建议添加了 pg 版本(9.4)

标签: postgresql


【解决方案1】:

在许多排序规则中,共享相同前缀的单词可能不会按排序顺序相邻出现。 See here 例如。这意味着具有这些排序规则的索引不能有效地用于完成前缀查询。

除非您的数据库排序规则是“C”,否则您的默认索引将无法用于前缀搜索。您可以手动指定要在支持它的索引中使用的排序规则或运算符类:

create index on foobar (x collate "C");

或

create index on foobar (x text_pattern_ops);

我只是使用“C”排序规则创建我的所有数据库(即使您需要使用UTF8 编码也可以这样做)。有些人不喜欢它的排序方式,但这主要是由于区分大小写。从来没有人向我抱怨过“嘿,您需要按照 en_US.UTF-8 排序规则进行排序”。那可能是因为几乎没有人知道这些规则是什么。

【讨论】:

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