[Part 1] Modifying Magento search

The problem:

Search in Magento
Searching for something...

Searching for something sometimes can be good, sometimes can be bad.
As you can see on the image above, search autocomplete shows you search suggestions based on what your customers previously searched. That is good thing though, but if your site is still new, autocomplete will show all results that are matching previously searched terms, some of them will be relevant to some product and some will have nothing in common with your products or site but some users typed them in search and even some words that you don’t want to see on your site.

*– Search terms can be managed from Administration panel (Catalog->Search Terms) and administrator can add, edit or remove search terms to make better search suggestions.

The solution (one of many):

To improve search suggestions we need to change the way search gets the results. Luckily Magento has model rewriting system, so we can save time and don’t need to reinvent the wheel.
First thing to do is to find the model that loads the collection with results before passing them to controller. In this case that model class is Mage_CatalogSearch_Model_Query and as the name suggests we can find this file in app/code/core/Mage/CatalogSearch/Model/Query.php and let’s examine the file. We are interested in getSuggestCollection() method:

  1. /**
  2.  * Retrieve collection of suggest queries
  3.  *
  4.  * @return Mage_CatalogSearch_Model_Resource_Query_Collection
  5.  */
  6. public function getSuggestCollection()
  7. {
  8. $collection = $this->getData('suggest_collection');
  9. if (is_null($collection)) {
  10. $collection = Mage::getResourceModel('catalogsearch/query_collection')
  11. ->setStoreId($this->getStoreId())
  12. ->setQueryFilter($this->getQueryText());
  13. $this->setData('suggest_collection', $collection);
  14. }
  15. return $collection;
  16. }

Here we see that Magento gets search result collection from suggestion collection and we need to change that.

In order not to change core files we need to rewrite this method. To do this first we need to create module under our namespace.
When rewriting core modules, it’s often good to give your module same name as the module that you are rewriting so later you or other developer can easily find this module. The core module can be found in core/Mage/CatalogSearch so we create our module in local/Mementia/CatalogSearch and because we are rewriting Mage_CatalogSearch module we need to add dependency to our module activation file, in this case : app/etc/modules/Mementia_CatalogSearch.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <config>
  3. <modules>
  4. <Mementia_CatalogSearch>
  5. <codePool>local</codePool>
  6. <active>true</active>
  7. <depends> <!-- Dependencies -->
  8. <Mage_CatalogSearch />
  9. </depends>
  10. </Mementia_CatalogSearch>
  11. </modules>
  12. </config>

Example of module activation file

Now, let’s write module configuration XML.
To tell Magento that we want to rewrite some model, we need to add following in config.xml of our module:

  1. <config>
  2. ..
  3. ..
  4. <global>
  5. ..
  6. ..
  7. <models>
  8. <catalogsearch>
  9. <rewrite>
  10. <query>Mementia_CatalogSearch_Model_CatalogSearch_Query</query>
  11. </rewrite>
  12. </catalogsearch>
  13. </models>
  14. </global>
  15. ..
  16. ..
  17. </config>

If you are beginner in Magento XML configurations can be very hard to understand, but it is quite simple. Here we are telling Magento that we want to rewrite Query model from CatalogSearch module and inside node we put our class that we want to rewrite. Our model class will be Mementia_CatalogSearch_Model_CatalogSearch_Query and we create Query.php file in Model/CatalogSearch/ folder.

  1. class Mementia_CatalogSearch_Model_CatalogSearch_Query extends Mage_CatalogSearch_Model_Query
  2. {
  3. }

Initial content of our Query.php

You notice from the code above that our model extends Mage > Core model because we need to override getSuggestCollection() method.
If we want our search suggestions to be based on product names, this method should look like this:

  1. public function getSuggestCollection()
  2. {
  3. $collection = $this->getData('suggest_collection');
  4. if (is_null($collection)) {
  5. $collection = Mage::getModel('catalog/product');
  6. Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection); //Filter disabled products
  7. $collection->getCollection() ->addAttributeToSelect('name')
  8. ->addAttributeToFilter('name', array('like' => '%'.$this->getQueryText().'%'))
  9. ->addAttributeToSort('name', 'ASC')
  10. ->setPageSize(10)
  11. ->addStoreFilter($this->getStoreId())
  12. ;
  13. /*
  14.   * Filter out of disable, out of stock and invisible products
  15.   *
  16.   *
  17.   */
  18. Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
  19. Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
  20. Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($collection);
  21. $this->setData('suggest_collection', $collection);
  22. }
  23. return $collection;
  24. }

Using this code we get collection with products that have product names that contain query string that customer has entered in search. Additionally I applied soring by name and results are limited to 10. Of course you can change filtering and sorting to your liking or even create own custom settings in Administration and allow administrator to manage results for search suggestions.
If you save the file and try to search you will get an error. We got this error because we modified collection and now the block that is responsible for generating HTML can’t find required variable. To fix this issue we need to find where this block is being generated. Open app/code/core/Mage/CatalogSearch/Block/Autocomplete.php and take look at getSuggestData() method. On this line of code:


We see that Autocomplete searches for “query_text” filed. This field does not exists in our modified collection. Now there are two possible solutions for this problem:

  1. Rewrite Mage_CatalogSearch_Block_Autocomplete::getSuggestData() method and this will allow us to make more customizations, or
  2. We can simply create alias field “query_text” in our collection and leave default Autocomplete block rendering.

First solution is very similar with model rewriting and as exercise you can try and solve for yourself :) .
Second solution is more interesting for me and hope for you too.
I’m guessing you all know how to create field alias in SQL, in Magento is also easy and simple. We can do this with addExpressionAttributeToSelect($alias, $expression, $attribute) method.
In our case that will this will look something like this:

  1. $collection->addExpressionAttributeToSelect('query_text', '{{name}}', 'name');
  2. public function getSuggestCollection()
  3. {
  4. $collection = $this->getData('suggest_collection');
  5. if (is_null($collection)) {
  6. $collection = Mage::getModel('catalog/product');
  7. Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection); //Filter disabled products
  8. $collection->getCollection() ->addAttributeToSelect('name')
  9. ->addAttributeToFilter('name', array('like' => '%'.$this->getQueryText().'%'))
  10. ->addExpressionAttributeToSelect('query_text', '{{name}}', 'name')
  11. ->addAttributeToSort('name', 'ASC')
  12. ->setPageSize(10)
  13. ->addStoreFilter($this->getStoreId())
  14. ;
  15. $this->setData('suggest_collection', $collection);
  16. }
  17. return $collection;
  18. }

Updated getSuggestCollection() method with alias.

Now if we save the file and try to search on the site we should get this:
Enhanced search in Magento
Now we are getting search suggestions from real product names.

If click on some search suggestion you will be taken to search results with that query string.

In Part 2 I will explain how to redirect customer when clicking on search suggestion directly to product instead of search page.
Stay tuned.