首页 > 解决方案 > 在全文搜索中计算 ts_stat 计数的唯一条目

问题描述

我正在努力使用 ts_stat 来获取表中标签的唯一出现次数并按最高计数对它们进行排序。我需要的是只计算每个条目一次,以便只计算唯一条目。我尝试了 group by 和 distinct,但没有什么对我有用。

例如表

user_id | tags         | post_date
===================================
2       | dog cat      | 1580049400
2       | dog          | 1580039400
3       | dog          | 1580038400
3       | dog dog cat  | 1580058400
4       | dog horse    | 1580028400

这是当前查询

SELECT word, ndoc, nentry
FROM   ts_stat($$SELECT to_tsvector('simple', tags) FROM tags WHERE post_date > 1580018400$$) 
ORDER  BY ndoc DESC
LIMIT  10;

现在这将产生

word | ndoc | nentry
====================
dog  | 5    | 6
cat  | 2    | 2
horse| 1    | 1

我要寻找的结果是唯一计数,因此即使在 post_date 条件中指出的某个日期之后他们有 > 1 个条目(这可能无关紧要),也没有 1 个用户可以计数超过一次。如下所示。

word | total_count_per_user
===========================
dog  | 3    (because there are 3 unique users with this term)
cat  | 2    (because there are 2 unique users with this term)
horse| 1    (because there are 1 unique users with this term)

更新:我更改了列名以反映输出。关键是无论用户输入一个单词多少次。它只需要每个用户的唯一计数。例如,如果该场景中的用户在文本中创建了 100 个带有 dog 的条目,则该用户只会计算 dog 1 次,而不是 100 个 dog。

标签: sqlpostgresql

解决方案


如果我的观点正确,您可以在 DISTINCT 值上使用 COUNT。示例查询如下 -

SELECT tags,COUNT(DISTINCT user_id)
FROM your_table
GROUP BY tags

推荐阅读