Custom search_api query for categories block 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?
The following code does what we need.

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

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

    $q = search_api_query($indexName, $options);
    $q-&gt;range(0, 0);
    $q-&gt;fields([]);

    // Skip hook_search_api_query_alter().
    $result = $q-&gt;getIndex()-&gt;server()-&gt;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-&gt;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']-&gt;facet_counts-&gt;facet_fields-&gt;$propkey, with $propkey = 'im_' . str_replace(':', '$', $facetFieldName), but this only applies to search_api_solr.