ElasticSearch聚合查询

ElasticSearch聚合查询

private static void searchAgg() {
       
        TermsAggregationBuilder urlAggBuilder = AggregationBuilders.terms("urlAgg").field("url").size(5);
        SearchResponse sr = client.prepareSearch(indexname).setQuery(null).addAggregation(urlAggBuilder).execute()
                .actionGet();
        sr.getAggregations();

        Map aggMap = sr.getAggregations().asMap();
        StringTerms urlTerms = (StringTerms) aggMap.get("urlAgg");

        Iterator urlBucketIt = urlTerms.getBuckets().iterator();

        while (urlBucketIt.hasNext()) {
           
            Bucket urlBucket = urlBucketIt.next();
            if (!urlBucket.getKey().toString().equals("")) {
               
                if (urlBucket.getDocCount() > 1) {
                   
                    String url = urlBucket.getKey().toString();
                    QueryBuilder query = QueryBuilders.matchQuery("url", url);
                   
                    SearchResponse searchResponse = client.prepareSearch(indexname)
                            .setTypes(type)
                            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                            .setQuery(query)
                            .setSize(50)
                            .execute().actionGet();
                   
                    SearchHits hits = searchResponse.getHits();

                    List idList = new ArrayList();
                    for (SearchHit hit : hits) {
                       
                        JSONObject jsonObject = new JSONObject(hit.getSourceAsString());
                       
                        String current = jsonObject.getString("current_time").toString();
                        if (current.equals("2017-04-13")) {
                            idList.add(hit.getId());
                        }
                    }

                    for (int i = 1; i < idList.size(); i++) {
                        client.prepareDelete("info", "info", idList.get(i)).execute().actionGet();
                    }
                }
            }
        }
    }

你可能感兴趣的:(ElasticSearch聚合查询)