有没有办法在postgres中为快速子字符串搜索编制索引

dan*_*dan 11 postgresql

我有一个数据库,并希望能够在表中查找类似于以下内容的搜索:select*from table where column as"abc%def%ghi"或select*from table where column in like"%def%ghi"is有没有办法索引列,这样不是太慢?

编辑:我还可以澄清数据库是只读的,不会经常更新.

Cra*_*ger 18

文本搜索和索引的选项包括:

从上面给出的最小信息,我会说只有一个三元组索引才能帮助你,因为你正在对一个字符串进行中缀搜索而不是查找字典单词.不幸的是,三元组索引是巨大的,效率很低; 不要指望某种神奇的性能提升,并记住他们需要花费大量的工作来建立数据库引擎并保持最新.


rog*_*ack 6

例如,如果您只需要在整个表中获取唯一的子字符串,则可以创建子字符串索引:

CREATE INDEX  i_test_sbstr ON tablename (substring(columname, 5, 3)); 
-- start at position 5, go for 3 characters

It is important that the substring() parameters in the index definition are
the same as you use in your query.
Run Code Online (Sandbox Code Playgroud)

参考:http://www.postgresql.org/message-id/BANLkTinjUhGMc985QhDHKunHadM0MsGhjg@mail.gmail.com


Clo*_*eto 5

对于like运算符使用运算符类之一varchar_pattern_opstext_pattern_ops

create index test_index on test_table (col varchar_pattern_ops);
Run Code Online (Sandbox Code Playgroud)

这仅在模式不以 a 开头时才有效,%在这种情况下需要另一种策略。

  • 如果需要全文搜索,[pg_trgm](http://www.postgresql.org/docs/current/static/pgtrgm.html) 可能会起作用。我过去使用过它,它在某些条件下工作得很好。应该注意的是,索引变得非常大。IIRC,大约是索引列大小的 2.5 倍。 (3认同)