How to return document field for NEST client with search?

I have following mappings:

{
  "mappings": {
      "properties" : {
        "CompletionTime" : {
          "type" : "date",
          "format": "date_hour_minute_second",
          "fields" : {
            "keyword" : {
              "type" : "date"
            }
          }
        },
        "Description" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "InitiatorName" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "StartTime" : {
          "type" : "date",
          "format": "date_hour_minute_second",
          "fields" : {
            "keyword" : {
              "type" : "date"
            }
          }
        },
        "TargetObjectName" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "TargetObjectType" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
  }
}

I created following code for C# Nest client:

public DateTime GetNewestDocumentDate()
        {
            var searchResponse = this.ec.Client.Search<Record>(s => s
                    .Query(q => q.MatchAll())
                    .Sort(so => so
                        .Field(fs => fs
                            .Field("StartTime")
                            .Order(SortOrder.Descending)
                        ))
                    .Size(1)
            );
            var a = searchResponse.Documents;
            Console.WriteLine(JsonSerializer.Serialize(a));

            return a.StartTime;
        }

I am new with C# and Elastic so I don't know how to return document field. In my case it should be something like this, but my syntax is not correct. var a is an array and a[0].StartTime didn't pass check in Visual Studio.

Solution:

var a = searchResponse.Documents.ElementAt(0);
            
return a.StartTime;

Hi dreic! I'm glad you found the solution. Indeed, Documents is a collection of the hits, deserialised to your Record type so you can enumerate those and access any of the properties as required.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.