We can use a facet query in addition to the normal query to get counts with respect to the facet query. The counts are not affected by the main query and filter queries can be excluded from it. Let's see the code to get counts of facets where genre
is fantasy
and also see an example of excluding a filter query.
Let us first create a query to select all books in our index.
$query->setQuery('cat:book');
Create a filter query for books that are in stock and tag it.
$fquery = $query->createFilterQuery('inStock'); $fquery->setQuery('inStock:true'); $fquery->addTag('inStockTag');
Get the facetset
component from our query using the following code:
$facetset = $query->getFacetSet();
Create a facet by query to count the number of books of a particular genre. Also, exclude the filter query we added earlier.
$facetqry = $facetset->createFacetQuery('genreFantasy'); $facetqry->setQuery('genre_s: fantasy'); $facetqry->addExclude('inStockTag');
Let us add another facet query...