How to get the _id of a document easily? [C#]

I'm indexing documents without an ID, letting ES set it by itself. How it is created nor the value is of any interest.

How can I easily get this _id in the response document?

I'd very much love not to iterate over each hit just to set the ID in my response since it's considered metadata.

var esResponse = await _client.SearchAsync<SearchBoundingBoxResult>(s => s
    .Query(q => q
        .GeoBoundingBox(b => b
            .Field(f => f.Geometry)
            .BoundingBox(box)
        )
    )
);

//return esResponse.Documents; // ID is null in the document

List<SearchBoundingBoxResult> searchResults = new();
foreach (var hit in esResponse.Hits)
{
    var doc = hit.Source!;
    doc.Id = hit.Id!;
    searchResults.Add(doc);
}

return searchResults;

And the response object looks like this (shortened for simplicity)

public class SearchBoundingBoxResult
{
    public string Id { get; set; }
    public required string Name { get; set; }
}

Example of the raw json document in ES

{
  "_index": "paths",
  "_id": "4b5OEpEBiSFFgOLpCwAZ",
  "_version": 1,
  "_score": 0,
  "_source": {
    "name": "Bergslagsleden Stage 1: Kloten - Gillersklack",
    "geometry": {
      "type": "LineString",
      "coordinates": [
        [
          15.288221000000002,
          59.89521199999999
        ],
		[...]
      ]
    }
  },
  "fields": {
    "name": [
      "Bergslagsleden Stage 1: Kloten - Gillersklack"
    ],
    "geometry": [
      {
        "coordinates": [
          [
            15.288221000000002,
            59.89521199999999
          ],
		  [...]
        ],
        "type": "LineString"
      }
    ],
  }
}

Is there a simple solution to get the ID in my response document or is the only real option to create a GUID when creating the document?

Hi @Motsols,

I don't think there is a better solution for this. As you can see in the JSON response, _id is stored outside of the _source object, which is just the way ES works.

If you use Elastic.Clients.Elasticsearch for ingestion, you should indeed set the Id property of your object to something unique, like a GUID.

The client automatically checks, if the document has a property which is called Id (as well considers some variations) and uses this as the _id meta-data during ingestion, update operations, etc.

This way, the id is effectively stored twice: One time as the _id meta-data and another time inside the id field of the _source object.

Another solution could be to set-up an ingest pipeline that automatically populates the id property of your document with the value from the _id meta-data.

Thanks, good to know that I haven't missed anything.
Then I'll go with the GUID approach as mentioned.