This content is archived. See latest version here

Last updated: Jun 10 2014

Introduction

The Filter method can be used to filter numerical fields in a number of ways. Supported numerical types are int, double, float and long as well as their nullable equivalents. Below is a list of use cases and examples illustrating the available methods.

Existence

To search for documents where a numerical field has a value, we can use the Exists method. The below search will find blog posts that has a AuthorId property. In other words, the below code is similar to the LINQ query Where(x => x.AuthorId.HasValue).

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => x.AuthorId.Exists());

Like all filters it can be negated using an exclamation mark (!). In other words, to instead find all blog posts that does not have an AuthorId we could use the below code.

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => !x.AuthorId.Exists());

Exact match

For exact matching we can use the Match method. The below search will match blog posts with ID 42 but not those with ID 41 or 43. The LINQ equivalent would be Where(x => x.Id == 42).

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => x.Id.Match(42));

Matching by range

To find documents with a numeric field that has a value within a given range we can use the InRange method. The below search will match blog posts that have between zero and five comments. In other words it will match blog posts that have 0, 1, 2, 3, 4, or 5 comments but not those that have 6 or 7 comments. An equivalent in LINQ could be Where(x => x.NumComments >= 0 && x.NumComments <= 5).

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => x.NumComments.InRange(0, 5));

For some numerical types, such as int, there is also other the GreaterThan and LessThan methods that make range filtering easier. For instance, given that NumComments cannot be negative, the above search could be rewritten to:

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => x.NumComments.LessThan(6));

Filtering on numerical collections

The Exists and Match method can also be used for properties that implement IEnumerable<int>. Support for other numerical types is currently lacking but will be available in future versions.

The below search that uses Exists will for instance match blog posts that has at least one category ID.

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => x.CategoryIds.Exists());

And the below search will match any blog post that has a category with ID 42. Note that it will not limit the result to blog posts that only have that category ID though.

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => x.CategoryIds.Match(42));

Do you have feedback on this documentation? Send an email to documentation@episerver.com. For development-related questions and discussions, refer to our Forums on https://world.episerver.com/forum/