← 中文资源

简体中文版本

ts_headline 高亮全文检索命中

用 ts_headline、websearch_to_tsquery 与自定义 StartSel、StopSel 标记生成高亮检索摘要。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 articles。 从子句角度看,用到了:WHERE 按条件筛出这条语句真正触碰的行;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这段 SQL 会碰到哪些对象?

articles。

核心语句

SELECT title,
       ts_headline(
         'english',
         body,
         websearch_to_tsquery('english', 'postgres index'),
         'StartSel=<mark>, StopSel=</mark>, MaxWords=18, MinWords=8'
       ) AS snippet
FROM articles
WHERE to_tsvector('english', body) @@ websearch_to_tsquery('english', 'postgres index');
INSERT INTO articles (id, title, body)
VALUES
  (1, 'Indexing Postgres', 'A Postgres index speeds up lookups. Choose the index type carefully.'),
  (2, 'Query Planning', 'The planner compares sequential scans with index scans.');
SELECT ts_headline(
         'english',
         body,
         websearch_to_tsquery('english', 'index'),
         'HighlightAll=TRUE, StartSel=[, StopSel=]'
       ) AS full_highlight
FROM articles
WHERE id = 1;

代码示例

CREATE TABLE articles (
  id int PRIMARY KEY,
  title text NOT NULL,
  body text NOT NULL
);

INSERT INTO articles (id, title, body)
VALUES
  (1, 'Indexing Postgres', 'A Postgres index speeds up lookups. Choose the index type carefully.'),
  (2, 'Query Planning', 'The planner compares sequential scans with index scans.');

SELECT title,
       ts_headline(
         'english',
         body,
         websearch_to_tsquery('english', 'postgres index'),
         'StartSel=<mark>, StopSel=</mark>, MaxWords=18, MinWords=8'
       ) AS snippet
FROM articles
WHERE to_tsvector('english', body) @@ websearch_to_tsquery('english', 'postgres index');

-- Highlight every match instead of one fragment
SELECT ts_headline(
         'english',
         body,
         websearch_to_tsquery('english', 'index'),
         'HighlightAll=TRUE, StartSel=[, StopSel=]'
       ) AS full_highlight
FROM articles
WHERE id = 1;