简体   繁体   中英

Best way to handle apostrophes when searching a MYSQL database

I am currently using

MATCH column_name AGAINST ( 'search_term' IN NATURAL LANGUAGE MODE);

where column_name is full text indexed. This works for the majority of cases but if the user searches for "items" I would like it to return both "short string items" AND "short string item's" from the DB (assuming both exist). Currently the way it is searching it treats the apostrophe as a letter rather than a word break such as a space. I saw some suggestions that I create another column of basically search friendly terms, in which case I could strip out the apostrophes but I was wondering if there was a better way, such as adjusting the collation to treat the apostrophe differently?

The solution that I ended up implementing first searches the fulltext indexed column in natural language mode and then also searches the column with a REPLACE and LIKE search:

SELECT
    *
FROM
    table
WHERE
    MATCH column_name AGAINST ("search_term" IN NATURAL LANGUAGE MODE)
    OR REPLACE (column_name, "'", "") LIKE "%search_term%";

This seems to return the proper results I am looking for.

For example if user searches for "items" , "item's" , "string items" , or "string items" it should return both "short string item's" and "short string items" (again assuming the exist in the DB).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM