HomeDev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideGitHubNuGetDev CommunityDoc feedbackLog In

Use filters to narrow down search results and to add advanced search functionality to websites. The Optimizely Search & Navigation fluent API provides a set of filter methods, which you can extend.

The [Filter](🔗) method provides a powerful way of filtering out certain matching documents by accepting an expression that returns a filter. Create these expressions by using extension methods, such as the `Match` method. These extension methods are limited to operating on value types and strings but not on complex types. However, you can extend the filtering functionality in the following ways:

  • Create a custom extension method that returns a `FilterExpression`. This is the most common way.

  • Create extension methods that return an instance of the `DelegateFilterBuilder` class.

## Return a FilterExpression

A `FilterExpression` is an object that encapsulates an expression that returns a Filter. Once the query is executed, the `FilterExpression` is found and replaced by the expression it encapsulates. Finally, the field names in that expression are replaced with the corresponding field names on server side.

The following example shows two classes: `Author` and `BlogPost`.

Assume that you want to find blog posts that have authors. Without a custom extension method, you cannot do that directly because there is no `Exists` method for the `Author` type. However, you know that authors always have an Id (which is obviously true in this case, because the Id is a value type, and is 0 if not specified), so the following code can accomplish this.

You can make queries like this more convenient by adding a custom extension method.

Next, rewrite the original query to check for the existence of an author instead of the existence of the author ID.

Alternatively, add a custom method for the `BlogPost` class.

Then, your query can be:

Extending the filtering functionality by creating extension methods that return `FilterExpression` is not limited to checking for existence, or to single filters. Assuming that a user is logged in and a publication date exists on the `BlogPost` class, you can create a custom method for finding blog posts that are visible to the user.

## Return a DelegateFilterBuilder

Extension methods returning an instance of `DelegateFilterBuilder` are one level closer, because the `DelegateFilterBuilder` constructor requires an expression that returns an actual filter. This means that they are not as useful for extending the filtering functionality for complex types. Instead, they are useful for extending the filtering functionality in ways that use filters not exposed by the fluent API.