user1950164
user1950164

Reputation:

postgres: Composite fulltext / btree index

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?

Upvotes: 3

Views: 1101

Answers (2)

Paolo Melchiorre
Paolo Melchiorre

Reputation: 6122

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)

Upvotes: 0

Nick Barnes
Nick Barnes

Reputation: 21356

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.

Upvotes: 1

Related Questions