Episerver Find UnifiedSearchFor with configurable operator

When using UnifiedSearch in Episerver Find, I prefer to use the method IClient.UnifiedSearchFor() because it takes care of necessary logic without exposing implementation details, rendering in lower risk of introducing bugs and unwanted behaviour.

By default, multiword queries is concatenated using the operator OR, but in this case we needed to use AND combining the words. The solution using the extension method .WithAndAsDefaultOperator() found on Episerver World1 only applies to methods returning the type of IQueriedSearch<ISearchContent, QueryStringQuery>. The return type of UnifiedSearchFor is IQueriedSearch<ISearchContent> which obstructing the possibility to extend with WithAndAsDefaultOperator().

So why not fix this, writing our own extension method returning the correct type? Let's go!

Episerver Find ships with two methods named UnifiedSearchFor, one in EPiServer.Find namespace, that invokes boosting with unified weights, and one in the EPiServer.Find.Cms namespace which resolves language for stemming.2

Our method is to replace Episerver.Find.UnifiedSearchFor which means we'll need to provide the language for stemming ourselves.

Our main goal is to be able to select which operator our query should use, we will start with setting these. I prefer to do this with an enum, but you can always use this using a struct or similar static value.

Applying some wild guessing, the implementation of UnifiedSearchFor looks like this:

  1. Init a search for ISearchContent
  2. Apply the search query with .For(string query)
  3. Apply weights with .UsingUnifiedWeights()

Rendering in the following set up:

To resolve our stemming we are going to need to provide the language ourselves when calling the extension. By using client.UnifiedSearch(language) we are calling built in functionality giving us a semi-isolated implementation in only calling methods in the public API, rendering in us unaware and independent of concrete implementation changes regarding UnifiedSearch in the future.

Full code available as gist: https://gist.github.com/kimgunnarsson/31ab1968d105e58183d6