PostgreSQL:查找最接近给定句子的句子
PostgreSQL: Find sentences closest to a given sentence
我有 table 张带有句子说明的图片。给定一个新句子,我想根据新句子与存储的旧句子的接近程度找到最匹配它的图像。
我知道我可以将 @@
运算符与 to_tsquery
一起使用,但 tsquery
接受特定词作为查询。
一个问题是我不知道如何将给定的句子转换成有意义的查询。句子可能有标点和数字。
但是,我也觉得我需要某种余弦相似性的东西,但我不知道如何从 PostgresQL 中得到它。我正在使用最新的 GA 版本,如果可以解决我的问题,我很乐意使用开发版本。
全文搜索 (FTS)
您可以使用 plainto_tsquery()
来 (per documentation) ...
produce tsquery
ignoring punctuation
SELECT plainto_tsquery('english', 'Sentence: with irrelevant words (and punctuation) in it.')
plainto_tsquery
------------------
'sentenc' & 'irrelev' & 'word' & 'punctuat'
像这样使用它:
SELECT *
FROM tbl
WHERE to_tsvector('english', sentence) @@ plainto_tsquery('english', 'My new sentence');
但这仍然相当严格,对相似性的容忍度非常有限。
八卦相似度
可能更适合搜索相似度,甚至在一定程度上克服错别字。
在最近邻搜索中安装附加模块pg_trgm
, create a GiST index and use the similarity operator %
:
基本上,在 sentence
上有一个 trigram GiST 索引:
-- SELECT set_limit(0.3); -- adjust tolerance if needed
SELECT *
FROM tbl
WHERE sentence % 'My new sentence'
ORDER BY sentence <-> 'My new sentence'
LIMIT 10;
更多:
- Finding similar strings with PostgreSQL quickly
- Finding similar posts with PostgreSQL
- Slow fulltext search for terms with high occurence
结合两者
您甚至可以结合 FTS 和三字母相似度:
这是一个很晚的答案,但我会添加以防万一有人遇到。如果你在单词的末尾加上“:*”,它会弹出类似的单词。
样本:
JS 自动完成 -> Codeigniter:
barcode = $this->input->get("term")。 ":*";
查询:
$ 查询 = 'select * from tablaneme where xx @@? LIMIT 15 ';
$ barcodequery = $ this-> db-> query ($query, array (explode("", $barcode)))) -> result_array();
我有 table 张带有句子说明的图片。给定一个新句子,我想根据新句子与存储的旧句子的接近程度找到最匹配它的图像。
我知道我可以将 @@
运算符与 to_tsquery
一起使用,但 tsquery
接受特定词作为查询。
一个问题是我不知道如何将给定的句子转换成有意义的查询。句子可能有标点和数字。
但是,我也觉得我需要某种余弦相似性的东西,但我不知道如何从 PostgresQL 中得到它。我正在使用最新的 GA 版本,如果可以解决我的问题,我很乐意使用开发版本。
全文搜索 (FTS)
您可以使用 plainto_tsquery()
来 (per documentation) ...
produce
tsquery
ignoring punctuation
SELECT plainto_tsquery('english', 'Sentence: with irrelevant words (and punctuation) in it.')
plainto_tsquery
------------------
'sentenc' & 'irrelev' & 'word' & 'punctuat'
像这样使用它:
SELECT *
FROM tbl
WHERE to_tsvector('english', sentence) @@ plainto_tsquery('english', 'My new sentence');
但这仍然相当严格,对相似性的容忍度非常有限。
八卦相似度
可能更适合搜索相似度,甚至在一定程度上克服错别字。
在最近邻搜索中安装附加模块pg_trgm
, create a GiST index and use the similarity operator %
:
基本上,在 sentence
上有一个 trigram GiST 索引:
-- SELECT set_limit(0.3); -- adjust tolerance if needed
SELECT *
FROM tbl
WHERE sentence % 'My new sentence'
ORDER BY sentence <-> 'My new sentence'
LIMIT 10;
更多:
- Finding similar strings with PostgreSQL quickly
- Finding similar posts with PostgreSQL
- Slow fulltext search for terms with high occurence
结合两者
您甚至可以结合 FTS 和三字母相似度:
这是一个很晚的答案,但我会添加以防万一有人遇到。如果你在单词的末尾加上“:*”,它会弹出类似的单词。 样本: JS 自动完成 -> Codeigniter:
barcode = $this->input->get("term")。 ":*";
查询: $ 查询 = 'select * from tablaneme where xx @@? LIMIT 15 '; $ barcodequery = $ this-> db-> query ($query, array (explode("", $barcode)))) -> result_array();