Introduction
The .NET API provides rich functionality for both free text search and for querying by applying filters. These can also be combined so that certain criteria are applied to free text search by means of filters. Sometimes however the opposite is desired. That is, instead of limiting search results by applying a filter, you may want to include documents that do not necessarily match the search query or previously applied filters.
You can achieved this via the Include method. Just like the Filter and Boostmatching method, the Include method requires a filter expression as a parameter. Documents that match this filter are included in the results even if they otherwise would not be. As these documents may not match any previously applied search query, they are given a constant score. This means that they are ordered high or low in the search results depending on the score of other documents in the result. Therefore, the Include method has a second parameter that you can use to enter a boost factor. Set it to
- 1 if you do not care about the ordering
- 10 if you want the documents high in the search results
- .1 if you want them low in the search results
Examples
A typical case for using the Include method is when building "search as you type" functionality. You may want to perform a regular free text search and include documents whose title contains a word that starts with what the user has entered. For instance, you are building "search as you type" functionality for blog posts, and the user enters Bar into the search box. It may be that the user is searching for bar, or it may be that the user is about to type in Barcelona. To retrieve sensible suggestions for the user, perform a regular free text search and include blog posts where the title (or other important, short fields) contains a word that starts with bar.
C#
var q = "Bar";
searchResult = client.Search<BlogPost>()
.For(q)
.Include(x => x.Title.AnyWordBeginsWith(q), 1)
.GetResult();
Note: The above example uses the AnyWordBeginsWith filter method. Use this powerful method with caution.
It is perfectly sensible to use it on short fields, such as titles, tags and so on. But, do not use the method on longer text fields -- it can have a severe, negative impact on performance.