2016-01-13 76 views
1

在我的ElasticSearch服务器中,我有一个现有的索引模板,其中包含一些设置和一些映射。将映射添加到现有索引模板(使用NEST属性)

我想为模板添加新类型的映射,但由于无法更新模板,我需要删除现有模板并重新创建它。

因为我想保留所有现有的设置,我试图让现有的定义,在这个例子中,映射添加到它,然后删除/重建,如:

using Nest; 
using System; 

public class SomeNewType { 
    [ElasticProperty(Index = FieldIndexOption.NotAnalyzed)] 
    public string SomeField { get; set; } 
    [ElasticProperty(Index = FieldIndexOption.Analyzed)] 
    public string AnotherField { get; set; } 
} 

class Program { 
    static void Main(string[] args) { 
     var settings = new ConnectionSettings(uri: new Uri("http://localhost:9200/")); 
     var client = new ElasticClient(settings); 
     var templateResponse = client.GetTemplate("sometemplate"); 
     var template = templateResponse.TemplateMapping; 
     client.DeleteTemplate("sometemplate"); 
     // Add a mapping to the template somehow... 
     template.Mappings.Add(...); 
     var putTemplateRequest = new PutTemplateRequest("sometemplate") { 
      TemplateMapping = template 
     }; 
     client.PutTemplate(putTemplateRequest); 
    } 
} 

但是,我无法找到一种方法来映射添加使用ElasticProperty模板定义属性,如在

client.Map<SomeNewType>(m => m.MapFromAttributes()); 

是否有可能创建一个RootObjectMapping添加到收藏Mappings类似于东西?

回答

2

您可以通过使用更强大的PutMappingDescriptor得到一个新的RootObjectMapping做到这一点,然后添加到您的GET _template请求返回的集合,像这样:

var settings = new ConnectionSettings(uri: new Uri("http://localhost:9200/")); 
var client = new ElasticClient(settings); 

var templateResponse = client.GetTemplate("sometemplate"); 
var template = templateResponse.TemplateMapping; 
// Don't delete, this way other settings will stay intact and the PUT will override ONLY the mappings. 
// client.DeleteTemplate("sometemplate"); 

// Add a mapping to the template like this... 
PutMappingDescriptor<SomeNewType> mapper = new PutMappingDescriptor<SomeNewType>(settings); 
mapper.MapFromAttributes(); 
RootObjectMapping newmap = ((IPutMappingRequest) mapper).Mapping; 

TypeNameResolver r = new TypeNameResolver(settings); 
string mappingName = r.GetTypeNameFor(typeof(SomeNewType)); 

template.Mappings.Add(mappingName, newmap); 

var putTemplateRequest = new PutTemplateRequest("sometemplate") 
{ 
    TemplateMapping = template 
}; 

var result = client.PutTemplate(putTemplateRequest); 

注:TypeNameResolver在Nest.Resolvers命名空间

正如上面的评论所述,如果映射是唯一需要更新的内容,我建议您不要删除旧的模板,否则您需要将所有其他相关设置复制到您的新请求中。

+0

谢谢,这正是我所需要的。关于删除,即使我删除模板,它看起来仍然保留设置:毕竟,GET _template'请求也返回设置,对吧? –

相关问题