ts_rank Orders Full-Text Search Results

Rank matches with ts_rank and ts_rank_cd, weight title above body, and combine ranking with a GIN index on a generated tsvector column.

SqlData Fetching

Code

snippet
CREATE TABLE notes (
  id int PRIMARY KEY,
  title text NOT NULL,
  body text NOT NULL,
  document tsvector GENERATED ALWAYS AS (
    setweight(to_tsvector('english', title), 'A') ||
    setweight(to_tsvector('english', body), 'B')
  ) STORED
);

CREATE INDEX notes_document_idx ON notes USING gin (document);

INSERT INTO notes (id, title, body)
VALUES
  (1, 'Postgres index tuning', 'A btree index helps equality; a gin index helps search.'),
  (2, 'Query planning', 'The planner may choose a sequential scan over an index.'),
  (3, 'Index types', 'Gin, gist, brin, and hash indexes serve different workloads.');

SELECT id,
       title,
       ts_rank(document, websearch_to_tsquery('english', 'postgres index')) AS rank,
       ts_rank_cd(document, websearch_to_tsquery('english', 'postgres index')) AS cover_rank
FROM notes
WHERE document @@ websearch_to_tsquery('english', 'postgres index')
ORDER BY rank DESC, id;

-- The GIN index can serve the containment filter.
SET enable_seqscan = off;
EXPLAIN (COSTS OFF)
SELECT id FROM notes
WHERE document @@ websearch_to_tsquery('english', 'index');
RESET enable_seqscan;

How it works

What runs here is SELECT / INSERT / CREATE / EXPLAIN — notes are the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

The notes table is the working surface here.

Statements that matter

INSERT INTO notes (id, title, body)
VALUES
(1, 'Postgres index tuning', 'A btree index helps equality; a gin index helps search.'),
(2, 'Query planning', 'The planner may choose a sequential scan over an index.'),
(3, 'Index types', 'Gin, gist, brin, and hash indexes serve different workloads.');
SELECT id,
title,
ts_rank(document, websearch_to_tsquery('english', 'postgres index')) AS rank,
ts_rank_cd(document, websearch_to_tsquery('english', 'postgres index')) AS cover_rank
FROM notes
WHERE document @@ websearch_to_tsquery('english', 'postgres index')
ORDER BY rank DESC, id;
EXPLAIN (COSTS OFF)
SELECT id FROM notes
WHERE document @@ websearch_to_tsquery('english', 'index');

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`notes` — referenced directly, no join needed.