gpt4 book ai didi

c# - 使用高级Nest Client和AutoMap进行PUT映射

转载 作者:行者123 更新时间:2023-12-03 00:49:51 27 4
gpt4 key购买 nike

我正在使用以下代码片段创建Elasticsearch索引:

ICreateIndexResponse createIndexResponse = elasticClient.CreateIndex(IndexName, c => c
.Mappings(ms => ms
.Map<Document>(m => m.AutoMap())
)
);
Document类是具有属性映射的POCO。

我希望能够将字段添加到映射中。使用Put Mapping API似乎可以实现:
PUT my_index 
{
"mappings": {
"_doc": {
"properties": {
"name": {
"properties": {
"first": {
"type": "text"
}
}
},
"user_id": {
"type": "keyword"
}
}
}
}
}

PUT my_index/_mapping/_doc
{
"properties": {
"name": {
"properties": {
"last": {
"type": "text"
}
}
},
"user_id": {
"type": "keyword",
"ignore_above": 100
}
}
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html

请注意,第一个PUT正在创建索引和映射。第二个PUT是添加和修改字段。我希望能够执行第二个PUT。

理想的情况是将属性添加到 Document类中,调用 AutoMap,并使用客户端调用PUT Mapping API。新属性将添加到我的映射中,并且适当时会更新/忽略以前存在的属性。

这可能吗?是否应该使用某些参数再次调用 CreateIndex方法?

最佳答案

Put Mapping API在客户端公开为.Map<T>

var client = new ElasticClient();

var putMappingResponse = client.Map<Document>(m => m
.AutoMap()
);

这将自动映射 Document的所有属性。我相信,Elasticsearch将仅对那些已经存在的映射不做任何操作,并添加新的映射。

如果您只想发送那些尚未映射的属性,则可以通过获取 Document的自动映射的属性,从索引中检索映射(从前者中除去后者),然后通过 .Map<T>()来发送那些映射来实现。就像是

var defaultIndex = "properties_example";
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

var settings = new ConnectionSettings(pool)
.DefaultIndex(defaultIndex);

var client = new ElasticClient(settings);

if (!client.IndexExists(defaultIndex).Exists)
{
var createIndexResponse = client.CreateIndex(defaultIndex, c => c
.Mappings(m => m
.Map<Document>(mm => mm.AutoMap())
)
);
}

var properties = new PropertyWalker(typeof(Document), null).GetProperties();

// will use the index inferred for Document, or the default index if none
// specified. Can specify an index on this call if you want to
var getMappingResponse = client.GetMapping<Document>();

var indexedMappings = getMappingResponse
// Use the index name to which the call was made.
.Indices[defaultIndex]
.Mappings[typeof(Document)]
.Properties;

var propertiesToIndex = new Dictionary<PropertyName, IProperty>();
foreach(var property in properties)
{
if (!indexedMappings.ContainsKey(property.Key))
{
propertiesToIndex.Add(property.Key, property.Value);
}
}

// map new properties only if there are some to map
if (propertiesToIndex.Any())
{
var request = new PutMappingRequest<Document>()
{
Properties = new Properties(propertiesToIndex)
};

var putMappingResponse = client.Map(request);
}

关于c# - 使用高级Nest Client和AutoMap进行PUT映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55506022/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com