A site I am building has products that are indexed with search_api + facetapi + search_api_solr.

One of the indexed fields is a (hierarchical) taxonomy term reference. In case this is relevant, I am indexing the "parents all" version of this field.

On the frontpage I want to show some kind of "doormat navigation" showing the most important categories. Something similar for the footer. And for the sidebar maybe.

What I found so far is this article, Display facets on non-search pages

I am not really happy with the options there, and would much rather do a solution with custom code, where I have full control on everything.

The missing part is how to do the search_api query? I need a search_api or SOLR query that returns a list of category ids, each with the number of indexed products for this category.

How would I build such a query?

1 Answer 1


The following code does what we need.

   * @return int[]
  function getCountsByTid($indexName, $facetFieldName) {

    $options = [];
    $options['search_api_facets'][$facetFieldName] = [
      'field' => $facetFieldName,
      // No limit.
      'limit' => -1,
      'operator' => 'and',
      'min_count' => '1',
      'missing' => '0',

    $q = search_api_query($indexName, $options);
    $q->range(0, 0);

    // Skip hook_search_api_query_alter().
    $result = $q->getIndex()->server()->search($q);

    if (!isset($result['search_api_facets'][$facetFieldName])) {
      return [];

    $countsByTid = [];
    foreach ($result['search_api_facets'][$facetFieldName] as $item) {
      // The tid comes in a weird format.
      $tid = (int)substr($item['filter'], 1, -1);
      $count = $item['count'];
      $countsByTid[$tid] = $count;

    return $countsByTid;

Normally, the $options['search_api_facets'] would be set in search_api_facetapi_search_api_query_alter(). However, this adds ALL facets, instead of just a specific facet. Also it limits the number of facet counts to 50. See #12132878: search_api_facetapi pollutes and slows all queries

Instead we set this option manually, and then skip the $q->execute() that would trigger hook_search_api_query_alter().

SearchApiService classes always add quotes around the search values, which seems quite pointless to me.

We could get the raw tids from $result['search_api_solr_response']->facet_counts->facet_fields->$propkey, with $propkey = 'im_' . str_replace(':', '$', $facetFieldName), but this only applies to search_api_solr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.