Compound FULLTEXT index in MySQL

前端 未结 2 929
失恋的感觉
失恋的感觉 2021-01-20 15:02

I would like to make system whitch allows to search user messages, by specific user. assume having folowing table

create table messages(
  user_id int,
  mes         


        
2条回答
  •  情话喂你
    2021-01-20 15:25

    You should add a fulltext index on message and a regular index on user_id, and use the query:

    SELECT *
    FROM messages
    WHERE MATCH(message) AGAINST(@search_query)
    AND user_id = @user_id;
    

    You're right that you can't do option 3. But rather than trying to pick between 1 and 2, let MySQL do the work for you. MySQL will only use one of the two indexes, and will do a linear scan to complete the second filter, but it will estimate the effectiveness of each index and choose the optimal one.

    Note: only do this if you can afford the overhead of two indexes (slower insert/update/delete). Also, if you know that each user will only have a few messages, then yes it might make sense to use a simple index and do a regex in the application layer or something like that.

提交回复
热议问题