Elasticsearch inner hits in java api
Asked Answered
C

1

8

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.

Compulsion answered 28/9, 2015 at 19:23 Comment(0)
H
10

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);
Hoarse answered 30/9, 2015 at 6:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.