Ealsticsearch 5.x Java API聚合string类型的时候,会报错(json的错),则需要在聚合的string类型字段的后面添加.keyword , 虽然使用watch查看聚合的es json的时候会出现以下报错,但是不会影响结果。

{ "error" : "JsonGenerationException[Can not write a field name, expecting a value]"}

1、Metrics Aggregations(度量聚合)

1)、MinAggregation(最小值聚合)

1、Prepare aggregation request

MinAggregationBuilder aggregation =

AggregationBuilders

.min("agg")

.field("height");

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.min.Min;

// sr is here your SearchResponse object

Min agg = sr.getAggregations().get("agg");

double value = agg.getValue();

2)、MaxAggregation(最大值聚合)

1、Prepare aggregation request

MaxAggregationBuilder aggregation =

AggregationBuilders

.max("agg")

.field("height");

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.max.Max;

// sr is here your SearchResponse object

Max agg = sr.getAggregations().get("agg");

double value = agg.getValue();

3)、SumAggregation(求和聚合)

1、Prepare aggregation request

SumAggregationBuilder aggregation =

AggregationBuilders

.sum("agg")

.field("height");

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.sum.Sum;

// sr is here your SearchResponse object

Sum agg = sr.getAggregations().get("agg");

double value = agg.getValue();

4) 、AvgAggregation(平均数聚合)

1、Prepare aggregation request

AvgAggregationBuilder aggregation =

AggregationBuilders

.avg("agg")

.field("height");

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.avg.Avg;

// sr is here your SearchResponse object

Avg agg = sr.getAggregations().get("agg");

double value = agg.getValue();

5)、StatsAggregation(统计聚合)

统计聚合即一次性获取最小值、最小值、平均值、求和、统计聚合的集合。

1、Prepare aggregation request

StatsAggregationBuilder aggregation =

AggregationBuilders

.stats("agg")

.field("height");

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.stats.Stats;

// sr is here your SearchResponse object

Stats agg = sr.getAggregations().get("agg");

double min = agg.getMin();

double max = agg.getMax();

double avg = agg.getAvg();

double sum = agg.getSum();

long count = agg.getCount();

6) 、Extended Stats Aggregation(扩展统计聚合)

1、Prepare aggregation request

ExtendedStatsAggregationBuilder aggregation =

AggregationBuilders

.extendedStats("agg")

.field("height");

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStats;

// sr is here your SearchResponse object

ExtendedStats agg = sr.getAggregations().get("agg");

double min = agg.getMin();

double max = agg.getMax();

double avg = agg.getAvg();

double sum = agg.getSum();

long count = agg.getCount();

double stdDeviation = agg.getStdDeviation();

double sumOfSquares = agg.getSumOfSquares();

double variance = agg.getVariance();

7) 、Values CountAggregation(值计数聚合)

1、Prepare aggregation request

ValueCountAggregationBuilder aggregation =

AggregationBuilders

.count("agg")

.field("height");

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCount;

// sr is here your SearchResponse object

ValueCount agg = sr.getAggregations().get("agg");

long value = agg.getValue();

8) 、Percentile Aggregation(百分位聚合)

1、Prepare aggregation request

PercentilesAggregationBuilder aggregation =

AggregationBuilders

.percentiles("agg")

.field("height");

自定义百分比:

PercentilesAggregationBuilder aggregation =

AggregationBuilders

.percentiles("agg")

.field("height")

.percentiles(1.0, 5.0, 10.0, 20.0, 30.0, 75.0, 95.0, 99.0);

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile;

import org.elasticsearch.search.aggregations.metrics.percentiles.Percentiles;

// sr is here your SearchResponse object

Percentiles agg = sr.getAggregations().get("agg");

// For each entry

for (Percentile entry : agg) {

double percent = entry.getPercent();    // Percent

double value = entry.getValue();        // Value

logger.info("percent [{}], value [{}]", percent, value);

}

3、Result

percent [1.0], value [0.814338896154595]

percent [5.0], value [0.8761912455821302]

percent [25.0], value [1.173346540141847]

percent [50.0], value [1.5432023318692198]

percent [75.0], value [1.923915462033674]

percent [95.0], value [2.2273644908535335]

percent [99.0], value [2.284989339108279]

9)、Percentile Ranks Aggregation(百分等级聚合)

1、Prepare aggregation request

PercentileRanksAggregationBuilder aggregation =

AggregationBuilders

.percentileRanks("agg")

.field("height")

.values(1.24, 1.91, 2.22);

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile;

import org.elasticsearch.search.aggregations.metrics.percentiles.PercentileRanks;

// sr is here your SearchResponse object

PercentileRanks agg = sr.getAggregations().get("agg");

// For each entry

for (Percentile entry : agg) {

double percent = entry.getPercent();    // Percent

double value = entry.getValue();        // Value

logger.info("percent [{}], value [{}]", percent, value);

}

3、Result

percent [29.664353095090945], value [1.24]

percent [73.9335313461868], value [1.91]

percent [94.40095147327283], value [2.22]

10)、Cardinality Aggregation(基数聚合)

1、Prepare aggregation request

CardinalityAggregationBuilder aggregation =

AggregationBuilders

.cardinality("agg")

.field("tags");

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.cardinality.Cardinality;

// sr is here your SearchResponse object

Cardinality agg = sr.getAggregations().get("agg");

long value = agg.getValue();

11)、Geo Bounds Aggregation(地理限制聚合)

1、Prepare aggregation request

GeoBoundsBuilder aggregation =

GeoBoundsAggregationBuilder

.geoBounds("agg")

.field("address.location")

.wrapLongitude(true);

2、Use aggregation response

import org.elasticsearch.search.aggregations.metrics.geobounds.GeoBounds;

// sr is here your SearchResponse object

GeoBounds agg = sr.getAggregations().get("agg");

GeoPoint bottomRight = agg.bottomRight();

GeoPoint topLeft = agg.topLeft();

logger.info("bottomRight {}, topLeft {}", bottomRight, topLeft);

3、Result

bottomRight [40.70500764381921, 13.952946866893775], topLeft [53.49603022435221, -4.190029308156676]

12)、Top Hits Aggregation(top n聚合)

1)、Prepare aggregation request

1、只查询分组的top 1:

AggregationBuilder aggregation = AggregationBuilders

.terms("agg").field("gender")

.subAggregation(

AggregationBuilders.topHits("top")

);

2、查询分组的top n:

AggregationBuilder aggregation = AggregationBuilders

.terms("agg").field("gender")

.subAggregation(

AggregationBuilders.topHits("top")

.explain(true)

.size(1)

.from(10)

);

2)、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.terms.Terms;

import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;

// sr is here your SearchResponse object

Terms agg = sr.getAggregations().get("agg");

// For each entry

for (Terms.Bucket entry : agg.getBuckets()) {

String key = entry.getKey();                    // bucket key

long docCount = entry.getDocCount();            // Doc count

logger.info("key [{}], doc_count [{}]", key, docCount);

// We ask for top_hits for each bucket

TopHits topHits = entry.getAggregations().get("top");

for (SearchHit hit : topHits.getHits().getHits()) {

logger.info(" -> id [{}], _source [{}]", hit.getId(), hit.getSourceAsString());

}

}

3)、查询结果:

key [male], doc_count [5107]

-> id [AUnzSZze9k7PKXtq04x2], _source [{"gender":"male",...}]

-> id [AUnzSZzj9k7PKXtq04x4], _source [{"gender":"male",...}]

-> id [AUnzSZzl9k7PKXtq04x5], _source [{"gender":"male",...}]

key [female], doc_count [4893]

-> id [AUnzSZzM9k7PKXtq04xy], _source [{"gender":"female",...}]

-> id [AUnzSZzp9k7PKXtq04x8], _source [{"gender":"female",...}]

-> id [AUnzSZ0W9k7PKXtq04yS], _source [{"gender":"female",...}]

13)、Scripted Metric Aggregation(脚本度量聚合)

1、maven依赖

<dependency>

<groupId>org.codehaus.groovy</groupId>

<artifactId>groovy-all</artifactId>

<version>2.3.2</version>

<classifier>indy</classifier>

</dependency>

1、Prepare aggregation request

ScriptedMetricAggregationBuilder aggregation = AggregationBuilders

.scriptedMetric("agg")

.initScript(new Script("params._agg.heights = []"))

.mapScript(new Script("params._agg.heights.add(doc.gender.value == 'male' ? doc.height.value : -1.0 * doc.height.value)"));

You can also specify a combine script which will be executed on each shard:

ScriptedMetricAggregationBuilder aggregation = AggregationBuilders

.scriptedMetric("agg")

.initScript(new Script("params._agg.heights = []"))

.mapScript(new Script("params._agg.heights.add(doc.gender.value == 'male' ? doc.height.value : -1.0 * doc.height.value)"))

.combineScript(new Script("double heights_sum = 0.0; for (t in params._agg.heights) { heights_sum += t } return heights_sum"));

You can also specify a reduce script which will be executed on the node which gets the request:

ScriptedMetricAggregationBuilder aggregation = AggregationBuilders

.scriptedMetric("agg")

.initScript(new Script("params._agg.heights = []"))

.mapScript(new Script("params._agg.heights.add(doc.gender.value == 'male' ? doc.height.value : -1.0 * doc.height.value)"))

.combineScript(new Script("double heights_sum = 0.0; for (t in params._agg.heights) { heights_sum += t } return heights_sum"))

.reduceScript(new Script("double heights_sum = 0.0; for (a in params._aggs) { heights_sum += a } return heights_sum"));

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.terms.Terms;

import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;

// sr is here your SearchResponse object

ScriptedMetric agg = sr.getAggregations().get("agg");

Object scriptedResult = agg.aggregation();

logger.info("scriptedResult [{}]", scriptedResult);

3、Result

result1:

scriptedResult object [ArrayList]

scriptedResult [ {

"heights" : [ 1.122218480146643, -1.8148918111233887, -1.7626731575142909, ... ]

}, {

"heights" : [ -0.8046067304119863, -2.0785486707864553, -1.9183567430207953, ... ]

}, {

"heights" : [ 2.092635728868694, 1.5697545960886536, 1.8826954461968808, ... ]

}, {

"heights" : [ -2.1863201099468403, 1.6328549117346856, -1.7078288405893842, ... ]

}, {

"heights" : [ 1.6043904836424177, -2.0736538674414025, 0.9898266674373053, ... ]

} ]

Result2:

scriptedResult object [ArrayList]

scriptedResult [-41.279615707402876,

-60.88007362339038,

38.823270659734256,

14.840192739445632,

11.300902755741326]

Result3:

scriptedResult object [Double]

scriptedResult [2.171917696507009]

2、Bucket Aggregations(桶聚合)

1) 、Global Aggregation(整体聚合)

1、Prepare aggregation request

AggregationBuilders

.global("agg")

.subAggregation(AggregationBuilders.terms("genders").field("gender"));

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.global.Global;

// sr is here your SearchResponse object

Global agg = sr.getAggregations().get("agg");

agg.getDocCount(); // Doc count

2)、FilterAggregation(过滤聚合)

1、Prepare aggregation request

AggregationBuilders

.filter("agg", QueryBuilders.termQuery("gender", "male"));

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.filter.Filter;

// sr is here your SearchResponse object

Filter agg = sr.getAggregations().get("agg");

agg.getDocCount(); // Doc count

3)、FilterAggregation(多过滤聚合)

1、Prepare aggregation request

AggregationBuilder aggregation =

AggregationBuilders

.filters("agg",

new FiltersAggregator.KeyedFilter("men", QueryBuilders.termQuery("gender", "male")),

new FiltersAggregator.KeyedFilter("women", QueryBuilders.termQuery("gender", "female")));

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.filters.Filters;

// sr is here your SearchResponse object

Filters agg = sr.getAggregations().get("agg");

// For each entry

for (Filters.Bucket entry : agg.getBuckets()) {

String key = entry.getKeyAsString();            // bucket key

long docCount = entry.getDocCount();            // Doc count

logger.info("key [{}], doc_count [{}]", key, docCount);

}

4) 、Missing Aggregation(失踪聚合)

1、Prepare aggregation request

AggregationBuilders.missing("agg").field("gender");

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.missing.Missing;

// sr is here your SearchResponse object

Missing agg = sr.getAggregations().get("agg");

agg.getDocCount(); // Doc count

5)、Nested Aggregation(嵌套聚合)

1、Prepare aggregation request

AggregationBuilders

.nested("agg", "resellers");

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.nested.Nested;

// sr is here your SearchResponse object

Nested agg = sr.getAggregations().get("agg");

agg.getDocCount(); // Doc count

6)、Reverse Nested Aggregation(反向嵌套聚合)

1、Prepare aggregation request

AggregationBuilder aggregation =

AggregationBuilders

.nested("agg", "resellers")

.subAggregation(

AggregationBuilders

.terms("name").field("resellers.name")

.subAggregation(

AggregationBuilders

.reverseNested("reseller_to_product")

)

);

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.nested.Nested;

import org.elasticsearch.search.aggregations.bucket.nested.ReverseNested;

import org.elasticsearch.search.aggregations.bucket.terms.Terms;

// sr is here your SearchResponse object

Nested agg = sr.getAggregations().get("agg");

Terms name = agg.getAggregations().get("name");

for (Terms.Bucket bucket : name.getBuckets()) {

ReverseNested resellerToProduct = bucket.getAggregations().get("reseller_to_product");

resellerToProduct.getDocCount(); // Doc count

}

6)、Children Aggregation(子聚合)

1、Prepare aggregation request

// "agg" is the name of the aggregation and "reseller" is the child // type

AggregationBuilder aggregation =

AggregationBuilders

.children("agg", "reseller");

2、Use aggregation response

import org.elasticsearch.join.aggregations.Children;

// sr is here your SearchResponse object

Children agg = sr.getAggregations().get("agg");

agg.getDocCount(); // Doc count

7)、Terms Aggregation(条件聚合)

1、Prepare aggregation request

AggregationBuilders

.terms("genders")

.field("gender");

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.terms.Terms;

// sr is here your SearchResponse object

Terms genders = sr.getAggregations().get("genders");

// For each entry

for (Terms.Bucket entry : genders.getBuckets()) {

entry.getKey();      // Term

entry.getDocCount(); // Doc count

}

Order(true升序,false降序)

1、按照分组字段的数量排序

AggregationBuilders

.terms("genders")

.field("gender")

.order(Terms.Order.count(true))

2、按照分组字段的照字母顺序排序

AggregationBuilders

.terms("genders")

.field("gender")

.order(Terms.Order.term(true))

3、按照聚合名称标识进行排序

AggregationBuilders

.terms("genders")

.field("gender")

.order(Terms.Order.aggregation("avg_height", false))

.subAggregation(

AggregationBuilders.avg("avg_height").field("height")

)

8)、Significant Terms Aggregation(子条件聚合)

1、Prepare aggregation request

AggregationBuilder aggregation =

AggregationBuilders

.significantTerms("significant_countries")

.field("address.country");

// Let say you search for men only

SearchResponse sr = client.prepareSearch()

.setQuery(QueryBuilders.termQuery("gender", "male"))

.addAggregation(aggregation)

.get();

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.significant.SignificantTerms;

// sr is here your SearchResponse object

SignificantTerms agg = sr.getAggregations().get("significant_countries");

// For each entry

for (SignificantTerms.Bucket entry : agg.getBuckets()) {

entry.getKey();      // Term

entry.getDocCount(); // Doc count

}

9)、Range Aggregation(范围聚合)

1、Prepare aggregation request

AggregationBuilder aggregation =

AggregationBuilders

.range("agg")

.field("height")

.addUnboundedTo(1.0f)

// from -infinity to 1.0 (excluded)

.addRange(1.0f, 1.5f)

// from 1.0 to 1.5 (excluded)

.addUnboundedFrom(1.5f);

// from 1.5 to +infinity

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.range.Range;

// sr is here your SearchResponse object

Range agg = sr.getAggregations().get("agg");

// For each entry

for (Range.Bucket entry : agg.getBuckets()) {

String key = entry.getKeyAsString();             // Range as key

Number from = (Number) entry.getFrom();          // Bucket from

Number to = (Number) entry.getTo();              // Bucket to

long docCount = entry.getDocCount();    // Doc count

logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, from, to, docCount);

}

3、result

key [*-1.0], from [-Infinity], to [1.0], doc_count [9]

key [1.0-1.5], from [1.0], to [1.5], doc_count [21]

key [1.5-*], from [1.5], to [Infinity], doc_count [20]

10)、Date Range Aggregation(日期范围聚合)

1、Prepare aggregation request

AggregationBuilder aggregation =

AggregationBuilders

.dateRange("agg")

.field("dateOfBirth")

.format("yyyy")

.addUnboundedTo("1950")

// from -infinity to 1950 (excluded)

.addRange("1950", "1960")

// from 1950 to 1960 (excluded)

.addUnboundedFrom("1960");

// from 1960 to +infinity

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.range.Range;

// sr is here your SearchResponse object

Range agg = sr.getAggregations().get("agg");

// For each entry

for (Range.Bucket entry : agg.getBuckets()) {

// Date range as key

String key = entry.getKeyAsString();

// Date bucket from as a Date

DateTime fromAsDate = (DateTime) entry.getFrom();

// Date bucket to as a Date

DateTime toAsDate = (DateTime) entry.getTo();

// Doc count

long docCount = entry.getDocCount();

logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, fromAsDate, toAsDate, docCount);

}

3、result

key [*-1950], from [null], to [1950-01-01T00:00:00.000Z], doc_count [8]

key [1950-1960], from [1950-01-01T00:00:00.000Z], to [1960-01-01T00:00:00.000Z], doc_count [5]

key [1960-*], from [1960-01-01T00:00:00.000Z], to [null], doc_count [37]

11)、IP Range Aggregation(IP范围聚合)

1、Prepare aggregation request

AggregatorBuilder<?> aggregation =

AggregationBuilders

.ipRange("agg")

.field("ip")

// from -infinity to 192.168.1.0 (excluded)

.addUnboundedTo("192.168.1.0")

// from 192.168.1.0 to 192.168.2.0(excluded)

.addRange("192.168.1.0", "192.168.2.0")

// from 192.168.2.0 to +infinity

.addUnboundedFrom("192.168.2.0");

AggregatorBuilder<?> aggregation =

AggregationBuilders

.ipRange("agg")

.field("ip")

.addMaskRange("192.168.0.0/32")

.addMaskRange("192.168.0.0/24")

.addMaskRange("192.168.0.0/16");

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.range.Range;

// sr is here your SearchResponse object

Range agg = sr.getAggregations().get("agg");

// For each entry

for (Range.Bucket entry : agg.getBuckets()) {

// Ip range as key

String key = entry.getKeyAsString();

// Ip bucket from as a String

String fromAsString = entry.getFromAsString();

// Ip bucket to as a String

String toAsString = entry.getToAsString();

// Doc count

long docCount = entry.getDocCount();

logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, fromAsString, toAsString, docCount);

}

3、result

key [*-192.168.1.0], from [null], to [192.168.1.0], doc_count [13]

key [192.168.1.0-192.168.2.0], from [192.168.1.0], to [192.168.2.0], doc_count [14]

key [192.168.2.0-*], from [192.168.2.0], to [null], doc_count [23]

Result 2:

key [192.168.0.0/32], from [192.168.0.0], to [192.168.0.1], doc_count [0]

key [192.168.0.0/24], from [192.168.0.0], to [192.168.1.0], doc_count [13]

key [192.168.0.0/16], from [192.168.0.0], to [192.169.0.0], doc_count [50]

12)、Histogram Aggregation(柱状图聚合)

1、Prepare aggregation request

AggregationBuilder aggregation =

AggregationBuilders

.histogram("agg")

.field("height")

.interval(1);

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;

// sr is here your SearchResponse object

Histogram agg = sr.getAggregations().get("agg");

// For each entry

for (Histogram.Bucket entry : agg.getBuckets()) {

Number key = (Number) entry.getKey();   // Key

long docCount = entry.getDocCount();    // Doc count

logger.info("key [{}], doc_count [{}]", key, docCount);

}

13)、Date Histogram Aggregation(日期柱状图聚合)

1、Prepare aggregation request

AggregationBuilder aggregation =

AggregationBuilders

.dateHistogram("agg")

.field("dateOfBirth")

.dateHistogramInterval(DateHistogramInterval.YEAR);

如果想获取最近十天的数据(相对时间):

AggregationBuilder aggregation =

AggregationBuilders

.dateHistogram("agg")

.field("dateOfBirth")

.dateHistogramInterval(DateHistogramInterval.days(10));

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;

// sr is here your SearchResponse object

Histogram agg = sr.getAggregations().get("agg");

// For each entry

for (Histogram.Bucket entry : agg.getBuckets()) {

DateTime key = (DateTime) entry.getKey();    // Key

String keyAsString = entry.getKeyAsString(); // Key as String

long docCount = entry.getDocCount();         // Doc count

logger.info("key [{}], date [{}], doc_count [{}]", keyAsString, key.getYear(), docCount);

}

3、result

key [1942-01-01T00:00:00.000Z], date [1942], doc_count [1]

key [1945-01-01T00:00:00.000Z], date [1945], doc_count [1]

key [1946-01-01T00:00:00.000Z], date [1946], doc_count [1]

...

key [2005-01-01T00:00:00.000Z], date [2005], doc_count [1]

key [2007-01-01T00:00:00.000Z], date [2007], doc_count [2]

key [2008-01-01T00:00:00.000Z], date [2008], doc_count [3]

14)、Geo Distance Aggregation(地理距离聚合)

1、Prepare aggregation request

AggregationBuilder aggregation =

AggregationBuilders

.geoDistance("agg", new GeoPoint(48.84237171118314,2.33320027692004))

.field("address.location")

.unit(DistanceUnit.KILOMETERS)

.addUnboundedTo(3.0)

.addRange(3.0, 10.0)

.addRange(10.0, 500.0);

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.range.Range;

// sr is here your SearchResponse object

Range agg = sr.getAggregations().get("agg");

// For each entry

for (Range.Bucket entry : agg.getBuckets()) {

String key = entry.getKeyAsString();    // key as String

Number from = (Number) entry.getFrom(); // bucket from value

Number to = (Number) entry.getTo();     // bucket to value

long docCount = entry.getDocCount();    // Doc count

logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, from, to, docCount);

}

3、result

key [*-3.0], from [0.0], to [3.0], doc_count [161]

key [3.0-10.0], from [3.0], to [10.0], doc_count [460]

key [10.0-500.0], from [10.0], to [500.0], doc_count [4925]

15) 、Geo Hash Grid Aggregation(地理哈希网格聚合)

1、Prepare aggregation request

AggregationBuilder aggregation =

AggregationBuilders

.geohashGrid("agg")

.field("address.location")

.precision(4);

2、Use aggregation response

import org.elasticsearch.search.aggregations.bucket.geogrid.GeoHashGrid;

// sr is here your SearchResponse object

GeoHashGrid agg = sr.getAggregations().get("agg");

// For each entry

for (GeoHashGrid.Bucket entry : agg.getBuckets()) {

String keyAsString = entry.getKeyAsString(); // key as String

GeoPoint key = (GeoPoint) entry.getKey();    // key as geo point

long docCount = entry.getDocCount();         // Doc count

logger.info("key [{}], point {}, doc_count [{}]", keyAsString, key, docCount);

}

3、result

key [gbqu], point [47.197265625, -1.58203125], doc_count [1282]

key [gbvn], point [50.361328125, -4.04296875], doc_count [1248]

key [u1j0], point [50.712890625, 7.20703125], doc_count [1156]

key [u0j2], point [45.087890625, 7.55859375], doc_count [1138]

...

3、Pipeline Aggregations(管道聚合)

4、Matrix Aggregations(矩阵聚合)

Caching heavy aggregations

Returning only aggregation results

Aggregation Metadata

Returning the type of the aggregation

Elasticsearch 5.x Java api Aggregations(聚合)相关推荐

  1. Es elasticsearch 十七 Java api 实现聚合 几个聚合示例 sql 开启许可 新特效 java 实现es7 sql 功能

    目录 Java api 实现聚合 依赖 简单聚合按照颜色分组获取每个卖出数量 聚合每个颜色卖出数量,及平均价格(每个分桶子聚合) 按照颜色分组 ,获取销售数量,avg min max sum 按照60 ...

  2. ElasticSearch入门-搜索(java api)

    ElasticSearch入门-搜索(java api) package com.qlyd.searchhelper;import java.util.Map;import net.sf.json.J ...

  3. es java api 进行聚合+桶聚合查询

    假设1个member有多个参加的meeting(会议),每个meeting可多次参加,每次参加对应一条参加时间和备注记录 需求: 获取某个member的所有meeting的最新一条记录 查询语句 {& ...

  4. es java api 子查询_elasticsearch elk最全java api 搜索 聚合、嵌套查询

    目录 matchAllQuery()方法用来匹配全部文档 public static void matchAllQuery(Client client ) { SearchResponse res = ...

  5. Elasticsearch Java API 6.2(java client)

    前言 本节描述了Elasticsearch提供的Java API,所有的Elasticsearch操作都使用客户端对象执行,所有操作本质上都是完全异步的(要么接收监听器,要么未来返回). 此外,客户端 ...

  6. Elasticsearch Java API四种实现方式

    0.题记 之前Elasticsearch的应用比较多,但大多集中在关系型.非关系型数据库与Elasticsearch之间的同步.以上内容完成了Elasticsearch所需要的基础数据量的供给.但想要 ...

  7. ElasticSearch java API - 聚合查询-聚合多字段聚合demo

    以球员信息为例,player索引的player type包含5个字段,姓名,年龄,薪水,球队,场上位置. index的mapping为: "mappings": {"pl ...

  8. Elasticsearch Java API 的使用(13)—分组聚合之一

    分组聚和不像度量聚合那样通过字段进行计算,而是根据文档创建分组.每个聚合都关联一个标准(取决于聚合的类型),决定了一个文档在当前的条件下是否会"划入"分组中. 换句话说,分组实际上 ...

  9. Elasticsearch Java API 分组、聚合、嵌套相关查询

    Elasticsearch Java API 分组.聚合.嵌套相关查询 翼支付监控系统正使用es做后端存储,这边我们是将日志计算处理过后的数据通过kafka储存到es.选择用es作为数据储存端是考虑到 ...

最新文章

  1. Linux下通用的Makefile
  2. openshift_通过OpenShift超越云炒作
  3. Windows To Ghost系统封装之必备软件集 - 好压
  4. JZOJ 3515. 软件公司
  5. c语言散列表的长度为11,2011数据结构C语言模拟试题及答案.doc
  6. bugfree如何修改Bug7种解决方案的标注方法 .
  7. 玉龙雪山还会存在多久
  8. esp8266 OTA 云远程更新固件 wifiupdate
  9. linux系统无法识别固态硬盘_重装Linux操作系统为什么识别不了硬盘
  10. 中科大科学岛计算机博士,2017年科学岛分院博士研究生招生拟录取名单公示
  11. 腾讯云音视频及融合通信技术
  12. duilib适配高分屏(高DPI适配)
  13. github使用ssh方式
  14. 职高生学计算机的走单招服装设计可以吗,2019年江西科技学院服装与服饰设计专业介绍...
  15. 初级SQL开发汇总指南
  16. 面向对象三大特性-多态
  17. (五)深入理解蓝牙BLE之“Beacon包格式详解”
  18. 如何修改文件的创建时间和修改时间?
  19. 圆、球的体积、表面积
  20. 不可抗力/(ㄒoㄒ)/~~ 开始学习node全栈<四>express Web框架

热门文章

  1. 励志暖心英语短文-改变我的那个瞬间
  2. 【datawhale202206】pyTorch推荐系统:多任务学习 ESMMMMOE
  3. Google Chrome浏览器使用技巧
  4. 【聆思CSK6 视觉AI开发套件试用】体验头肩检测和手势识别初体验
  5. Java开发自学技巧!链表反转的两种实现方法,太香了
  6. 云南电信DNS服务器地址
  7. 关于travis scott的网名_qq心碎伤感网名2020最新
  8. HBase系列从入门到精通(三)
  9. 阿里Redis最全面试全攻略,读完这个就可以和阿里面试官好好聊聊
  10. 基于PP-PicoDet的钢铁缺陷检测