Optimizely Search & Navigation - Get autocomplete suggestions in right language

blog header image

AI generated by DALL-E2

When you are using Optimizely Search & Navigation (Find) to help you generate autocomplete suggestions server side in a multi-language scenario it can be tricky (and poorly documented) to figure out how to get the suggestions in the correct language.

I recently had to do this for a client - and looked everywhere for the documentation - but came up short. However luckily Jonas Bergqvist was a great help and shared some example code with me - that I'll now share with you guys:


protected IEnumerable<string> GetTags(string lang, string tag)
{
            var tagCollection = new List<string>();
            if (!string.IsNullOrWhiteSpace(lang))
            {
                tagCollection.Add("language:" + lang);
            }
            if (!string.IsNullOrWhiteSpace(tag))
            {
                tagCollection.Add(tag);
            }
            return _tagHelper != null ? _tagHelper.AddDefaultTags(tagCollection) : tagCollection;
 }

public IEnumerable<string> GetAutocompleteSuggestions(string query, string lang, int size, string tag){
          var taghelper = ServiceLocator.Current.GetInstance<IStatisticTagsHelper>();
          var suggestions = SearchClient.Instance.Statistics().Autocomplete(query,size,GetTags(lang,tag));
          return suggestions.Hits.Select(h => h.Query);
}

 

On a side-note: I often find that the autogenerated suggestions from Find can be a bit noisy - so instead I usually prefer to combine them in my own backend API with a few other things in the right priority (and only take top N). For example:

  1. Editorial autocomplete texts for the current query string. I find them using the above code sample and then filter to only get editorial suggestions for the current language.
  2. Search for pages where the title/name has a wildcard match to the currently typed in phrase. If any are found, return the titles as first suggestions
  3. Return other generated autocomplete suggestions (from the above code).

The above can naturally be tweaked to your liking. How do you prefer to do search autocomplete in Optimizely CMS? Let me know in the comments below.

Recent posts