Skip to content

How override the searched products in magento 2.4.4

I want to override the search products on front end and also want to access the search query.
For eg If customer search the term “Men Jackets”. In back end i have setup some values which i will check if Search By Name OR is enabled then it should show the standard magento 2 result but AND is enabled it should show according to the query AND.
My Admin Settings are shown as below
enter image description here

Is there anyway where i can access the term and also override the search products results.

Tried this solution its not working at all

  <?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoElasticsearchSearchAdapterQueryBuilderMatchQuery" type="VMSearchAdapterQueryBuilderMatchQuery" />
</config>



<?php
namespace VMSearchAdapterQueryBuilder;

use MagentoElasticsearchModelAdapterFieldMapperProductAttributeProvider;
use MagentoElasticsearchModelAdapterFieldMapperProductFieldProviderFieldTypeResolverInterface as TypeResolver;
use MagentoElasticsearchModelConfig;
use MagentoElasticsearchSearchAdapterQueryValueTransformerPool;
use MagentoFrameworkSearchRequestQueryBoolExpression;
use MagentoFrameworkSearchRequestQueryInterface as RequestQueryInterface;
use MagentoElasticsearchModelAdapterFieldMapperInterface;
use MagentoFrameworkSearchAdapterPreprocessorPreprocessorInterface;

/**
 * Extend Builder for match query. 
 * See https://magento.stackexchange.com/questions/192718/how-do-i-change-magento-2-search-from-or-logic-to-and for the full discussuon
 */
class MatchQuery extends MagentoElasticsearchSearchAdapterQueryBuilderMatchQuery
{
    /**
     * Elasticsearch condition for case when query must not appear in the matching documents.
     */
    const QUERY_CONDITION_MUST_NOT = 'must_not';

    /**
     * @var FieldMapperInterface
     */
    private $fieldMapper;

    /**
     * @var AttributeProvider
     */
    private $attributeProvider;

    /**
     * @var TypeResolver
     */
    private $fieldTypeResolver;

    /**
     * @var ValueTransformerPool
     */
    private $valueTransformerPool;
    /**
     * @var Config
     */
    private $config;

    /**
     * @param FieldMapperInterface $fieldMapper
     * @param AttributeProvider $attributeProvider
     * @param TypeResolver $fieldTypeResolver
     * @param ValueTransformerPool $valueTransformerPool
     * @param Config $config
     */
    public function __construct(
        FieldMapperInterface $fieldMapper,
        AttributeProvider $attributeProvider,
        TypeResolver $fieldTypeResolver,
        ValueTransformerPool $valueTransformerPool,
        Config $config
    ) {
        $this->fieldMapper = $fieldMapper;
        $this->attributeProvider = $attributeProvider;
        $this->fieldTypeResolver = $fieldTypeResolver;
        $this->valueTransformerPool = $valueTransformerPool;
        $this->config = $config;
        parent::__construct($fieldMapper, $attributeProvider, $fieldTypeResolver, $valueTransformerPool, $config);
    }

    /**
     * Creates valid ElasticSearch search conditions from Match queries.
     *
     * The purpose of this method is to create a structure which represents valid search query
     * for a full-text search.
     * It sets search query condition, the search query itself, and sets the search query boost.
     *
     * The search query boost is an optional in the search query and therefore it will be set to 1 by default
     * if none passed with a match query.
     *
     * @param array $matches
     * @param array $queryValue
     * @return array
     */
    protected function buildQueries(array $matches, array $queryValue)
    {
        MagentoFrameworkAppObjectManager::getInstance()->get('PsrLogLoggerInterface')->info('msg to print');

        $conditions = 

        // Checking for quoted phrase "phrase test", trim escaped surrounding quotes if found
        $count = 0;
        $value = preg_replace('#^"(.*)"$#m', '$1', $queryValue['value'], -1, $count);
        $condition = ($count) ? 'match_phrase' : 'match';

        $transformedTypes = [];
        foreach ($matches as $match) {
            $resolvedField = $this->fieldMapper->getFieldName(
                $match['field'],
                ['type' => FieldMapperInterface::TYPE_QUERY]
            );

            $attributeAdapter = $this->attributeProvider->getByAttributeCode($resolvedField);
            $fieldType = $this->fieldTypeResolver->getFieldType($attributeAdapter);
            $valueTransformer = $this->valueTransformerPool->get($fieldType ?? 'text');
            $valueTransformerHash = spl_object_hash($valueTransformer);
            if (!isset($transformedTypes[$valueTransformerHash])) {
                $transformedTypes[$valueTransformerHash] = $valueTransformer->transform($value);
            }
            $transformedValue = $transformedTypes[$valueTransformerHash];
            if (null === $transformedValue) {
                //Value is incompatible with this field type.
                continue;
            }
            $matchCondition = $match['matchCondition'] ?? $condition;

            if($matchCondition != 'match_phrase_prefix'){
                $field = [
                    'query' => $transformedValue,
                    'boost' => $match['boost'] ?? 1,
                    'operator' => 'and'
                ];
            } else {
                $field = [
                    'query' => $transformedValue,
                    'boost' => $match['boost'] ?? 1
                ];
            }
            $conditions[] = [
                'condition' => $queryValue['condition'],
                'body' => [
                    $matchCondition => [
                        $resolvedField => $field,
                    ],
                ],
            ];

        }

        echo "<pre>";
        print_r($conditions);
//MagentoFrameworkAppObjectManager::getInstance()->get('PsrLogLoggerInterface')->debug(print_r($conditions));

        return $conditions;
    }
}

Already Tried
I need to override the search term
Magento 2 Change Default OrderBy Parameter for Search Results

Plz help me to find the solution
Thanks in Advance 🙂