How to create pg_trgm compound indexes with date columns

时间:2018-01-23 19:19:25

标签: postgresql indexing trigram pg-trgm

SELECT col1, max(date) as max_date
FROM table
WHERE col1 ILIKE 'name'
GROUP BY col1

Here col1 is varchar and date is timestamp with time zone data type. So created extension CREATE EXTENSION pg_trgm

Then tried the following indexes and got the errors:

1: Issue: ERROR: operator class "gin_trgm_ops" does not accept data type timestamp with time zone

CREATE INDEX CONCURRENTLY trgm_table_col1_date_index
ON table 
USING gin (provider_id, date gin_trgm_ops);

2: Issue: ERROR: operator class "text_pattern_ops" does not exist for access method "gin"

 CREATE INDEX CONCURRENTLY trgm_table_col1_date_index
    ON table 
    USING gin (provider_id, date text_pattern_ops);

How can I create an index for the above query for faster execution? Any help will be really appreciated!

EDIT: So this works syntactically but does not speed up the query:

CREATE INDEX CONCURRENTLY trgm_provider_date_index
ON table 
USING gin (provider_id gin_trgm_ops, date_var) 

1 个答案:

答案 0 :(得分:1)

据我所知,Postgres无法使用GIN索引优化min() / max()个查询。

可以date列添加到GIN索引(以及其他标量类型,例如inttext等),方法是安装btree_gin个贡献模块。但是,由于GIN索引方法没有义务以任何特定顺序存储其条目,因此Postgres不能假设它们对于找到最大值是有用的,因此它们将被忽略。

(我无法在文档中找到对此的具体参考,但我认为它与the limitation which prevents anything other than a B-tree from being used to optimise an ORDER BY完全相同。)