java实现从es查询数据并显示在前端的echart(全过程)

java实现从es查询数据并显示在前端的echart(全过程)

整个工作就是通过java实现从es中取得数据,并且对数据进行处理,得到需要的数据,然后显示在echart中。

使用httpclient连接es

CloseableHttpClient httpclient = HttpClientBuilder.create().build(); // 创建默认的httpClient实例. 	
StringBuffer param = new StringBuffer();
param.append("test-2019-02/_search?pretty");
HttpPost httppost = new HttpPost(url+param); // 创建httppost

这段是使用httpclient连接es,需要在请求中添加url和param,param是固定的,这里我给写死了,而我创建的方法是

public static String post(String url, String jsonString) throws IOException

所以在调用这个方法的时候加入网址就行。

数据封装

数据封装就是将查询语句封装起来,我通过map进行封装,就是通过最里面的键值对开始,依次向外扩展,实现将查询语句的键值对全部封装进map中。

		SONObject extended_bounds=new JSONObject();
        extended_bounds.put("min","2019-01-07 00:00:00");
        extended_bounds.put("max","2019-01-08 23:00:00");
        JSONObject date_histogram=new JSONObject();
        date_histogram.put("field","beginTimeStr111");
        date_histogram.put("interval","hour");
        date_histogram.put("format","yyyy-MM-dd HH:mm:ss");
        date_histogram.put("time_zone","+08:00");
        date_histogram.put("min_doc_count",0);
        date_histogram.put("extended_bounds",extended_bounds);
        ......

最后返回一个封装好的map,将map也作为url传入请求

数据处理

 String str1=JSON.toJSONString(strjson);
 String str=EsConnectionUtil.post("http://172.18.232.197:9200/",str1);

封装好的map是strjson,取得数据是str,对取得数据进行处理

		JSONObject jsonObject=JSONObject.parseObject(str);
        JSONArray jsonArray=jsonObject.getJSONObject("aggregations").getJSONObject("group_by_time").getJSONArray("buckets");

这是获取所有结果中你所需的数据,然后可以通过遍历将这些数据全部放入list中。

ajax请求并显示在echart中

取得处理后的数据后,就需要传入前端,而这里使用的是ajax请求,然后传入echart中,在ajax中写入请求路径,这是会根据请求路径调用一个controller类,然后返回值进入到ajax中的function中,将数据取出来放入横纵坐标即可。
最后实现表格如下:
java实现从es查询数据并显示在前端的echart(全过程)_第1张图片

你可能感兴趣的:(工作笔记)