Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL index for like 'abc%' searching

I have postgreSQL table with city list (>1M) and I need to search over this table by pattern like 'abc%'. I created B-tree index on city.name column, and here is what i got:

EXPLAIN SELECT * FROM city WHERE NAME ~~* 'Мос%' 
Seq Scan on city  (cost=0.00..44562.62 rows=117 width=131)

And the exact select:

EXPLAIN SELECT * FROM city WHERE NAME = 'Москва' 
Index Scan using city_name_idx on city  (cost=0.43..12.33 rows=2 width=131)

Is there any way to use standart index to achieve good performance on first select?

I am using Symfony2/Doctrine2, so it's not very easy (and I do not want) to implement db-specific things here.

like image 791
Eddie Avatar asked Jul 13 '15 18:07

Eddie


People also ask

Does like use index in PostgreSQL?

There is no index support for LIKE / ILIKE in PostgreSQL 8.4 - except for left anchored search terms. Since PostgreSQL 9.1 the additional module pg_trgm provides operator classes for GIN and GiST trigram indices supporting LIKE / ILIKE or regular expressions (operators ~ and friends).

How do I find special characters in PostgreSQL?

SELECT * FROM spatial_ref_sys WHERE srtext LIKE '%\ /%'; Sometimes these ticks are very useful for searching special characters in a database.

How does Postgres decide which index to use?

The first step is determining the boundaries of the index scan, as it relates to the data stored in the index. In particular this is relevant for multi-column B-tree indexes, where only a subset of the columns might match the query.

What are the different types of index in 7 PostgreSQL explain each one of them?

PostgreSQL provides several index types: B-tree, Hash, GiST, SP-GiST and GIN. Each Index type uses a different algorithm that is best suited to different types of queries. By default, the CREATE INDEX command creates B-tree indexes, which fit the most common situations.


1 Answers

  • 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.

like image 163
Daniel Vérité Avatar answered Sep 21 '22 22:09

Daniel Vérité