我有 GIN 索引列,使用gin_trgm_ops
.
我正在mad
使用相似性搜索该术语:
我得到:
god-made
made
man
man-made
may
但它遗漏了一些词,例如srimad
.
我想选择前 5 个 where ILIKE '%mad%'
or'mad%'
然后也是前五个 trigrams 并组合结果。
实施解决方案后:
我的 SQL 查询和解释:
EXPLAIN (COSTS OFF)
(SELECT word_similarity('mad',word), word FROM articles_words WHERE word ILIKE '%mad%' ORDER BY word_similarity('mad',word) DESC LIMIT 10)
UNION
(SELECT word_similarity('mad',word),word FROM articles_words WHERE word_similarity('mad',word) > 0.4 ORDER BY word_similarity('mad',word) DESC, word LIMIT 10)
"QUERY PLAN"
"HashAggregate"
" Group Key: (word_similarity('mad'::text, articles_words.word)), articles_words.word"
" -> Append"
" -> Limit"
" -> Sort"
" Sort Key: (word_similarity('mad'::text, articles_words.word)) DESC"
" -> Bitmap Heap Scan on articles_words"
" Recheck Cond: (word ~~* '%mad%'::text)"
" -> Bitmap Index Scan on words_idx"
" Index Cond: (word ~~* '%mad%'::text)"
" -> Limit"
" -> Sort"
" Sort Key: (word_similarity('mad'::text, articles_words_1.word)) DESC, articles_words_1.word"
" -> Seq Scan on articles_words articles_words_1"
" Filter: (word_similarity('mad'::text, word) > '0.40000000000000002'::double precision)"
还有关于 UNION 的问题:
第一个查询项目:
(SELECT word_similarity('mad',word), word FROM articles_words WHERE word ILIKE '%mad%' ORDER BY word_similarity('mad',word) DESC LIMIT 10)
0.75 man-made
0.75 made
0.75 god-made
0.5 srimad-bhagavatam
0.5 srimad
第二个查询项:
(SELECT word_similarity('mad',word),word FROM articles_words WHERE word_similarity('mad',word) > 0.4 ORDER BY word_similarity('mad',word) DESC, word LIMIT 10)
0.75 god-made
0.75 made
0.75 man-made
0.5 anti-material
0.5 half-man
0.5 magistrate
0.5 maha
0.5 maha-mantra
0.5 mahaprabhu
0.5 maharaja
我想要结果为:
0.75 man-made
0.75 made
0.75 god-made
0.5 srimad-bhagavatam
0.5 srimad
0.5 anti-material
0.5 half-man
0.5 magistrate
0.5 maha
0.5 maha-mantra
0.5 mahaprabhu
0.5 maharaja
但我按以下顺序排列:
0.75 god-made
0.5 maha
0.5 anti-material
0.5 mahaprabhu
0.5 maharaja
0.5 srimad
0.5 half-man
0.5 magistrate
0.5 srimad-bhagavatam
0.75 made
0.75 man-made
0.5 maha-mantra