Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare mapping on ElasticSearch server with inferred mapping from C# class?

I have a ASP.NET WebForms web application which uses ElasticSearch (using the NEST API) for autocomplete search and it works great. However, from time to time the structure of the document (I only have one type of document) stored in ElasticSearch changes and the mapping needs to change with it.

My approach has been to have the master definition of the document type (and mapping) in C# code (simply a C# class with relevant ElasticProperty attributes set on its properties). I would like to be able to ask NEST if the mapping definition the ElasticSearch server has matches the one which could be inferred from my document class and, if not, update the server's mapping. Something like:

ElasticClient client = new ElasticClient(new ConnectionSettings(new Uri("http://localhost:9200")), "my_index");
// Hypothetical code below - does NEST offen an API which lets me do this if statement?
if (!client.GetMapping("MyDocument").Matches<MyDocument>()) {
    client.CloseIndex("my_index"); // Is this necessary when updating mapping?
    client.Map<MyDocument>(m => m.MapFromAttributes());
    client.OpenIndex("my_index");
}

Does NEST offer such an API?

like image 478
David Nordvall Avatar asked Nov 27 '15 11:11

David Nordvall


1 Answers

Can be done this way without creating anything in the cluster :

var getIndexResponse = await _elasticClient.GetIndexAsync(indexName);
IIndexState remote = getIndexResponse.Indices[indexName];
// move the index definition out of here and use it to create the index as well
IIndexState local = new CreateIndexDescriptor(indexName);
// only care about mappings
var areMappingsSynced = JToken.DeepEquals
(
    JObject.Parse(_elasticClient.Serializer.SerializeToString(new { local.Mappings })),
    JObject.Parse(_elasticClient.Serializer.SerializeToString(new { remote.Mappings }))
);
like image 94
jtroconisa Avatar answered Oct 16 '22 15:10

jtroconisa