Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic id generation and mapping _id NEST

I want the id to be automatically generated when I index a document into elastic search. This works fine when I don't specify an Id property in my poco.

What I would like to do is map the underlying _id field onto my poco class when getting and use auto generated id when indexing. It looks like I can either specify the id or not at all. Are their any nest api options that I am missing?

EDIT

Example gist https://gist.github.com/antonydenyer/9074159

like image 833
Antony Denyer Avatar asked Oct 23 '13 13:10

Antony Denyer


2 Answers

As @Duc.Duong said in comments you can access Id using DocumentWithMeta. In current version of NEST DocumentsWithMetaData is replaced with Hits and also you should cast IHit<DataForGet>.Id from string to int.

this is my code:

public class DataForIndex
{
    public string Name { get; set; }
    // some other fields...
}

public class DataForGet : DataForIndex
{
    public int Id { get; set; }
}

var result = client.Search<DataForGet>(x => x.Index("index").MatchAll());
var list = results.Hits.Select(h =>
                                   {
                                       h.Source.Id = Convert.ToInt32(h.Id);
                                       return h.Source;
                                   }).ToList();
like image 106
mjalil Avatar answered Oct 20 '22 15:10

mjalil


Automatic ID Generation

The index operation can be executed without specifying the id. In such a case, an id will be generated automatically. In addition, the op_type will automatically be set to create. Here is an example (note the POST used instead of PUT):

$ curl -XPOST 'http://localhost:9200/twitter/tweet/' -d '{
  "user" : "kimchy",
  "post_date" : "2009-11-15T14:12:12",
  "message" : "trying out Elasticsearch"
}'

Result:

{
  "_index" : "twitter",
  "_type" : "tweet",
  "_id" : "6a8ca01c-7896-48e9-81cc-9f70661fcb32",
  "_version" : 1,
  "created" : true
}
like image 37
uzay95 Avatar answered Oct 20 '22 17:10

uzay95