Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 366
NatsuDragonEye Avatar asked Dec 18 '22 05:12

NatsuDragonEye


1 Answers

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"}
like image 117
Russ Cam Avatar answered Dec 30 '22 10:12

Russ Cam