Search code examples
javaelasticsearchparent-childquery-builder

Elasticsearch QueryBuilders that get all parents that has children


I have documents that are both parent and child in an Elastic Search mapping. And because children are updated frequently, this connection was chosen over nested documents. I now want to find every parent with children and with no parent.

HasChildQueryBuilder hQuery = QueryBuilders
       .hasChildQuery("instance", QueryBuilders
             .hasChildQuery("instance_permission", terms));

I discovered this on the Internet, however it appears to have changed and is no longer valid.

Query query = new NativeSearchQueryBuilder()
       .withQuery(QueryBuilders.boolQuery().
        must.(QueryBuilders.matchQuery("relation_type", "parent))
        must. ****  // parents that has children query  ****
       .build();  

Can somebody help me in finishing this query?


Solution

  • This works // JoinQueryBuilders.hasChildQuery

    
    Query query = new NativeSearchQueryBuilder()
           .withQuery(QueryBuilders.boolQuery()
              .must(QueryBuilders.matchQuery("relation_type", "parent"))
              .must(JoinQueryBuilders.hasChildQuery("child", QueryBuilders.matchAllQuery(), ScoreMode.None)))
           .withPageable(pageRequest)
           .build();
    SearchHits<Asset> searchHits = elasticsearchRestTemplate.search(query, Asset.class);