ts_stat Surveys Lexeme Frequency
Feed ts_stat any query returning one tsvector column to rank lexemes by total occurrences and document coverage, hunting stop-word candidates.
Code
-- 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;How the snippet works
What runs here is SELECT / INSERT / CREATE — notes and ts_stat are the objects involved.
Mechanically, the statements are built from: COUNT aggregation; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; a PRIMARY KEY that enforces row identity.
Applying it
Point it at the notes table — the LIMIT keeps the probe cheap while you tune the predicates.
Statements that matter
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'));
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What relations does the SQL touch?
- The references are `notes`, `ts_stat`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.