ElasticSearch Java Client querying nested objects

user962206 picture user962206 · Jul 12, 2014 · Viewed 8.8k times · Source

How do I convert this kind of query.

{
  "query": {
    "nested": {
      "path": "consultations",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "consultations.prescriptions": "alfuorism"
              }
            },
            {
              "match": {
                "consultations.Diagnosis": "Fever"
              }
            }
          ]
        }
      }
    }
  }
}

To a Java Client query using QueryBuilders

Answer

Dan Tuffery picture Dan Tuffery · Jul 12, 2014

The folowing Java code will generate your query

public NestedQueryBuilder nestedBoolQuery(final Map<String, String> propertyValues, final String nestedPath) {

    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    Iterator<String> iterator = propertyValues.keySet().iterator();

    while (iterator.hasNext()) {
        String propertyName = iterator.next();
        String propertValue = propertyValues.get(propertyName);
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery(propertyName, propertValue);
        boolQueryBuilder.must(matchQuery);
    }

    return QueryBuilders.nestedQuery(nestedPath, boolQueryBuilder);
}

The parameter propertyValues is:

Map<String, String> propertyValues = new HashMap<String, String>();
propertyValues.put("consultations.prescriptions", "alfuorism");
propertyValues.put("consultations.Diagnosis", "Fever");

The parameter nestedPath is:

consultations