Search Optimisation in Magento 2

Here is the custom Builder Plugin to sort the Search results to get accurate results

<?php
namespace JJSearchCustomizationPluginModelAdapterIndex;


use MagentoFrameworkAppObjectManager;
use MagentoFrameworkAppRequestInterface;
use MagentoElasticsearchModelAdapterIndexBuilder;


class CustomBuilder
{
    public function afterBuild(Builder $subject, $result)
    {
        // Use ObjectManager to get request safely in plugin context
        $request = ObjectManager::getInstance()->get(RequestInterface::class);
        $searchQuery = trim($request->getParam('q') ?? '');
        $inputLength = strlen($searchQuery);



    if ($inputLength <= 3) {


    $result['analysis']['tokenizer']['default_tokenizer'] = [


        'type' => 'ngram',


        'min_gram' => 3,


        'max_gram' => 3 // Support up to 4-char substrings


    ];


    $result['analysis']['filter']['ngram_filter'] = [


        'type' => 'ngram',


        'min_gram' => 3,


        'max_gram' => 3


    ];


    $result['analysis']['analyzer']['my_analyzer'] = [


        'type' => 'custom',


        'tokenizer' => 'default_tokenizer',


        'filter' => ['lowercase', 'ngram_filter']


    ];


    $result['index']['max_ngram_diff'] = 0;


    } else {


        $result['analysis']['analyzer']['my_analyzer'] = [


            'type' => 'custom',


            'tokenizer' => 'keyword',


            'filter' => ['lowercase']


        ];


    }
 


        return $result;
    }
}


When this is used we get the best reaults from the search and it will be matched to the first or any combination of 3 letter or characters in the search keyword

Leave a comment

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