Multilanguage searching with Elasticsearch
Multilanguage searching with Elasticsearch

Multilanguage searching with Elasticsearch

2014, Apr 16    

This time I’ll start directly with the code.  First an utility method to create the connection:

[csharp]
private ElasticClient Connect(IEnumerable contents)
{
var defaultLanguageCode = “eng”;
var uri = new System.Uri(ConfigurationManager.AppSettings[“ElasticSearchServer”]);
var settings = new ConnectionSettings(uri).SetDefaultIndex(defaultLanguageCode);
var client = new ElasticClient(settings);
}
[/csharp]

And here’s the interesting part:

[csharp]
public IEnumerableSearch(string text, int page, int pageSize, IEnumerablelanguages) { ElasticClient client = this.Connect(); IQueryResponsesearchResults = client.Search(s => this.GetIndexSearchDescriptor(s, languages) .QueryString(text) .Skip(System.Math.Max(0, page) * pageSize) .Take(pageSize));

if (searchResults.Total != 0 && searchResults.Hits != null && searchResults.Hits.Hits != null)
{
int totalPages = (int)System.Math.Ceiling((double)((float)searchResults.Total / (float)pageSize));
var results = searchResults.Hits.Hits;

return results.Select(h => h.Source).ToArray();
}
return Enumerable.Empty(); } [/csharp]

As you may see, the Search method takes the text parameter and a list of languages. In the last post we indexed the content translations using language codes (eg: eng, ita, esp and so on…) as index names. So the idea here is to use the GetIndexSearchDescriptor method to get a SearchDescriptor instance from the language codes and run a query using the text in input.
As a bonus I have added quick&dirty pagination just for the sake of it 😀

[csharp]
private SearchDescriptorGetIndexSearchDescriptor(SearchDescriptors, IEnumerablelanguages) { if (languages == null || !languages.Any()) return s.AllIndices();

return s.Indices(languages);
}
[/csharp]

Did you like this post? Then