Search string by exact word in Mysql

后端 未结 8 1171
广开言路
广开言路 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:29

    The best solution is create a fulltext index:

    create fulltext index `i_company` on `table`(`company`);
    

    Then you can search as:

    select * from `table` where match(company) against ('Demo');
    

    Read more about mysql full text search.

    Depending on your MySQL version, Full text index is available for MyISAM in version 5.5 or less, and is available for InnoDB since 5.6.

    0 讨论(0)
  • 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

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