Multilanguage searching with Elasticsearch
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 IEnumerable
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
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 SearchDescriptor
return s.Indices(languages);
}
[/csharp]