geodistance-aggregation.asciidoc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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", new GeoPoint(48.84237171118314,2.33320027692004))
  13. .field("address.location")
  14. .unit(DistanceUnit.KILOMETERS)
  15. .addUnboundedTo(3.0)
  16. .addRange(3.0, 10.0)
  17. .addRange(10.0, 500.0);
  18. --------------------------------------------------
  19. ===== Use aggregation response
  20. Import Aggregation definition classes:
  21. [source,java]
  22. --------------------------------------------------
  23. import org.elasticsearch.search.aggregations.bucket.range.Range;
  24. --------------------------------------------------
  25. [source,java]
  26. --------------------------------------------------
  27. // sr is here your SearchResponse object
  28. Range agg = sr.getAggregations().get("agg");
  29. // For each entry
  30. for (Range.Bucket entry : agg.getBuckets()) {
  31. String key = entry.getKeyAsString(); // key as String
  32. Number from = (Number) entry.getFrom(); // bucket from value
  33. Number to = (Number) entry.getTo(); // bucket to value
  34. long docCount = entry.getDocCount(); // Doc count
  35. logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, from, to, docCount);
  36. }
  37. --------------------------------------------------
  38. This will basically produce:
  39. [source,text]
  40. --------------------------------------------------
  41. key [*-3.0], from [0.0], to [3.0], doc_count [161]
  42. key [3.0-10.0], from [3.0], to [10.0], doc_count [460]
  43. key [10.0-500.0], from [10.0], to [500.0], doc_count [4925]
  44. --------------------------------------------------