Posted on

Adding extra weight to AND results in an OR search

My Relevanssi engine has the AND operator enabled, with a fallback to OR when the search finds no matches. I’d like the search to display first the AND results and later the OR results.

For example, if I search for “wedding party”, I’d like the search to show first the entries matching both words and later the entries matching only “wedding” or only “party”.

Is it possible to configure or program a search like that?

What you’re asking for is pretty much what the OR search aims to do. It’s not strict, though, so if some post seems to be valuable even if it doesn’t have all the search terms, it will be high on the list, but most of the time if all search terms are good search terms, AND matches will be on the top.

If you really want to push it further, perhaps something like this with the relevanssi_match filter hook:

add_filter( 'relevanssi_match', 'rlv_and_boost' );
function rlv_and_boost( $match ) {
    global $rlv_and_database;
    $multi_term_boost = 5;
    if ( ! isset( $rlv_and_database[ $match->doc ] ) ) {
        $rlv_and_database[ $match->doc ] = true;
    } else {
        $match->weight *= $multi_term_boost;
    }
    return $match;
}

With this function in place, posts that match more than one search term will get a bonus. The more search terms the post matches, the bigger the bonus. You can adjust the boost factor until you get results you like.

This was asked here.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *