How to allow fulltext searching with hyphens in the search query

前端 未结 5 454
温柔的废话
温柔的废话 2020-12-03 14:57

I have keywords like \"some-or-other\" where the hyphens matter in the search through my mysql database. I\'m currently using the fulltext function.

Is there a way

5条回答
  •  伪装坚强ぢ
    2020-12-03 15:31

    Some people would suggest to use the following query:

    SELECT id 
    FROM texts
    WHERE MATCH(text) AGAINST('well-known' IN BOOLEAN MODE)
    HAVING text LIKE '%well-known%';
    

    But by that you need many variants depending on the used fulltext operators. Task: Realize a query like +well-known +(>35-hour <39-hour) working week*. Too complex!

    And do not forget the default len of ft_min_word_len so a search for up-to-date returns only date in your results.

    Trick

    Because of that I prefer a trick so constructions with HAVING etc aren't needed at all:

    1. Instead of adding the following text to your database table:

      "The Up-to-Date Sorcerer" is a well-known science fiction short story.
      copy the hyphen words without hypens to the end of the text inside a comment:
      "The Up-to-Date Sorcerer" is a well-known science fiction short story.

    2. If the users searches for up-to-date remove the hyphen in the sql query:
      MATCH(text) AGAINST('uptodate ' IN BOOLEAN MODE)

    By that you're user can find up-to-date as one word instead of getting all results that contain only date (because ft_min_word_len kills up and to).

    Of course before you echo the texts you should remove the comments.

    Advantages

    • the query is simpler
    • the user is able to use all fulltext operators as usual
    • the query is faster.
    • If a user searches for -well-known +science MySQL treats that as not include *well*, could include *known* and must include *science*. This isn't what the user expected. The trick solves that, too (as the sql query searches for -wellknown +science)

提交回复
热议问题