Optimizing the ‘LIKE’ Search type in Magento version 1.9

Before going to optimize, please make sure that ‘Search Type’ is ‘Like’. It can be determined taking a look at:

System ->Configuration ->Catalog ->Search Type

Important: If we want to see any changes in frontend search results please make sure the search data is re-indexed.

Open the file:

..\core\Mage\CatalogSearch\Model\Resource\Fulltext.php

Inside the prepareResult( ), see the code from line 343. The logic which we are going to change is in that particular line. Take a look at that part:

$like[ ] = $helper->getCILike('s.data_index', $word, array('position' => 'any'));

Here we can notice the parameter array(‘position’=>’any’).This means that Magento default search will search the word in such a way that the particular position of word will be anywhere .In SQL terms, we can say it will be like: %searchterm%

We can change that to ‘start’ or ‘end’ as defined in the class:

switch ($options['position']) {
case 'any':
$value = '%' . $value . '%';
break;
case 'start':
$value = $value . '%';
break;
case 'end':
$value = '%' . $value;
break;
}

It is self explanatory and in SQL terms the ‘start’ and ‘end’ can be defined as searchterm% and %serachterm respectively.

In Fulltext.php, we can optimize the search further in such a way that AND logic can be used. See the code below:


if ($like) {
$likeCond = '(' . join(' OR ', $like) . ')';
}
It can be changed to:
if ($like) {
$likeCond = '(' . join(' AND ', $like) . ')';
}

So that the magento will search for items containing exactly all the terms.

Thank you for reading… Please share your valuable comments

This entry was posted in Magento Developer Notes. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *