sql - mysql search words in text column sorted by # world matched -
problem:
the text input 3 or 4 words, want show field contain @ least 1 of these words.
for example if words "alpha bravo charlie delta" want allow results
charlie bravo name charlie alphaness alpha , delta addeltas bravo delta , alpha , bravo bbbbravoooo charlieeeee
no problem till here, use query:
select * subject name '%alpha%' or name '%bravo%' or name '%charlie%' or name '%delta%
but want show results in particular order, results more relevant when
- more words occurance more relevante result should be, "charlie bravo" shows before "bravo"
i found solution that
select * , ( (char_length(col1) - char_length(replace(col1,'alpha',''))) / char_length('alpha') + (char_length(col1) - char_length(replace(col1,'bravo',''))) / char_length('bravo') + (char_length(col1) - char_length(replace(col1,'delta',''))) / char_length('delta') + (char_length(col1) - char_length(replace(col1,'charlie',''))) / char_length('charlie') ) occurances yourtable order occurances desc
but need other order rules:
- if record begin searched word more relevant es."alpha and..."
- if word in record begin searched word more relevant es."what alphaness"
- searched word inside record es."addeltas"
i find solution these order problem but, how combine both?
select id, name subjects name '%alpha%' order name 'alpha%' desc, ifnull(nullif(instr(name, ' alpha'), 0), 99999), ifnull(nullif(instr(name, 'alpha'), 0), 99999), name;
so conclude if search "alpha bravo" results should be:
delta , alpha , bravo (contain both words first) alpha , delta (begin first word searched) bravo (begin second word searched) alphaness (has first word searched begin of word) charlie bravo (has second word searched begin of word) bbbbravoooo charlieeee (has second word searched inside)
ps need case insensitive , without distinction accented letters òàùèìé è = e
looks need stored function calculate weight used in ordering.
e.g. weight 0.
if word found in field weight+=1000
if word beginning of record weight+=100
if word beginning of word weight+=10
weight+=(amount of words - word index) order of word
so passing search "alpha bravo" returns
1000+10+1 + 1000+10 delta , alpha , bravo (contain both words first) 1000+100+1 alpha , delta (begin first word searched) 1000+100 bravo (begin second word searched) 1000+10+1 alphaness (has first word searched begin of word) 1000+10 charlie bravo (has second word searched begin of word) 1000 bbbbravoooo charlieeee (has second word searched inside)
Comments
Post a Comment