Search code examples
elasticsearchnest

Inner Hits isn't working ElasticSearch


Good Day:

I'm using ElasticSearch/NEST to query against nested objects. What I realize is that my nested object is empty however, the parent is being returned despite there being now match.

ISearchResponse<Facility> responses = await this._elasticClient.SearchAsync<Facility>(a => a.Query(q =>
                  q.Bool(b =>
                            b.Must(m =>
                                m.Nested(n =>
                                    n.Query(nq =>
                                            nq.Term(t =>t.Field(f => f.Reviews.First().UserId).Value(user.Id))
                                            ).InnerHits(ih => ih.From(0).Size(1).Name("UserWithReview"))
                                 )
                             )
                       )

            ));

When I look at the generated query, I"m even more confused what is happening:

Successful low level call on POST: /dev/doc/_search?typed_keys=true
# Audit trail of this API call:
 - [1] HealthyResponse: Node: http://localhost:9200/ Took: 00:00:00.9806442
# Request:
{}

As you can see the request is empty.


Solution

  • You haven't defined the nested query with all the properties needed; it's missing the Path property, which tells Elasticsearch which document field (i.e. path) to execute the query on. Looking at the rest of the query, it looks like this should be the Reviews property

    ISearchResponse<Facility> responses =
        await this._elasticClient.SearchAsync<Facility>(a => a
            .Query(q => q
                .Bool(b => b
                    .Must(m => m
                        .Nested(n => n
                            .Path(f => f.Reviews) // <-- missing
                            .Query(nq => nq
                                .Term(t => t
                                    .Field(f => f.Reviews.First().UserId)
                                    .Value(user.Id)
                                )
                            )
                            .InnerHits(ih => ih.From(0).Size(1).Name("UserWithReview"))
                        )
                    )
                )
            )
        );