添加映射到现有索引模板(使用NEST属性)

时间:2016-01-13 13:07:18

标签: c# elasticsearch nest

在我的ElasticSearch服务器中,我有一个现有的索引模板,其中包含一些设置和一些映射。

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

由于我想保留所有现有设置,我尝试获取现有定义,将映射添加到它,然后删除/重新创建,如下例所示:

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集合中,其类似于MapFromAttributes的内容?

1 个答案:

答案 0 :(得分: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命名空间

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