Magento – Magento2: FullText Search Programatically

catalogsearchfulltextmagento2search

Does anyone know how to run a search using FullText and a string?

I'm trying to inject

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

and do

$this->_fulltext->addSearchFilter("wat");
$products = $this->_fulltext->getItems();

but the result is always empty.

Any idea?

Best Answer

Try below code its work for me:

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

//Create Temp table for store result 
$temporaryStorage = $this->temporaryStorageFactory->create();
$table = $temporaryStorage->storeApiDocuments($this->searchResult->getItems());        
$productCollection = $this->_productCollectionFactory->create();
$productCollection->getSelect()->joinInner(
       ['search_result' => $table->getName()],
       'e.entity_id = search_result.' . TemporaryStorage::FIELD_ENTITY_ID,
       []
);


// Classes need to load

use Magento\Search\Api\SearchInterface;  //$this->searchInterface
use Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory; // $this->temporaryStorageFactory
use Magento\Framework\Api\Search\SearchCriteriaBuilder; // $this->searchCriteriaBuilder
use Magento\Framework\Search\Adapter\Mysql\TemporaryStorage; //TemporaryStorage
Related Topic