inner hits elasticsearch nest in csharp

To perform an elasticsearch query with inner hits using Nest in C#, we need to define the inner hits mapping in the search request. Here is an example query that demonstrates how to do this:

main.cs
var response = client.Search<Data>(s => s
    .Query(q => q
        .Nested(n => n
            .Path(p => p.InnerData)
            .Query(nq => nq
                .Match(m => m
                    .Field(fd => fd.InnerData.Name)
                    .Query("search term")
                )
            )
            .InnerHits(i => i
                .Name("innerDataHits")
                .Source(s => s
                    .Includes(i => i
                        .Field(f => f.InnerData.Name)
                    )
                )
            )
        )
    )
);

var innerDataHits = response.Hits.Select(h => h.InnerHits["innerDataHits"].Documents<DataInner>(f => f.InnerData)).ToList();
693 chars
24 lines

In the above code snippet, we are using the NEST library's search method to execute an Elasticsearch query. We are defining the query as a nested query, which allows us to search documents that are nested inside other documents.

The ".InnerHits" method is used to define the inner hits mapping for the query. We are giving it a name, "innerDataHits", and specifying which source fields we want to include in the results.

The "Response.Hits" object contains the search results, and we can access the inner hits using the "InnerHits" property. We are using the "Documents" method to parse the inner hits into a strongly-typed list of "DataInner" objects.

This example should give you an idea of how to perform inner hits queries in Elasticsearch using the Nest library in C#.

gistlibby LogSnag