geodistance-aggregation.asciidoc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. [[java-aggs-bucket-geodistance]]
  2. ==== Geo Distance Aggregation
  3. Here is how you can use
  4. {ref}/search-aggregations-bucket-geodistance-aggregation.html[Geo Distance Aggregation]
  5. with Java API.
  6. ===== Prepare aggregation request
  7. Here is an example on how to create the aggregation request:
  8. [source,java]
  9. --------------------------------------------------
  10. AggregationBuilder aggregation =
  11. AggregationBuilders
  12. .geoDistance("agg")
  13. .field("address.location")
  14. .point(new GeoPoint(48.84237171118314,2.33320027692004))
  15. .unit(DistanceUnit.KILOMETERS)
  16. .addUnboundedTo(3.0)
  17. .addRange(3.0, 10.0)
  18. .addRange(10.0, 500.0);
  19. --------------------------------------------------
  20. ===== Use aggregation response
  21. Import Aggregation definition classes:
  22. [source,java]
  23. --------------------------------------------------
  24. import org.elasticsearch.search.aggregations.bucket.range.Range;
  25. --------------------------------------------------
  26. [source,java]
  27. --------------------------------------------------
  28. // sr is here your SearchResponse object
  29. Range agg = sr.getAggregations().get("agg");
  30. // For each entry
  31. for (Range.Bucket entry : agg.getBuckets()) {
  32. String key = entry.getKey(); // key as String
  33. Number from = (Number) entry.getFrom(); // bucket from value
  34. Number to = (Number) entry.getTo(); // bucket to value
  35. long docCount = entry.getDocCount(); // Doc count
  36. logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, from, to, docCount);
  37. }
  38. --------------------------------------------------
  39. This will basically produce:
  40. [source,text]
  41. --------------------------------------------------
  42. key [*-3.0], from [0.0], to [3.0], doc_count [161]
  43. key [3.0-10.0], from [3.0], to [10.0], doc_count [460]
  44. key [10.0-500.0], from [10.0], to [500.0], doc_count [4925]
  45. --------------------------------------------------