Filter search results by site when using the same Apache Solr Index for multiple sites

Last updated on
30 April 2025

When you are using one Apache Solr instance to index multiple sites, you will have contents from all sites in the same index.

To ensure that the search results shows only contents from the current site, you can filter the Apache Solr index based on an attribute called 'Site Hash'.
This attribute is passed by the Apache Solr module every time the site is indexed and is stored together with the related pages.

For those who are familiar with GSA (Google Search Appliance), if you are looking for a "collection" behavior, this filter may be the answer.

Note: the site hash is generated based on the base_url by a function called "apachesolr_site_hash()" once and then it's stored in a variable in your database. So if your sites are sharing the base_url or the database, they will share the Site Hash.
In this case, you may need to add another filter (e.g.: Domain ID if using the Domain Access module).

In order to get the filter defined, you can use the following code (according to your Drupal core version):

Drupal 6

function mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
  $query->add_filter('hash', apachesolr_site_hash());
}

In case you are using the Apache Solr Multisite Search module, you may need the following code to avoid any impacts to the multisite search:

function mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
  if ($caller != "apachesolr_multisitesearch") {
    $query->add_filter('hash', apachesolr_site_hash());
    }
}

Drupal 7

The hook and method names were changed up for D7, so the code to get the same filter behavior should be:

function mymodule_apachesolr_query_alter($query) {
  $query->addFilter('hash', apachesolr_site_hash());
}

Deleting the index based on the Site Hash

You can also use the Site Hash to restrict the 'delete index' action in the administrative area to remove from the index only the pages related to the current site.

Use one of the following codes (according to your Drupal core version):

Drupal 6

function mymodule_apachesolr_delete_index_alter(&$query) {
  $query = 'hash:' . apachesolr_site_hash();
}

Drupal 7

function mymodule_apachesolr_delete_by_query(&$query) {
  $query = 'hash:' . apachesolr_site_hash();
}

Help improve this page

Page status: Not set

You can: