elasticsearchnestedjavahit

Elasticsearch inner hits in java api


I am trying to implement inner hits with elasticsearch using Java API, but I cannot find much of any documentation on it or examples that other people are using. I have my JSON search that works as follows:

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "nested": {
          "path": "locations",
          "filter": {
            "geo_distance": {
              "distance": "20km",
              "locations.address.geoLocation": {
                "lat": 38.07061,
                "lon": -76.77514
              }
            }
          },
          "inner_hits": {}
        }
      }
    }
  }
}

I see an InnerHitsBuilder and addInnerHit methods in the elasticsearch library but I cannot find the documentation on how to use them.


Solution

  • Note that there are plenty of test cases in the ES source code where each feature is being tested, so browsing the ES code is a incredibly rich source of information. Inner hits makes no exception and you can find all inner_hits test cases in the InnerHitsTests.java class.

    So your query above can be created like this:

        // build the geo_distance filter
        GeoDistanceFilterBuilder geo = FilterBuilders
                .geoDistanceFilter("locations.address.geoLocation")
                .distance("20km")
                .lat(38.07061)
                .lon(-76.77514);
    
        // build the nested filter and add inner_hits
        NestedFilterBuilder nested = FilterBuilders
               .nestedFilter("locations", geo)
               .innerHit(new QueryInnerHitBuilder());  <--- this is what you're looking for
    
        // wrap it all inside a filtered query
        FilteredQueryBuilder query = QueryBuilders
               .filteredQuery(QueryBuilders.matchAllQuery(), nested);