qq_37243472
热爱编程,热爱生活
2020-01-13 10:41
采纳率: 50%
浏览 1.1k

根据sql,es的查询条件,怎么用java es api写出来。

Sql:

select hour,count(*),avg(billDuration) 
from tab
where customerNumber ='13201646126'
group by hour

es:

GET cdr_20200110/_search
{
  "size": 3, 
  "query": {
    "term": {
      "customerNumber": "13201646126"
    }
  },
  "aggs": {
    "hour_sum": {
      "terms":{
        "field": "hour"
      },
      "aggs": {
        "avg_bill": {
          "avg": {
            "field": "billDuration"
          }
        }
      }
    }
  }
}

自己写了个不知道对不对

TermQueryBuilder termQueryBuilder =  QueryBuilders.termQuery("customerNumber","13201646126");
        AggregationBuilder aggsBuilder = AggregationBuilders.filter("hour_sum",termQueryBuilder);
        TermsAggregationBuilder terms = AggregationBuilders.terms("hour");
        AvgAggregationBuilder avgs =AggregationBuilders.avg("avg_bill").field("billDuration");
        terms.subAggregation(avgs);
        terms.subAggregation(aggsBuilder);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • qq_23292875
    Hefei19881002 2020-01-13 14:31
    这个方式比较难搞啊,看看我的 如果有用的话别忘记采纳
        public void search() throws IOException {
        RestClient client = RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")).build();
        String dsl = "{" + 
                "  \"size\": 3, " + 
                "  \"query\": {" + 
                "    \"term\": {" + 
                "      \"customerNumber\": \"13201646126\"" + 
                "    }" + 
                "  }," + 
                "  \"aggs\": {" + 
                "    \"hour_sum\": {" + 
                "      \"terms\":{" + 
                "        \"field\": \"hour\"" + 
                "      }," + 
                "      \"aggs\": {" + 
                "        \"avg_bill\": {" + 
                "          \"avg\": {" + 
                "            \"field\": \"billDuration\"" + 
                "          }" + 
                "        }" + 
                "      }" + 
                "    }" + 
                "  }" + 
                "}";
        HttpEntity entity = new NStringEntity(dsl,ContentType.APPLICATION_JSON);
        Response performRequest = client.performRequest("GET","cdr_20200110/_search",Collections.singletonMap("pretty", "true"), entity);
        JSONObject jsonobj = (JSONObject) JSONObject.parse(EntityUtils.toString( performRequest.getEntity()));
        System.out.println(jsonobj.toString());
    }
    
    点赞 评论

相关推荐