You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:54:25