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 

Introduction

There are two extension methods for the ITypeSearch<TSource> class for filtering Filter and FilterHits. Both adds 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. What this means is that filters added using the Filter method will apply both to the search results and to the returned facets while filters added using the FilterHits method will only filter the search results but not the facets.

In most cases, and always when not using facets, the Filter method should be used as that is better from a performance perspective. The one case where FilterHits should be used is when we want to apply a filter to the search results, the hits, but not to the facets.

Example

Given that we have indexed 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"}
    };

We then 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 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: Sep 26, 2013

Recommended reading