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.

SqlData Fetching

Code

snippet
-- 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

FAQ

What objects does the SQL involve?
The references are `docs`.