Use filters to narrow down search results, or use them for database-like queries. This topic explains how to filter search results based on Filter and FilterHits, with the Filter method in Episerver Search & Navigation (formerly Episerver Find).
How it works
There are two extension methods for the ITypeSearch<TSource> class filter: Filter and FilterHits. Both add filters to a search request but do so in different ways.
The Filter method applies a filter to the search query, while FilterHits adds a filter to the search request body. Use the Filter method in most cases, as it filters both the search result and the facets. Use FilterHits when you want to apply a filter to search results (the hits), but not to the facets.
Example
You index three blog posts. Two have the same author.
var post1 = new BlogPost
{
Author = new Author {Name = "Agatha Christie"}
};
var post2 = new BlogPost
{
Author = new Author {Name = "Agatha Christie"}
};
var post3 = new BlogPost
{
Author = new Author {Name = "Charles Dickens"}
};
Next, search for blog posts, filter by author to match the one with two posts, and request a terms facet for the author name. First, use the Filter method; then, the FilterHits method.
var result = client.Search<BlogPost>()
.Filter(x => x.Author.Name.Match("Agatha Christie"))
.TermsFacetFor(x => x.Author.Name)
.GetResult();
var facetItems = result.TermsFacetFor(x => x.Author.Name);
Console.WriteLine("Using Filter");
foreach (var facetItem in facetItems)
{
Console.WriteLine(facetItem.Term + " (" + facetItem.Count + ")");
}
result = client.Search<BlogPost>()
.FilterHits(x => x.Author.Name.Match("Agatha Christie"))
.TermsFacetFor(x => x.Author.Name)
.GetResult();
facetItems = result.TermsFacetFor(x => x.Author.Name);
Console.WriteLine("Using FilterHits");
foreach (var facetItem in facetItems)
{
Console.WriteLine(facetItem.Term + " (" + facetItem.Count + ")");
}
This code produces:
Using Filter
Agatha Christie (2)
Using FilterHits
Agatha Christie (2)
Charles Dickens (1)
Last updated: Oct 31, 2016