Postgres:如何在生成的列中包含权重?
Postgres: How can I include weights in a generated column?
我有以下架构:
CREATE TABLE books (
title VARCHAR(255),
subtitle TEXT
);
添加没有权重的生成列工作正常:
ALTER TABLE books ADD COLUMN full_text_search TSVECTOR
GENERATED ALWAYS AS (to_tsvector('english',
coalesce(title, '') ||' '||
coalesce(subtitle, '')
)) STORED; -- ✅ Working
现在我想增加重量,但它不起作用:
ALTER TABLE books ADD COLUMN full_text_search_weighted TSVECTOR
GENERATED ALWAYS AS (to_tsvector('english',
setweight(coalesce(title, ''), 'A') ||' '||
setweight(coalesce(subtitle, ''), 'B')
)) STORED; -- ❌ Not working
有没有办法在 postgres 的生成列中包含权重?
复制Link:https://www.db-fiddle.com/f/4jyoMCicNSZpjMt4jFYoz5/1385
阅读 docs 后,我发现 setweight
正在返回 tsvector
。我不得不这样修改它:
ALTER TABLE books ADD COLUMN full_text_search_weighted TSVECTOR
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||' '||
setweight(to_tsvector('english', coalesce(subtitle, '')), 'B')
) STORED; -- ✅ Working
现在我们可以使用以下查询对结果进行排序:
SELECT ts_rank(full_text_search_weighted , plainto_tsquery('english', 'book')), title, subtitle
FROM "books"
WHERE full_text_search_weighted @@ plainto_tsquery('english', 'book')
ORDER BY ts_rank(full_text_search_weighted , plainto_tsquery('english', 'book')) DESC;
我有以下架构:
CREATE TABLE books (
title VARCHAR(255),
subtitle TEXT
);
添加没有权重的生成列工作正常:
ALTER TABLE books ADD COLUMN full_text_search TSVECTOR
GENERATED ALWAYS AS (to_tsvector('english',
coalesce(title, '') ||' '||
coalesce(subtitle, '')
)) STORED; -- ✅ Working
现在我想增加重量,但它不起作用:
ALTER TABLE books ADD COLUMN full_text_search_weighted TSVECTOR
GENERATED ALWAYS AS (to_tsvector('english',
setweight(coalesce(title, ''), 'A') ||' '||
setweight(coalesce(subtitle, ''), 'B')
)) STORED; -- ❌ Not working
有没有办法在 postgres 的生成列中包含权重?
复制Link:https://www.db-fiddle.com/f/4jyoMCicNSZpjMt4jFYoz5/1385
阅读 docs 后,我发现 setweight
正在返回 tsvector
。我不得不这样修改它:
ALTER TABLE books ADD COLUMN full_text_search_weighted TSVECTOR
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||' '||
setweight(to_tsvector('english', coalesce(subtitle, '')), 'B')
) STORED; -- ✅ Working
现在我们可以使用以下查询对结果进行排序:
SELECT ts_rank(full_text_search_weighted , plainto_tsquery('english', 'book')), title, subtitle
FROM "books"
WHERE full_text_search_weighted @@ plainto_tsquery('english', 'book')
ORDER BY ts_rank(full_text_search_weighted , plainto_tsquery('english', 'book')) DESC;