Search string by exact word in Mysql

后端 未结 8 1227
广开言路
广开言路 2021-01-18 07:11

I have a system that searches for company. I want that when a user searches for \"Demo\", all records that have \"Demo\" will be returned, like \"The Demo\", \"Demo Inc.\",

8条回答
  •  独厮守ぢ
    2021-01-18 07:44

    Try testing for a space at both sides:

    select * from table where company LIKE "Demo %" OR company LIKE "% Demo"
    

    However, as you have stated you need to make use of your indexes and anything with a leading wildcard % won't use the indexes.

    So, I think that you need to implement some kind of pre-processing on your search columns, something along the lines of:

    Pre-process your record names:

    • Use a stemming algorithm on all the record names in your database
    • Store the stemmed words in one table (stemmed_words)
    • Record the number of occurrences of the stemmed word against the record id (record_index)

    Then when the user searches:

    • Use a stemming algorithm on the search term words
    • Query your tables to find the result with the most frequently used stemmed word

    Example stemmed_words Table columns:

    id, stemmed_word  // Eg. 1 (auto generated), "Demo"
    

    Example record_index Table columns:

    record_id, stemmed_word_id, occurrence_count // Eg. 1 (auto generated), 1 (ID of "Demo" in stemmed_words table), 2 (2 occurrences)
    

    Here's a basic tutorial to get you started with stemming and word counts

提交回复
热议问题