Magento – Magento 2 Elastic search 6 Fulltext search with like

catalogsearchelasticsearchmagento-searchmagento2

I am trying to customize the default Magento 2 Elasticsearch 6. Right now the default Fulltext search is not giving that good result.

For Example I have product name like ADB12355 BBB, ADB3456 AAA, etc.

I am getting proper results either when adding ADB12355 BBB or ADB3456. The problem is I also want both the products if someone just search for ADB some kind of LIKE in mysql.

Also My configuration is correct and indexes are created but So far I am not able to find the correct place to customize.

Best Answer

Give a try.

Add plugin on the below class Builder.php by making a sample module.

File: app/code/Custom/LikeSearch/etc/di.xml

<type name="Magento\Elasticsearch\Model\Adapter\Index\Builder">
        <plugin name="custom_like_search_builder" type="Custom\LikeSearch\Plugin\Model\Adapter\Index\CustomBuilder"></plugin>
</type>

File: Custom\LikeSearch\Plugin\Model\Adapter\Index\CustomBuilder.php

<?php
namespace Custom\LikeSearch\Plugin\Model\Adapter\Index;

class CustomBuilder {

    public function afterBuild(\Magento\Elasticsearch\Model\Adapter\Index\Builder $subject, $result)
    {
        $likeToken = $this->getLikeTokenizer();
        $result['analysis']['tokenizer'] = $likeToken;
        $result['analysis']['filter']['trigrams_filter'] = [
            'type' => 'ngram',
            'min_gram' => 3,
            'max_gram' => 3
        ];
        $result['analysis']['analyzer']['my_analyzer'] = [
            'type' => 'custom',
            'tokenizer' => 'standard',
            'filter' => [
                'lowercase', 'trigrams_filter'
            ]
        ];
        return $result;
    }


    protected function getLikeTokenizer()
    {
        $tokenizer = [
            'default_tokenizer' => [
                'type' => 'ngram'
            ],
        ];
        return $tokenizer;
    }
}

Once done perform the php bin/magento indexer:reindex catalogsearch_fulltext

It should give results like below:

For search term, ADB gives results of below products names

ADB12355 BBB

ADB3456 AAA

For search term, GIT gives results of below products names

ABCGIT AAA

XYZGIT BBB