Drupal Solr: How to add custom filter in solr

Problem: How to add our own custom filter in drupal solr index.

Requirement:

  1. Drupal 7.x
  2. Search API Solr Search
  3. Solr server should enabled and running.

Solution:

By default Search API solr has very less filters like Bundle Filter, Node filter, Node Access etc. Many times we require our custom filter base on some value or field. Like in this post,my requirement is to exclude those articles which title include "Eating Fish" words.

So Lets start.

Step 1: Create on custom module solr_filter and in solr_filter.module file implement hook_search_api_alter_callback_info.

/**
 * Implement hook_search_api_alter_callback_info
 * @return type
 */
function solr_filter_search_api_alter_callback_info() {
    $callbacks['exclude_article_1'] = array(
        'name' => t('Exclude Article'),
        'description' => t('Exclude article which title include words "Eating Fish"'),
        'class' => 'SearchApiExcludeSomeNodes',
    );
    return $callbacks;
}

/**
 * Class SearchApiExcludeSomeNodes
 */
class SearchApiExcludeSomeNodes extends SearchApiAbstractAlterCallback {

    /**
     * 
     * @param SearchApiIndex $index
     * @return type
     */
    public function supportsIndex(SearchApiIndex $index) {
        return $index->getEntityType() === 'node';
    }

    /**
     * 
     * @param array $items
     */
    public function alterItems(array &$items) {
        foreach ($items as $k => $item) {

            if ($item->type == 'article') {  // Apply only for article content type
                if (strpos($item->title, 'Eating Fish') !== false) {
                    unset($items[$k]);
                }
            }
        }
    }
}



Step 2: Enable the module and clear the cache now you will see our custom filter in filter list on index filters.

Step 3: Now check this filter and you will see, in solr result those article will come which has not "Eating Fish" word in title.


Comments

Popular posts from this blog

Install PHP 7.x on Linux Mint 18

Install Redis on ubuntu 14.04, 14.10, 15.04, 16.04 etc

Disable Drupal 8 caching during development