用PostgreSQL查找类似的帖子

时间:2013-07-24 18:37:57

标签: postgresql search pattern-matching

我有一张表posts

CREATE TABLE posts (
  id serial primary key,
  content text
);

当用户提交帖子时,如何将他的帖子与其他帖子进行比较并找到类似帖子? 我正在寻找像StackOverflow那样的“类似问题”。

2 个答案:

答案 0 :(得分:5)

虽然Text Search是一个选项,但它主要不适用于此类搜索。典型的用例是基于字典和词干来查找文档中的单词,而不是比较整个文档。

我确信StackOverflow已经为相似性搜索添加了一些智能,因为这不是一件小事

您可以使用similarity function and operators模块提供的pg_trgm获得中途不错的结果:

SELECT content, similarity(content, 'grand new title asking foo') AS sim_score
FROM   posts
WHERE  content  % 'grand new title asking foo'
ORDER  BY 2 DESC, content;

请确保content {{1}}为此。

但你可能还需要做更多。在识别新内容中的关键字后,您可以将其与文本搜索结合使用。

答案 1 :(得分:0)

您需要在Postgres中使用全文搜索。

http://www.postgresql.org/docs/9.1/static/textsearch-intro.html