赞
踩
版本:elasticsearch7.14
1、Index API | Java REST Client [7.14] | Elastic
搜索:
2、 Search API | Java REST Client [7.14] | Elastic
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.14/java-rest-high-search.html
RestHighLevelClient的maven依赖为(使用前必须添加相应依赖)
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.14.0</version> </dependency>
注意:以上的依赖版本可以根据你使用的ES的版本来定,向下兼容,但是无法向上兼容
- private RestHighLevelClient esRestClient = null;
-
- /**
- * 创建客户端连接
- */
- public void restClientConnect(String IP,int PORT){
- RestHighLevelClient restClient=null;
- try {
- RestClientBuilder builder = RestClient.builder(new HttpHost(IP, PORT, "http"));
- restClient= new RestHighLevelClient(builder);
- }catch (Exception e){
- log.error(e.toString());
- }
- this.esRestClient = restClient;
- }
-
-
- /**
- * 关闭客户端
- */
- public void closeEs() {
- try {
- if(esRestClient !=null) {
- esRestClient.close();
- }
- }catch (IOException e){
- e.printStackTrace();
- }
- }
RestHighLevelClient 支持对ES的增删改查、批量操作
- /**
- * 往索引插入文档数据,随机id插入数据
- * @param indexName 索引名称
- * @param jsonStr Json数据
- */
- public void addData(String indexName,String jsonStr){
- addData(indexName,jsonStr,null);
- }
-
- /**
- * 往索引插入文档数据
- * @param indexName 索引名称
- * @param jsonStr Json数据
- * @param id id
- */
-
- public void addData(String indexName,String jsonStr,String id){
- IndexRequest request = new IndexRequest(indexName);
- if(id !=null){
- request.id(id);
- }
- request.source(jsonStr, XContentType.JSON);
- request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);//插入完成后立即强制刷新索引
- try {
- IndexResponse response = esRestClient.index(request,RequestOptions.DEFAULT);
- log.info("addData: "+response.getShardInfo()+" ,indexName:"+indexName);
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
查询支持直接查询和条件查询,由于ES是根据索引、文档类型和文档ID确定一个唯一的文档的,所以直接查询必须要有索引和类型还有ID。
- /**
- * 根据条件获取文档数据
- * @param indexName 索引名称
- */
- public void getData(String indexName) {
- //1 创建搜索文档请求
- SearchRequest searchRequest=new SearchRequest(indexName); //请求索引
- try{
- // 2 执行检索
- SearchResponse response = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
- // 3 分析响应结果
- //System.out.println(response.toString());
- //遍历数据
- SearchHit[] hits = response.getHits().getHits();
- for (SearchHit hit : hits) {
- Map<String, Object> sourceAsMap = hit.getSourceAsMap();
- log.info("getData: "+sourceAsMap.toString()+" ,indexName:"+indexName);
-
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 根据条件获取文档数据
- * @param indexName 索引名称
- * @param key 查询字段
- * @param value 查询值
- */
- public void getData(String indexName,String key,String value) {
- //1 创建搜索文档请求
- SearchRequest searchRequest=new SearchRequest(indexName); //请求索引
- SearchSourceBuilder builder = new SearchSourceBuilder();
- builder.query(QueryBuilders.matchQuery(key,value));
- searchRequest.source(builder);
- try{
- // 2 执行检索
- SearchResponse response = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
- // 3 分析响应结果
- log.info("getData: "+response.toString());
- //遍历数据
- SearchHit[] hits = response.getHits().getHits();
- for (SearchHit hit : hits) {
- //String sourceAsString = hit.getSourceAsString();
- //System.out.println(sourceAsString);
- Map<String, Object> sourceAsMap = hit.getSourceAsMap();
- log.info("getData: "+sourceAsMap+" ,indexName:"+indexName);
-
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 根据索引和id进行删除
- * @param indexName 索引名称
- * @param id id号
- */
- public void deleteData(String indexName,String id) {
- //创建删除文档请求
- DeleteRequest request = new DeleteRequest();
-
- //设置属性:指定要删除的索引及id值
- DeleteRequest delete = request.index(indexName).id(id);
- try {
- //执行删除请求
- DeleteResponse deleteResponse = esRestClient.delete(delete, RequestOptions.DEFAULT);
- if(deleteResponse.getResult().toString().equals("DELETED")){
- log.info("deleteData,删除成功,indexName: "+indexName+",id: "+id);
- }
- }catch (IOException e){
- e.printStackTrace();
- }
-
- }
-
-
- /**
- * 根据条件进行删除
- * @param indexName 索引名称
- * @param key 字段
- * @param value 值
- */
-
- public void deleteData(String indexName,String key,String value) {
- //1 设置条件
- //设置删除条件: key = value
- MatchQueryBuilder nameSelect = QueryBuilders.matchQuery(key, value);
-
- //通过QueryBuilders中的搜索逻辑
- BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
- queryBuilder.should(nameSelect);
-
- //2 通过DeleteByQueryRequest来构建删除请求,setQuery来装载条件,indices来指定索引
- DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
- deleteByQueryRequest.setQuery(queryBuilder);
- deleteByQueryRequest.indices(indexName); //指定删除索引
- try {
- //3 通过deleteByQuery来发起删除请求
- BulkByScrollResponse deleteResponse=esRestClient.deleteByQuery(deleteByQueryRequest , RequestOptions.DEFAULT);
- if(deleteResponse.getDeleted() >=1){
- log.info("deleteData,删除成功,删除文档条数: "+deleteResponse.getDeleted()+" ,indexName:"+indexName);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
- package elasticsearch;
-
- import org.apache.http.HttpHost;
- import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
-
- import org.elasticsearch.client.indices.CreateIndexRequest;
- import org.elasticsearch.client.indices.CreateIndexResponse;
-
- import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
- import org.elasticsearch.action.delete.DeleteRequest;
- import org.elasticsearch.action.delete.DeleteResponse;
- import org.elasticsearch.action.index.IndexRequest;
- import org.elasticsearch.action.index.IndexResponse;
- import org.elasticsearch.action.search.SearchRequest;
- import org.elasticsearch.action.search.SearchResponse;
- import org.elasticsearch.action.support.WriteRequest;
- import org.elasticsearch.action.support.master.AcknowledgedResponse;
- import org.elasticsearch.client.*;
- import org.elasticsearch.common.xcontent.XContentType;
- import org.elasticsearch.index.query.BoolQueryBuilder;
- import org.elasticsearch.index.query.MatchQueryBuilder;
- import org.elasticsearch.index.query.QueryBuilders;
- import org.elasticsearch.index.reindex.BulkByScrollResponse;
- import org.elasticsearch.index.reindex.DeleteByQueryRequest;
- import org.elasticsearch.search.SearchHit;
- import org.elasticsearch.search.builder.SearchSourceBuilder;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
-
- import java.io.IOException;
- import java.util.Map;
-
-
- /**
- * ClassName EsTest
- * description EsTest
- *
- * @author : HMF
- * date: 2022/8/18 9:35
- **/
-
-
- public class EsTest {
- protected static Logger log = LoggerFactory.getLogger(EsTest.class);
- private RestHighLevelClient esRestClient = null;
-
- /**
- * 创建客户端
- */
- public void restClientConnect(String IP,int PORT){
- RestHighLevelClient restClient=null;
- try {
- RestClientBuilder builder = RestClient.builder(new HttpHost(IP, PORT, "http"));
- restClient= new RestHighLevelClient(builder);
- }catch (Exception e){
- log.error(e.toString());
- }
- this.esRestClient = restClient;
- }
-
-
- /**
- * 往索引插入文档数据,随机id插入数据
- * @param indexName 索引名称
- * @param jsonStr Json数据
- */
- public void addData(String indexName,String jsonStr){
- addData(indexName,jsonStr,null);
- }
-
- /**
- * 往索引插入文档数据
- * @param indexName 索引名称
- * @param jsonStr Json数据
- * @param id id
- */
-
- public void addData(String indexName,String jsonStr,String id){
- IndexRequest request = new IndexRequest(indexName);
- if(id !=null){
- request.id(id);
- }
- request.source(jsonStr, XContentType.JSON);
- request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);//插入完成后立即强制刷新索引
- try {
- IndexResponse response = esRestClient.index(request,RequestOptions.DEFAULT);
- log.info("addData: "+response.getShardInfo()+" ,indexName:"+indexName);
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 根据条件获取文档数据
- * @param indexName 索引名称
- */
- public void getData(String indexName) {
- //1 创建搜索文档请求
- SearchRequest searchRequest=new SearchRequest(indexName); //请求索引
- try{
- // 2 执行检索
- SearchResponse response = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
- // 3 分析响应结果
- //System.out.println(response.toString());
- //遍历数据
- SearchHit[] hits = response.getHits().getHits();
- for (SearchHit hit : hits) {
- Map<String, Object> sourceAsMap = hit.getSourceAsMap();
- log.info("getData: "+sourceAsMap.toString()+" ,indexName:"+indexName);
-
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 根据条件获取文档数据
- * @param indexName 索引名称
- * @param key 查询字段
- * @param value 查询值
- */
- public void getData(String indexName,String key,String value) {
- //1 创建搜索文档请求
- SearchRequest searchRequest=new SearchRequest(indexName); //请求索引
- SearchSourceBuilder builder = new SearchSourceBuilder();
- builder.query(QueryBuilders.matchQuery(key,value));
- searchRequest.source(builder);
- try{
- // 2 执行检索
- SearchResponse response = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
- // 3 分析响应结果
- log.info("getData: "+response.toString());
- //遍历数据
- SearchHit[] hits = response.getHits().getHits();
- for (SearchHit hit : hits) {
- //String sourceAsString = hit.getSourceAsString();
- //System.out.println(sourceAsString);
- Map<String, Object> sourceAsMap = hit.getSourceAsMap();
- log.info("getData: "+sourceAsMap+" ,indexName:"+indexName);
-
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 根据索引和id进行删除
- * @param indexName 索引名称
- * @param id id号
- */
- public void deleteData(String indexName,String id) {
- //创建删除文档请求
- DeleteRequest request = new DeleteRequest();
-
- //设置属性:指定要删除的索引及id值
- DeleteRequest delete = request.index(indexName).id(id);
- try {
- //执行删除请求
- DeleteResponse deleteResponse = esRestClient.delete(delete, RequestOptions.DEFAULT);
- if(deleteResponse.getResult().toString().equals("DELETED")){
- log.info("deleteData,删除成功,indexName: "+indexName+",id: "+id);
- }
- }catch (IOException e){
- e.printStackTrace();
- }
-
- }
-
-
- /**
- * 根据条件进行删除
- * @param indexName 索引名称
- * @param key 字段
- * @param value 值
- */
-
- public void deleteData(String indexName,String key,String value) {
- //1 设置条件
- //设置删除条件: key = value
- MatchQueryBuilder nameSelect = QueryBuilders.matchQuery(key, value);
-
- //通过QueryBuilders中的搜索逻辑
- BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
- queryBuilder.should(nameSelect);
-
- //2 通过DeleteByQueryRequest来构建删除请求,setQuery来装载条件,indices来指定索引
- DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
- deleteByQueryRequest.setQuery(queryBuilder);
- deleteByQueryRequest.indices(indexName); //指定删除索引
- try {
- //3 通过deleteByQuery来发起删除请求
- BulkByScrollResponse deleteResponse=esRestClient.deleteByQuery(deleteByQueryRequest , RequestOptions.DEFAULT);
- if(deleteResponse.getDeleted() >=1){
- log.info("deleteData,删除成功,删除文档条数: "+deleteResponse.getDeleted()+" ,indexName:"+indexName);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-
-
- /**
- * 关闭客户端
- */
- public void closeEs() {
- try {
- if(esRestClient !=null) {
- esRestClient.close();
- }
- }catch (IOException e){
- e.printStackTrace();
- }
- }
-
-
- }
调用:
- public static void main(String[] args){
- EsTest es=new EsTest();
- es.restClientConnect("10.1.1.196",9200); //创建客户端连接ES
-
- String indexName="autotest_java";
- String jsonStr=" {\n" +
- " \"aoeId\": \"1\",\n" +
- " \"aoeAes\": \"李四\",\n" +
- " \"aoeSm4\": \"Beijing Refining Network Technology Co.Ltd.\",\n" +
- " \"aoeSm4A\": \"硬件开发工程师\",\n" +
- " \"aoeEmail\": \"qianxiulan@yahoo.com\",\n" +
- " \"aoePhone\": \"15652996964\",\n" +
- " \"aoeIdCard\": \"210302199608124861\",\n" +
- " \"aoeOfficerCard\": \"武水电字第3632734号\",\n" +
- " \"aoePassport\": \"BWP018930705\",\n" +
- " \"aoeGeneralIdCard\": \"0299233902\",\n" +
- " \"aoeCreditCard\": \"6212262502009182455\",\n" +
- " \"aoeString\":\"北京市海淀区恒润国际大厦710\"\n" +
- "}";
- es.addData(indexName,jsonStr);
-
- String key="aoeAes";
- String value="李四";
- es.getData(indexName,key,value);
- es.deleteData(indexName,key,value);
-
- //es.addData(indexName,jsonStr,"1");
- //es.getData(indexName);
- //es.deleteData(indexName,"1");
- es.closeEs();
-
-
- }
-
执行结果:
参考:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。