我有一个数据库,并且希望能够在表中查找类似于以下内容的搜索: select * from table where column like "abc%def%ghi" or select * from table where column like "%def%ghi" Is有没有办法索引列,这样就不会太慢?
编辑:我还可以澄清一下数据库是只读的,不会经常更新。
我有一个数据库,并且希望能够在表中查找类似于以下内容的搜索: select * from table where column like "abc%def%ghi" or select * from table where column like "%def%ghi" Is有没有办法索引列,这样就不会太慢?
编辑:我还可以澄清一下数据库是只读的,不会经常更新。
文本搜索和索引选项包括:
具有基于字典的搜索的全文索引,包括对前缀搜索的支持,例如to_tsvector(mycol) @@ to_tsquery('search:*')
text_pattern_ops
支持前缀字符串匹配的索引LIKE 'abc%'
,例如但不支持中缀搜索,如%blah%
;。d 索引可reverse()
用于后缀搜索。
pg_tgrm
如最近的 dba.stackexchange.com 帖子中所示,较新版本上的 trigram索引。
像Apache Solr这样的外部搜索和索引工具。
从上面给出的最少信息来看,我想说只有三元组索引才能为您提供帮助,因为您正在对字符串进行中缀搜索而不是查找字典单词。不幸的是,三元组索引很大而且效率很低。不要指望某种神奇的性能提升,请记住,它们需要大量工作来构建数据库引擎并保持最新状态。
对于like
操作员,请使用操作员类之一varchar_pattern_ops
或text_pattern_ops
create index test_index on test_table (col varchar_pattern_ops);
这仅在模式不以 a 开头时才有效,%
在这种情况下需要另一种策略。
例如,如果您只需要在整个表中获取唯一的子字符串,您可以创建一个子字符串索引:
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.
参考:http ://www.postgresql.org/message-id/BANLkTinjUhGMc985QhDHKunHadM0MsGhjg@mail.gmail.com