How can I manipulate MySQL fulltext search relevance to make one field more 'valuable' than another?

前端 未结 9 1685
灰色年华
灰色年华 2020-11-28 02:55

Suppose I have two columns, keywords and content. I have a fulltext index across both. I want a row with foo in the keywords to have more relevance than a row with foo in th

相关标签:
9条回答
  • 2020-11-28 03:27

    I needed something similar and used the OP's solution, but I noticed that fulltext doesn't match partial words. So if 'watermelon' is in Keywords or Content as part of a word (like watermelonsalesmanager) it doesn't MATCH and is not included in the results because of the WHERE MATCH. So I fooled around a bit and tweaked the OP's query to this:

    SELECT *, 
    CASE WHEN Keywords LIKE '%watermelon%' THEN 1 ELSE 0 END AS keywordmatch, 
    CASE WHEN Content LIKE '%watermelon%' THEN 1 ELSE 0 END AS contentmatch,
    MATCH (Title, Keywords, Content) AGAINST ('watermelon') AS relevance 
    FROM about_data  
    WHERE (Keywords LIKE '%watermelon%' OR 
      Title LIKE '%watermelon%' OR 
      MATCH(Title, Keywords, Content) AGAINST ('watermelon' IN BOOLEAN MODE)) 
    HAVING (keywordmatch > 0 OR contentmatch > 0 OR relevance > 0)  
    ORDER BY keywordmatch DESC, contentmatch DESC, relevance DESC
    

    Hope this helps.

    0 讨论(0)
  • 2020-11-28 03:29

    Simpler version using only 2 fulltext indexes (credits taken from @mintywalker):

    SELECT id, 
       MATCH (`content_ft`) AGAINST ('keyword*' IN BOOLEAN MODE) AS relevance1,  
       MATCH (`title_ft`) AGAINST ('keyword*' IN BOOLEAN MODE) AS relevance2
    FROM search_table
    HAVING (relevance1 + relevance2) > 0
    ORDER BY (relevance1 * 1.5) + (relevance2) DESC
    LIMIT 0, 1000;
    

    This will search both full indexed columns against the keyword and select matched relevance into two separate columns. We will exclude items with no match (relevance1 and relevance2 are both zero) and reorder results by increased weight of content_ft column. We don't need composite fulltext index.

    0 讨论(0)
  • 2020-11-28 03:34

    As far as I know, this isn't supported with MySQL fulltext search, but you can achieve the effect by somehow repeating that word several times in the keyword field. Instead of having keywords "foo bar", have "foo bar foo bar foo bar", that way both foo and bar are equally important within the keywords column, and since they appear several times they become more relevant to mysql.

    We use this on our site and it works.

    0 讨论(0)
提交回复
热议问题