我遇到使用批量 API (C# NEST v5.4( 插入文档的问题。我有一系列文档,在数组中我有我的 ID。
我的代码是:
documents = documents .ToArray();
Client.Bulk(bd =>
bd.IndexMany(documents,
(descriptor, s) => descriptor.Index(indexName)));
如何使用描述符手动插入_id?
提前感谢!
您可以设置_id
,类似于在BulkDescriptor
上设置索引名称的方式。给定以下 POCO
public class Message
{
public string Content { get; set; }
}
例如,使用递增计数器设置 ID
var documents = new[] {
new Message { Content = "message 1" },
new Message { Content = "another message" },
new Message { Content = "yet another one" }
};
var indexName = "index-name";
var id = 0;
client.Bulk(bd => bd
.IndexMany(documents, (descriptor, s) => descriptor.Index(indexName).Id(++id)));
产生以下请求
POST http://localhost:9200/_bulk
{"index":{"_index":"index-name","_type":"message","_id":1}}
{"content":"message 1"}
{"index":{"_index":"index-name","_type":"message","_id":2}}
{"content":"another message"}
{"index":{"_index":"index-name","_type":"message","_id":3}}
{"content":"yet another one"}
下面是基于 GUID 类型的字段的示例,但它可以是任何其他类型。 我们可以在 elasticsearch 中指定要作为文档_id的类的字段。
public class Customer
{
public Guid CustomerId { get; set; }
public int CustomerCode { get; set; }
public string Name { get; set; }
}
基于上述 POCO 的示例
public void InsertMany(IList<Customer> customers)
{
var response = client.Bulk(bd => bd
.Index("customer")
.IndexMany(customers, (descriptor, lead) => descriptor.Id(lead.CustomerId)));
if (response.ServerError != null)
throw new Exception(response.ServerError?.ToString(), response.OriginalException);
}
异步相同的代码
public async Task InsertManyAsync(IList<Customer> customers)
{
var response = await client.BulkAsync(bd => bd
.Index("customer")
.IndexMany(customers, (descriptor, lead) => descriptor.Id(lead.CustomerId)));
if (response.ServerError != null)
throw new Exception(response.ServerError?.ToString(), response.OriginalException);
}