使用子表达式的MySQL布尔全文搜索

时间:2015-12-30 17:28:39

标签: mysql database full-text-search information-retrieval

我想在MySQL中编写一个布尔全文搜索查询。但我希望按此顺序得到结果:

Exact Matches> Including all the words> Including some of the words

>表示更高。)

通过以下查询,我得到更高的精确匹配:

SELECT *, MATCH(name,description,address) 
AGAINST('>("word1 word2 word3") <(word1 word2 word3)' IN BOOLEAN MODE) 
AS score FROM samples WHERE MATCH(name,description,address) 
AGAINST('>("word1 word2 word3") <(word1 word2 word3)' IN BOOLEAN MODE) ORDER BY score DESC

通过以下查询,我得到的文档包含的所有单词都高于包含查询某些部分的单词:

SELECT *, MATCH(name,description,address) 
AGAINST('>(+word1 +word2 +word3) <(word1 word2 word3)' IN BOOLEAN MODE) 
AS score FROM samples WHERE MATCH(name,description,address) 
AGAINST('>(+word1 +word2 +word3) <(word1 word2 word3)' IN BOOLEAN MODE) ORDER BY score DESC  

但我想结合这两个查询。这是迄今为止我遇到的最好的,但我没有得到我想要的结果。

SELECT *, MATCH(name,description,address) 
AGAINST('>("word1 word2 word3") <(>(+word1 +word2 +word3) <(word1 word2 word3))' IN BOOLEAN MODE) 
AS score FROM samples WHERE MATCH(name,description,address) 
AGAINST('>("word1 word2 word3") <(>(+word1 +word2 +word3) <(word1 word2 word3))' IN BOOLEAN MODE) 
ORDER BY score DESC

没有UNIONs有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

( SELECT *,
         1 AS sort_order,       -- top priority to exact match
         1.0 AS extra_ordering
      ... WHERE txt = 'aaaa bbbb cccc' )
UNION ALL
( SELECT *,
         2 AS sort_order,      -- next to all words exist
         MATCH(txt) AGAINST("+aaaa +bbbb +cccc" IN BOOLEAN MODE)
      ... WHERE MATCH(txt) AGAINST("+aaaa +bbbb +cccc" IN BOOLEAN MODE)
UNION ALL
( SELECT *,
         3 AS sort_order,      -- finally "any" words
         MATCH(txt) AGAINST("aaaa bbbb cccc" IN BOOLEAN MODE)
      ... WHERE MATCH(txt) AGAINST("aaaa bbbb cccc" IN BOOLEAN MODE)
ORDER BY sort_order ASC, extra_ordering DESC
LIMIT 1;  -- to get the 'best'

答案 1 :(得分:1)

这会有用吗?

  SELECT *,
         MATCH (name,description,address) 
           AGAINST ('"word1 word2 word3"' IN BOOLEAN MODE) score_exact,
         MATCH (name,description,address) 
           AGAINST ('+word1 +word2 +word3' IN BOOLEAN MODE) score_all,
         MATCH (name,description,address) 
           AGAINST ('word1 word2 word3' IN BOOLEAN MODE) score_some
    FROM samples
   WHERE MATCH (name,description,address) 
           AGAINST ('word1 word2 word3' IN BOOLEAN MODE)
ORDER BY score_exact DESC, score_all DESC, score_some DESC