Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElasticSearch Java Client querying nested objects

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

like image 844
user962206 Avatar asked Jul 12 '14 07:07

user962206


People also ask

How do I search in nested fields?

You can search nested fields using dot notation that includes the complete path, such as obj1.name . Multi-level nesting is automatically supported, and detected, resulting in an inner nested query to automatically match the relevant nesting level, rather than root, if it exists within another nested query.

What is nested object in Elasticsearch?

The nested type is a specialised version of the object data type that allows arrays of objects to be indexed in a way that they can be queried independently of each other.

What is a nested field?

When a packed class contains an instance field that is a packed type, the data for that field is packed directly into the containing class. The field is known as a nested field .


1 Answers

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
like image 149
Dan Tuffery Avatar answered Oct 12 '22 23:10

Dan Tuffery