比较 ElasticSearch 服务器上的映射与来自 C# 类的推断映射?

Dav*_*all 6 c# elasticsearch nest

我有一个 ASP.NET WebForms Web 应用程序,它使用 ElasticSearch(使用 NEST API)进行自动完成搜索,并且效果很好。但是,存储在 ElasticSearch 中的文档结构(我只有一种类型的文档)会不时发生变化,并且映射需要随之变化。

我的方法是在 C# 代码中拥有文档类型(和映射)的主定义(只是一个ElasticProperty在其属性上设置相关属性的 C# 类)。我希望能够询问 NEST ElasticSearch 服务器的映射定义是否与可以从我的文档类中推断出的映射定义相匹配,如果不匹配,则更新服务器的映射。就像是:

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");
}
Run Code Online (Sandbox Code Playgroud)

NEST 是否提供这样的 API?

小智 3

可以通过这种方式完成,而无需在集群中创建任何内容:

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 }))
);
Run Code Online (Sandbox Code Playgroud)