Posted on

Exact matches for short search terms

Is is possible to set Relevanssi in a way that it would return only perfect matches for queries up to 3 characters, but any words that starts with the queried term if it has 4 characters or more?

Originally asked here

Yes, but it requires a bit of coding. With the latest version (free 4.8.2, Premium 2.10.2), this is likely the easiest solution:

add_filter( 'relevanssi_term_where', 'rlv_three_exact_four_fuzzy' );
function rlv_three_exact_four_fuzzy( $where ) {
    if ( preg_match( "/'.*?%'/", $where, $matches ) ) {
        if ( relevanssi_strlen( $matches[0] ) <= 6 ) { // 3 characters + ', ', and %
            $where = '(relevanssi.term = ' . str_replace( '%', '', $matches[0] ) . ')';
        }
    }
    return $where;
}

Add this to theme functions.php and set Relevanssi to use partial matching in the searching settings. Now searches with search terms that are at most three characters long will use exact matching.

Next version of Relevanssi (likely 4.8.3 and 2.10.3) will add a new parameter to this filter hook, which will simplify this to:

add_filter( 'relevanssi_term_where', 'rlv_three_exact_four_fuzzy', 10, 2 );
function rlv_three_exact_four_fuzzy( $where, $term ) {
    if ( relevanssi_strlen( $term ) <= 3 ) {
        $where = "(relevanssi.term = '$term')";
    }
    return $where;
}

The way this works is simple. The relevanssi_term_where filter hook lets you adjust the part of the MySQL query that includes the search term. If the search term is short, instead of doing the default partial search query, the function replaces that with the exact match query (relevanssi.term = 'term').

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.