1:创建 tsvector 的列/视图/物化视图。
CREATE MATERIALIZED VIEW unique_lexeme AS
SELECT word FROM ts_stat(
'SELECT to_tsvector('simple', post.title) ||
to_tsvector('simple', post.content) ||
to_tsvector('simple', author.name) ||
to_tsvector('simple', coalesce(string_agg(tag.name, ' ')))
FROM post
JOIN author ON author.id = post.author_id
JOIN posts_tags ON posts_tags.post_id = posts_tags.tag_id
JOIN tag ON tag.id = posts_tags.tag_id
GROUP BY post.id, author.id');
2:使用三元组从该列中选择
SELECT word
FROM unique_lexeme
WHERE similarity(word, 'samething') > 0.5
ORDER BY word <-> 'samething';
(在本站搜索:拼写错误
http://rachbelaid.com/postgres-full-text-search-is-good-enough/)
3:当你找到单词时,用它们对结果进行排名。使用子查询:
SELECT word WHEREsimilarity(word, 'samething') > 0.5 ORDER BY word <-> 'samething';
或者,您可以只创建一个子查询来检查相似性。
补充:
索引 tsvector 列。
同时刷新物化视图(http://www.postgresqltutorial.com/postgresql-materialized-views/)。
使用触发器更新列(https://www.postgresql.org/docs/9.0/textsearch-features.html)