I have repeatedly reviewed this issue, and I have never found the right answer.
Is it possible to do a MySQL search that returns ACTUAL exactly sorted results by relevance?
I am trying to create an ajax search form that makes suggestions when the user types in the input field, and did not find a suitable solution for this, using only pure MySQL queries. I know that there are search engines such as ElasticSearch, I want to know how to do this, only with a raw MySQL query.
I have a table of school subjects. There are less than 1200 lines, and that will never change. Let us do a basic FULLTEXT search, where the user starts typing "Bio".
Request ("Bio ...") - FULLTEXT BOOLEAN MODE
SELECT name, MATCH(name) AGAINST('bio*' IN BOOLEAN MODE) AS relevance
FROM subjects
WHERE MATCH(name) AGAINST('bio*' IN BOOLEAN MODE)
ORDER BY relevance DESC
LIMIT 10
results
name | relevance
--------------------------------------------------------
Biomechanics, Biomaterials and Prosthetics | 1
Applied Biology | 1
Behavioural Biology | 1
Cell Biology | 1
Applied Cell Biology | 1
Developmental/Reproductive Biology | 1
Developmental Biology | 1
Reproductive Biology | 1
Environmental Biology | 1
Marine/Freshwater Biology | 1
To show how bad these results are, here is a comparison with a simple LIKEquery that shows increasingly relevant results that were not shown:
Request ("Bio ...") - LIKE
SELECT id, name
WHERE name LIKE 'bio%'
ORDER BY name
results
name | relevance
--------------------------------------------------------
Bio-organic Chemistry | 1
Biochemical Engineering | 1
Biodiversity | 1
Bioengineering | 1
Biogeography | 1
Biological Chemistry | 1
Biological Sciences | 1
Biology | 1
Biomechanics, Biomaterials and Prosthetics | 1
Biometry | 1
And already you see how many items are not offered, even if they are more likely that the user will search.
However, the problem with use LIKEis how to search across multiple words and in the middle of type words FULLTEXT.
The main ordering I would like to implement is something like:
- First words starting with search query
- Second word starting with search query
- Words where the term is not at the beginning of words
- Everything is usually in alphabetical order, unless otherwise specified
, , MySQL ?