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
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();
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With