postgres: Composite fulltext / btree index

纵然是瞬间 提交于 2020-01-02 07:11:23

问题


I want to do a fulltext search on one column and sort in a different column. If I index these two columns separately postgres can't use both indexes in this query. Is there a way to create a composite index that could be used in this scenario?


回答1:


Unfortunately not.

While you can attach scalar columns to a GIN index via the btree_gin contrib module, Postgres can't use a GIN index for sorting. From the docs:

Of the index types currently supported by PostgreSQL, only B-tree can produce sorted output — the other index types return matching rows in an unspecified, implementation-dependent order.




回答2:


I report as answer my previous comment with example on it

In a similar scenario I build a GiST index on a tsvector column and on another tetxt colum with gist_trgm_ops operator so I actually did a full-text search with the tsvector column and then ordered on the other text column with trigram distance value using only one index.

I created an index on "title" and "search":

CREATE INDEX docs_docume_search_title_gist
  ON public.docs_document
  USING gist
  (title COLLATE pg_catalog."default" gist_trgm_ops, search);

In this query the full-text search is on "search" and the ordering is on "title" with trigram:

SELECT "title", ("title" <-> 'json') AS "distance"
FROM "docs_document"
WHERE ("release_id" = 22 AND "search" @@ (plainto_tsquery('json')) = true)
ORDER BY "distance" ASC
LIMIT 10

This is the explain:

Limit  (cost=0.40..71.99 rows=10 width=29)
  Output: title, (((title)::text <-> 'json'::text))
  ->  Index Scan using docs_docume_search_title_gist on public.docs_document  (cost=0.40..258.13 rows=36 width=29)
        Output: title, ((title)::text <-> 'json'::text)
        Index Cond: (docs_document.search @@ plainto_tsquery('json'::text))
        Order By: ((docs_document.title)::text <-> 'json'::text)
        Filter: (docs_document.release_id = 22)


来源:https://stackoverflow.com/questions/48327224/postgres-composite-fulltext-btree-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!