pom文件:
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.2.0</version> </dependency>
创建client(client可以关闭, 建议在停止应用前调用close() 方法):
RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("10.8.3.55", 9200, "http")));
// 1. 检测索引是否存在(所有和索引有关的操作全部推荐用org.elasticsearch.client.indices包下的类) GetIndexRequest request = new GetIndexRequest("twitter"); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists);
// 2. 创建索引 CreateIndexRequest request = new CreateIndexRequest("twitter"); request.settings(Settings.builder() .put("index.number_of_shards", 1) .put("index.number_of_replicas", 1) ); // 第一种 request.mapping("{\"properties\":{\"msg\":{\"type\":\"text\"}}}", XContentType.JSON); // 第二种 Map<String, Object> properties = new HashMap<>();// properties Map<String, Object> message = new HashMap<>(); message.put("type", "text"); properties.put("message", message);// 添加映射 Map<String, Object> username = new HashMap<>(); username.put("type", "keyword"); properties.put("username", username);// 添加映射 Map<String, Object> mapping = new HashMap<>(); mapping.put("properties", properties); request.mapping(mapping); CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); System.out.println(createIndexResponse.index());
// 3. 增加文档(如果类注释推荐使用org.elasticsearch.client.Requests来创建类,最好用他推荐的方式) IndexRequest request = Requests.indexRequest("twitter"); request.id("1");// 指定ID request.source("message", "消息内容...abc", "username", "jack 杰克");// 支持多种方式 IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); System.out.println(indexResponse);
// 4. 修改文档 UpdateRequest request = new UpdateRequest("twitter", "1"); request.doc("message", "修改之后的消息内容...abc", "username", "修改之后的jack 杰克");// 支持多种方式 UpdateResponse response = client.update(request, RequestOptions.DEFAULT); System.out.println(response);
// 5. Bulk BulkRequest request = new BulkRequest(); request.add(new DeleteRequest("twitter", "1")); request.add(new UpdateRequest("twitter", "2") .doc(XContentType.JSON,"username", "jack===")); request.add(new IndexRequest("twitter").id("3") .source(XContentType.JSON,"username", "jack222")); BulkResponse response = client.bulk(request, RequestOptions.DEFAULT); System.out.println(response.hasFailures());
// 6. 根据ID获取文档 GetRequest request = Requests.getRequest("twitter").id("2"); GetResponse response = client.get(request, RequestOptions.DEFAULT); System.out.println(response.getSourceAsString());
// 7. Search SearchRequest request = new SearchRequest("twitter"); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchAllQuery());
request.source(builder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); Iterator<SearchHit> hits = response.getHits().iterator(); ObjectMapper mapper = new ObjectMapper(); List<Person> personList = new ArrayList<>(); while (hits.hasNext()) { personList.add(mapper.readValue(hits.next().getSourceAsString(), Person.class)); } System.out.println(personList);
查询聚合DSL语句构建使用 SearchSourceBuilder:
// 样例 伪代码:
// SearchSourceBuilder builder = new SearchSourceBuilder(); // String[] include = {"timeStamp", // "msgBody.boxList.boxStatus.boxCurrent", // "msgBody.boxList.batInfo.batSN", // "msgBody.boxList.batStatus.batCurrent", // "msgBody.boxList.batStatus.batVoltage", // "msgBody.boxList.batStatus.batRSOC"}; // builder.query(QueryBuilders.boolQuery() //// .filter(QueryBuilders.termQuery("msgBody.boxList.batInfo.batSN", "BAA2118122200104")) // .filter(QueryBuilders.rangeQuery("timeStamp").gte(1557729000).lte(1557741600))) // .sort("timeStamp", SortOrder.ASC) // .from(0) // .size(100).fetchSource(include, null); //// builder.aggregation(AggregationBuilders.terms("data_count").field("deviceInfo.deviceSN")).size(0);
聚合结果分析参考: https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/_bucket_aggregations.html
获取聚合必须要指定相关的类 如 Terms:
Terms data = response.getAggregations().get("data_count"); System.out.println(data.getBuckets().get(0).getKey()); System.out.println(data.getBuckets().get(0).getDocCount()); System.out.println(response.toString());