Search across multiple types
Describes how to build functionality for searching across multiple object types in one query, in Optimizely Search & Navigation.
There are two ways to search over multiple types:
Implicit
– TheIClient.Search<T>()
method supports inheritance by default. So, searching over multiple types with a common base class requires no extra effort.IncludeType
– Create a search request for one type, then include additional types in the request. When doing so, you must provide a projection from the additional type to the return type of the search request, the original type, or some projection.
You can create a search request for BlogPosts
and include the Article
type in the request, as shown in the following example.
result = client.Search<BlogPost> .For("Banana")
.IncludeType<BlogPost, Article>(x => new BlogPost {
Title = x.Title, Content = x.MainBody
})
.GetResult();
In this case, you search for BlogPosts
and Articles
and retrieve the results as BlogPosts
. However, in most situations, it is preferable to project types to a third type that is more suitable for search results, like this.
result = searchQuery.For("Banana")
.Select(x => new SearchResult {
Title = x.Title, Content = x.Content
})
.IncludeType<SearchResult, Article>(x => new SearchResult {
Title = x.Title, Content = x.MainBody
})
.GetResult();
Limitations
Although you can use the
IncludeType
method to include additional types, the search request is built towards the first type. So, if you limit the request to search in specific fields and none of those exists in the other types, you only get hits from the first type. In practice, however, if you search through all content without limiting the request to specific fields, or if the types share the same name for fields, this is not a problem.
Updated 6 months ago