Java 使用dsl操作es直接调用
时间: 2023-06-30 21:21:05 浏览: 179
Java使用DSL操作ES可以通过Elasticsearch Java High Level REST Client实现。以下是一个简单的示例代码:
```java
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 查询文档
SearchRequest searchRequest = new SearchRequest("index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("field", "value"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 添加文档
IndexRequest indexRequest = new IndexRequest("index");
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("field1", "value1");
jsonMap.put("field2", "value2");
indexRequest.source(jsonMap);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
// 更新文档
UpdateRequest updateRequest = new UpdateRequest("index", "id");
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("field1", "new value1");
jsonMap.put("field2", "new value2");
updateRequest.doc(jsonMap);
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
// 删除文档
DeleteRequest deleteRequest = new DeleteRequest("index", "id");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
client.close(); // 关闭连接
```
在使用DSL操作ES时,需要创建一个`RestHighLevelClient`实例,并且在操作完毕后需要关闭连接。以上示例代码演示了如何使用DSL操作ES进行查询、添加、更新和删除文档。需要注意的是,具体的查询条件和操作方式需要根据实际需求进行调整。
阅读全文