如何用PostgreSQL的ts_vector函数统计列中指定单词的出现次数?
PostgreSQL统计text_col列中"test"单词出现次数的方案
单条记录逐行统计
如果需要为表中每一行单独计算text_col列里"test"的出现次数,可使用以下SQL:
SELECT id, text_col, (SELECT count(*) FROM unnest(to_tsvector('simple', text_col)) AS token WHERE token.lexeme = 'test') AS test_count FROM your_table;
- 用
'simple'分词配置是为了精确匹配原词,不会把"testing"、"tested"这类变形词统计进去;如果需要包含词干匹配(把相关变形词都归为"test"统计),将'simple'替换为'english'即可。 - 若
text_col存在NULL值,可通过coalesce确保对应计数为0:SELECT id, text_col, coalesce((SELECT count(*) FROM unnest(to_tsvector('simple', text_col)) AS token WHERE token.lexeme = 'test'), 0) AS test_count FROM your_table;
全表总次数统计
如果要统计整个表中"test"出现的总次数,基于逐行统计的结果嵌套求和即可:
SELECT sum(test_count) AS total_test_count FROM ( SELECT (SELECT count(*) FROM unnest(to_tsvector('simple', text_col)) AS token WHERE token.lexeme = 'test') AS test_count FROM your_table ) AS subquery;
内容的提问来源于stack exchange,提问作者Pravin kumar
相关产品推荐
相关产品推荐

