Setweight Weights Title Over Body
Tag title and body lexemes with setweight A and B, concatenate the tsvectors, and let ts_rank score title hits above body hits by default.
Code
-- setweight weights title over body:A 段 lexeme 在 ts_rank 默认权重下得分最高
-- ts_rank 默认权重 {0.1, 0.2, 0.4, 1.0} 依次对应 D, C, B, A
WITH docs AS (
SELECT
setweight(to_tsvector('english', 'postgres window functions'), 'A')
||
setweight(to_tsvector('english', 'window functions rank rows inside partitions'), 'B')
AS tsv
)
SELECT
-- 只命中 title 段的查询
ts_rank(tsv, to_tsquery('english', 'postgres')) AS title_hit,
-- 只命中 body 段的查询
ts_rank(tsv, to_tsquery('english', 'partitions')) AS body_hit
FROM docs;Inside the snippet
At its core this is a single SELECT statement against docs.
What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query.
Putting it to use
The docs table is the working surface here.
Interactive Tools for This Topic
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.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.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.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- What objects does the SQL involve?
- The references are `docs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.