根据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个回答

这个方式比较难搞啊,看看我的 如果有用的话别忘记采纳
    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());
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐