实现说明
实际执行的是 SELECT / INSERT / CREATE——notes、ts_stat 是涉及的对象。
机制上由这些部分组成:用 COUNT 做聚合;ORDER BY 固定了输出顺序;LIMIT 限制返回行数;强制行身份的 PRIMARY KEY。
常见问题
这段 SQL 涉及哪些关系?
引用的是 notes、ts_stat。
核心语句
SELECT word, ndoc, nentry
FROM ts_stat('SELECT vector FROM notes')
ORDER BY nentry DESC, word
LIMIT 5;
SELECT count(*) AS distinct_lexemes
FROM ts_stat('SELECT vector FROM notes');
INSERT INTO notes VALUES
(1, to_tsvector('english', 'The quick brown fox jumps')),
(2, to_tsvector('english', 'quick fox and the lazy dog')),
(3, to_tsvector('english', 'fox outpaces the quick fox again'));
代码示例
-- ts_stat 分析词项统计:输入的查询必须只返回一个 tsvector 列
CREATE TABLE notes (
id integer PRIMARY KEY,
vector tsvector
);
INSERT INTO notes VALUES
(1, to_tsvector('english', 'The quick brown fox jumps')),
(2, to_tsvector('english', 'quick fox and the lazy dog')),
(3, to_tsvector('english', 'fox outpaces the quick fox again'));
-- ndoc:词出现在几个文档;nentry:出现总次数
SELECT word, ndoc, nentry
FROM ts_stat('SELECT vector FROM notes')
ORDER BY nentry DESC, word
LIMIT 5;
-- 全库不同词项(lexeme)总数:给词典覆盖与停用词清理定基准
SELECT count(*) AS distinct_lexemes
FROM ts_stat('SELECT vector FROM notes');
-- 词频审计的落点:ts_stat 给出高频词候选后,回到具体文档核对
-- 某个词的实际分布(例如 quick 出现在哪几行)
SELECT id, vector @@ to_tsquery('english', 'quick') AS mentions_quick
FROM notes
ORDER BY id;