Search code examples
mysqlsqldatabasefull-text-searchfull-text-indexing

Extract specific words from text field in mysql


I have a table that contains a text field, there is around 3 to 4 sentences in the field depending on the row.

Now, I am making an auto-complete html object, and I would like to start typing the beginning of a word and that the database return words that start with those letters from the database text field.

Example of a text field: I like fishsticks, fishhat are great too

in my auto-complete if I would type "fish" it would propose "fishsticks" and "fishhat"

Everything works but the query.

I can easily find the rows that contains a specific word but I can't extract only the word, not the full text.

select data_txt from mytable match(data_txt) against('fish', IN BOOLEAN MODE) limit 10

I know it is dirty, but I cannot rearrange the database.

Thank you for your help!

EDIT:

Here's what I got, thanks to Brent Worden, it is not clean but it works:

SELECT DISTINCT
SUBSTRING(data_txt, 
LOCATE('great', data_txt),
LOCATE(' ' , data_txt, LOCATE('great', data_txt)) - LOCATE('great', data_txt)
)
 FROM mytable WHERE data_txt LIKE '% great%'
LIMIT 10

any idea on how to avoid using the same LOCATE expression over and over?


Solution

  • Use LOCATE to find the occurrence of the word.

    Use LOCATE and the previous LOCATE return value to find the occurrence of the first space after the word.

    USE SUBSTR and the previous 2 LOCATE return values to extract the whole word.