{ "query": { "match": { "productName": { "query": "牛奶" } } }, "aggs": { "shopIdagg": { "terms": { "field": "productId", "order": { "top_hit": "desc" } }, "aggs": { "maxP": { "max": { "field": "salesPrice" } }, "top_test": { "top_hits": { "sort": { "_score": "desc", "salesPrice": "desc" } } }, "top_hit": { "max": { "script": "_score" } } } } }}
Java客户端代码为:
int currentPage = 2; int pageSize = 10; int count = currentPage * pageSize; try { Client client = EsCollectionIk.getCollectionForIk(index); TermsBuilder placeProductGroup = AggregationBuilders.terms("placeProduct_group").field("productId").size(count); Order top_hit_order = Order.aggregation("top_hit", false); placeProductGroup.order(Order.compound(top_hit_order)); XContentBuilder maxPriceJsonBuilder = XContentFactory.jsonBuilder() .startObject() .startObject("max_price") .startObject("max").field("field", "salesPrice").endObject() .endObject() .startObject("top_test") .startObject("top_hits") .startObject("sort") .field("_score", "desc") .field("salesPrice", "desc") .endObject() .field("size", 1).endObject() .endObject() .startObject("top_hit").startObject("max").field("script", "_score").endObject().endObject() .endObject(); maxPriceJsonBuilder.string(); placeProductGroup.subAggregation(maxPriceJsonBuilder); SearchRequestBuilder builder = client.prepareSearch(index) .setTypes(EsCollectionIk.analyzerType) .setFrom(0).setSize(10) .setQuery(QueryBuilders.matchQuery("productName", "牛奶")) .addAggregation(placeProductGroup); SearchResponse resp = builder.execute().actionGet(); SearchHits sHits = resp.getHits(); SearchHit[] hits = sHits.getHits(); float time = resp.getTookInMillis() / 1000f; System.out.println("找到约 " + sHits.getTotalHits() + " 条结果 (用时" + time + "秒) "); System.out.println("resp: "); System.out.println(resp); System.out.println(); StringTerms outAggre = resp.getAggregations().get("placeProduct_group"); Listbuckets = outAggre.getBuckets(); System.out.println("hits: " + hits.length + "; buckets: " + buckets.size()); System.out.println(""); //搜索结果, 对分组无用 /*for (SearchHit hit : hits) { Map source = hit.getSource(); System.out.println("source: " + source); }*/ System.out.println(""); int begin = pageSize * (currentPage - 1); int end = Math.min(begin + pageSize, buckets.size()); for (int i = begin; i < end; i++) { //InternalMax maxPrice = aggre.get("max_price"); //String maxSalesPrice = maxPrice.getValueAsString(); Bucket bucket = buckets.get(i); Aggregations aggre = bucket.getAggregations(); InternalTopHits topHits = aggre.get("top_test"); SearchHits searchHits = topHits.getHits(); for (SearchHit shit : searchHits) { Map source = shit.getSource(); //String hitSalesPrice = String.valueOf(source.get("salesPrice")); //System.out.println("maxSalesPrice: " + maxSalesPrice + "; hitSalesPrice: " + hitSalesPrice); System.out.println("分组查询结果: " + source); break; } } } catch (IOException e) { e.printStackTrace(); }}
留着有时间好好看看。