Try our conversational search powered by Generative AI!

Loading...
Area: Optimizely Search & Navigation
ARCHIVED This content is retired and no longer maintained. See the latest version here.

Recommended reading 

How it works

There are two extension methods for the ITypeSearch<TSource> class for filtering Filter and FilterHits. Both add filters to the search request but they 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; filters added using the Filter method apply both to the search results and to the returned facets while filters added using the FilterHits method filters only the search results but not the facets.

Use the Filter method In most cases for performance reasons, and always when not using facets. Use FilterHits when you want to apply a filter to the search results (the hits), but not to the facets.

Example

Given that you index three blog posts of which two have the same author.

C#
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 using the Filter method, then using the FilterHits method.

C#
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 will print:

Using Filter
Agatha Christie (2)

Using FilterHits
Agatha Christie (2)
Charles Dickens (1)

Do you find this information helpful? Please log in to provide feedback.

Last updated: Nov 16, 2015

Recommended reading