使用ElasticSearch中的Bulk.IndexMany指定_id字段

e37o9pze  于 2023-02-11  发布在  ElasticSearch
关注(0)|答案(2)|浏览(186)

我在使用批量API(C#NEST v5.4)插入文档时遇到了一个问题。我有一个文档数组,数组中有我的ID。
我的代码是:

documents = documents .ToArray();

Client.Bulk(bd =>
bd.IndexMany(documents,
    (descriptor, s) => descriptor.Index(indexName)));

如何使用描述符手动插入_id?
先谢了!

roqulrg3

roqulrg31#

可以像在BulkDescriptor上设置索引名称那样设置_id

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"}
anhgbhbe

anhgbhbe2#

下面是一个基于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);
}

相关问题