我有带城市列表的postgreSQL表(> 1M),我需要通过'abc%'这样的模式搜索这个表。
我在city.name
列上创建了B树索引,这是我得到的:
EXPLAIN SELECT * FROM city WHERE NAME ~~* 'Мос%'
Seq Scan on city (cost=0.00..44562.62 rows=117 width=131)
确切的选择:
EXPLAIN SELECT * FROM city WHERE NAME = 'Москва'
Index Scan using city_name_idx on city (cost=0.43..12.33 rows=2 width=131)
有没有办法在第一次选择时使用标准索引来获得良好的性能?
我正在使用Symfony2 / Doctrine2,因此在这里实现特定于db的事情并不容易(我不想要)。
答案 0 :(得分:3)
To speed up LIKE
(case sensitive), create an index like this:
create index indexname on city (name text_pattern_ops);
To speed up ILIKE
or ~~*
, in addition to LIKE
, assuming PostgreSQL 9.1 or newer, create an index like this:
create index indexname on city using gin(name gin_trgm_ops);
gin_trgm_ops
is provided by the pg_trgm extension that should be added if not already present in the database.