← 中文资源

简体中文版本

ts_rank 排序全文检索结果

用 ts_rank 与 ts_rank_cd 为匹配排序,把标题权重置于正文之上,并用生成 tsvector 列上的 GIN 索引配合查询。

阅读英文原文

实现说明

一个文件里不止一条语句:SELECT / INSERT / CREATE / EXPLAIN,notes 都在涉及之列。 具体组合了这些手段:WHERE 决定这条语句会作用到哪些行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。

常见问题

说出这个文件涉及的表。

notes——这些名字在文件里直接引用,不涉及连接。

核心语句

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;
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.');
EXPLAIN (COSTS OFF)
SELECT id FROM notes
WHERE document @@ websearch_to_tsquery('english', 'index');

代码示例

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;