Search code examples
c#elasticsearchnestelasticsearch-bulk-api

Specify the _id field using Bulk.IndexMany in ElasticSearch


I'm facing a problem inserting document using bulk API (C# NEST v5.4). I've an array of documents and inside of the array I've my ID.

My code is:

documents = documents .ToArray();

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

How can i insert the _id manually using the descriptor?

Thanks in advance!


Solution

  • You can set _id similarly to how you're setting the index name on the BulkDescriptor. Given the following POCO

    public class Message
    {
        public string Content { get; set; }
    }
    

    Setting the ids using an incrementing counter for example

    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)));
    

    yields the following request

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