Search code examples
c#elasticsearchnest

NEST How to find field on subdocument


I've a sample company JSON document structure like this:

[
    {
        "id": "id1",
        "name": "company1",
        "employees": [
            {
                "name": "employee1",
                "education": "education1"
            },
            {
                "name": "employee2",
                "education": "education2"
            }
        ]
    }
]

and I'm doing queries like this:

GET companies/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "employees.education": {
              "value": "education1"
            }
          }
        },
        {
          "term": {
            "employees.education": {
              "value": "education2"
            }
          }
        }
      ]
    }
  }
}

The query is build using NEST:

var filters = new List<Func<QueryContainerDescriptor<Company>, QueryContainer>>();

foreach (var education in educationsToFilter)
{
    filters.Add(fq => fq.Term(f => f.Employees.Suffix("education"), education));
}

var searchResponse = _client.Search<Company>(s => s
    .Query(q => q
        .Bool(bq => bq
            .Filter(filters)
        )
    )
);

Is there a better way of finding the Term Field instead of using the Suffix-method? I would like a more type safe way.


Solution

  • You can resolve nested field name with this lambda expression:

    fq.Term(f => f.Employees.FirstOrDefault().Education, education)
    

    Hope that helps.