简体   繁体   中英

Force “implied AND” instead of “implied OR” in mysql boolean match?

In mysql boolean match, if no operators are present, OR is implied. If you want AND, you need to add + to each keywords.

So query "word1 word2" is equal to "word1 OR word2", "+word1 +word2" is equal to "word1 AND word2"

I don't want users to have to enter + before each keyword, what are my options?

Suggested option 1: Is there something in my.conf I can change to set the defaults (I didn't find anything)

Suggested option 2: parse the query and manually add + to each word. Any simple code for this you can share?

The problem with this is if the user adds "quotes" or operators (+-*<>) etc. it breaks my parsing code.

I went with second suggestions on my site.

Simple one liner to add + before each word if you deal only with words, (not with quoted strings)

$q = implode(' ', array_map(create_function('$a', 'return "+".$a;'), preg_split('`\\s+`', $q))))

or even simpler regex replace doing the same:

echo preg_replace('`(\\W|^)\\w`', '\\1+\\2', $q);

if you have not only single words but also quoted phrases to search this should add + before each single unquoted word and each quoted string

echo preg_replace('`(\\s|^)(\\w|"[^"]+")`', '\\1+\\2', $q);

Not sure what you mean, but here is an example of how you can add + in front of each word.

$s = "a string with several words in it";
$words = preg_split('/\s+/',$s,null,PREG_SPLIT_NO_EMPTY);
if (count($words)) {
    $str = '+' . implode(' +',$words);
}

There is no way of changing the behavior of full-text matching in boolean mode with no operators, short of editing the source. You'll have to use option 2 (as the others show) in some form or another. Just be careful how you do it, if the search expression comes from the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM