How to Filter Product Collection by Matching String in Magento 2

catalogsearchmagento2product-collection

We have loaded product collection based on category ID, we are further trying to filter the product collection result with query string.

We have tried :

Query string set and get is working fine with below code.

$query = $this->_queryFactory->create();
$query->setQueryText('Joust');
$query->getQueryText();

Add search filter is not working to my product collection.

use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection;

$collection->addSearchFilter($query->getQueryText());

Can any one help me on this query.

Best Answer

addSearchFilter does not do much if you don't apply the filter:

public function addSearchFilter($query)
{
    $this->queryText = trim($this->queryText . ' ' . $query);
    return $this;
}

What you need to do is to inject \Magento\Framework\Api\FilterBuilder, \Magento\Framework\Api\Search\SearchCriteriaBuilder as well as \Magento\Search\Api\SearchInterface and do the following:

$this->filterBuilder->setField('search_term');
$this->filterBuilder->setValue('Joust');
$this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());
$searchCriteria = $this->searchCriteriaBuilder->create();
$searchCriteria->setRequestName("search");
$this->searchResult = $this->searchInterface->search($searchCriteria);