Magento – My Search result not showing relevance products properly Magento 2

catalogsearchmagento2search

When I search for any string, the relevant search results not working properly. Can you guys please look into the attached image?

I have enabled name and SKU for the search.

enter image description here

To reproduce this issue I have exported my products and import them in fresh Magento and still facing the same problem. so now there are no extensions and designs there.

My Magento version is 2.2.3

Best Answer

I had similar issue when I tried to use curl command with search query, it was giving me proper result and not in Magento listing. Try below code by overriding Block file.

di.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\CatalogSearch\Block\Result" type="Vendor\Module\Block\Result" />
</config>

Result.php

<?php 
namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;

class Result extends \Magento\CatalogSearch\Block\Result
{   
    protected function _construct()
    {
        $this->setModuleName('Magento_CatalogSearch');
        parent::_construct();
    }

    protected function _getProductCollection()
    {
        if (null === $this->productCollection) {
            $this->productCollection = $this->getListBlock()->getLoadedProductCollection();
        }
        try {
            $block = $this->getLayout()->createBlock('Magento\Catalog\Block\Product\ProductList\Toolbar');

            $dir = $this->getRequest()->getParam('product_list_dir');
            if(!isset($dir)){ $dir = 'DESC'; }
            if ($block->getCurrentOrder()) {
                switch ($block->getCurrentOrder()) {
                case 'relevance':
                    $this->productCollection->setOrder('relevance', $dir);
                    break;
                case 'name':
                    $this->productCollection->setOrder('name', $dir);
                    break;
                case 'price':
                    $this->productCollection->setOrder('price', $dir);
                    break;
                default:
                    $this->productCollection->setOrder('relevance', $dir);
                    break;
                }
            }
            return $this->productCollection;
        } catch (\Exception $e) {
            $this->logger->error('Fault Code: ' . trim($e->getCode()));
            $this->logger->error('Fault Reason: ' . trim($e->getMessage()) . "\n");
        }
    }
}
Related Topic