Magento 2 Custom Ajax Search Slow Compared to Default Search

ajaxcatalogsearchcollection;magento-2.1

I have created custom controller and custom page for quick order functionality.When I type in textbox product name it trigger ajax in custom controller to find a product name.In website around 90,000 products are there. So problem is when I search and trigger in custom controller it takes too much time to find product and when I use magento default search to find product it returns quick result of product list.So below is my ajax code and custom search code in controller.

$('#quick-search').keyup(function(){
            var search_text = jQuery("#quick-search").val();
            try {
                    jQuery.ajax({
                        url : '<?php echo $block->getUrl('quickorder/search/product') ?>',
                        dataType : 'json',
                        data: { 'search_text' :  search_text  },
                        type : 'post',
                        success : function(data) {
                            jQuery('.main-search-results').html(data.products);
                        }
                    });
                } catch (e) {
                }
        });

Controller/Search/Product.php

public function execute()
{

        $search_text = $this->getRequest()->getPost('search_text');

        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect(array('name'))->addAttributeToFilter('name',
        array('like' => $search_text.' %'),
        array('like' => '% '.$search_text.' %'), 
        array('like' => '% '.$search_text) 
        ));

        echo "<pre>";
        print_r($collection->getData());
       die();
}

Best Answer

To improve the performance, we need to set collection page start and records to show.

For example:

$collection->setPage(1, $numProducts);

Or

$collection->getSelect()->limit(20);
Related Topic