赞
踩
Springboot 使用 RestClient 集成低版本 elasticsearch (es版本为5.4.2)
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.8.0</version>
</dependency>
@Bean public RestClient restClient() { RestClientBuilder builder = RestClient.builder( new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")); //配置超时时间 builder.setRequestConfigCallback( new RestClientBuilder.RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig( RequestConfig.Builder requestConfigBuilder) { return requestConfigBuilder.setSocketTimeout(10000).setConnectTimeout(60000); } }); //配置监听器,监控节点情况 builder.setFailureListener(new RestClient.FailureListener() { @Override public void onFailure(Node node) { super.onFailure(node); System.out.println(node.getHost() + "--->该节点失败了"); } }); return builder.build(); }
3.Elasticsearch 的基本操作
下面的方法都需要引用到步骤2创建的RestClient 实例
(1) 创建索引
/* * 低版本创建索引的方法 * @param index 索引 * @return String * */ * //引入第2步中创建的实例 @Autowired private RestClient restClient; public static int creatIndex(String index) { String result = "erro"; String method = "PUT"; String endpoint = index; System.out.println("creatIndex: "+index); try { Request request= new Request(method,endpoint); Response response = restClient.performRequest(request); int status = response.getStatusLine().getStatusCode(); return status; } catch (IOException e) { System.out.println(e.getMessage()); } return result; }
(2) 判断索引是否存在
/* *restClient方式检查索引是否存在 * @param index 索引 * @return boolean */ //引入第2步中创建的实例 @Autowired private RestClient restClient; public static boolean getIndex(String index){ boolean exists = false; try { Request request = new Request("HEAD", index); Response response = restClient.performRequest(request); int status = response.getStatusLine().getStatusCode(); if(status==200){ exists=true; return exists; } log.info("exists: " + exists); return exists; } catch (IOException e) { System.out.println(e.getMessage()); return false; } }
(3) 向索引插入数据
//引入第2步中创建的实例 @Autowired private RestClient restClient; public int insertData() { int status=500; try { String endPoint = "/" + indexName + "/" + indexType +"/"+ id; IndexRequest indexRequest = new IndexRequest(); XContentBuilder builder = XContentFactory.jsonBuilder() .startObject() .field("Id", "1") .field("name","小明") .field("age","18") .field("creatTime","2020/08/01 10:00:00") .endObject(); indexRequest.source(builder); String source = indexRequest.source().utf8ToString(); HttpEntity entity = new NStringEntity(source, ContentType.APPLICATION_JSON); Request request = new Request("PUT", endPoint); request.setEntity(entity); Response response = null; response = restClient.performRequest(request); status=response.getStatusLine().getStatusCode(); } catch (IOException e) { System.out.println(e.getMessage()); } return status; }
注: 我们使用的低版本中非常依赖于索引中的type,如果在插入数据的中遗漏的话,代码会报错
(4) 从索引中获取数据
//引入第2步中创建的实例 @Autowired private RestClient restClient; public String getData( String startTime, String endTime, Pageable pageable) { int pageSize=pageable.getPageSize(); int page = pageable.getPageNumber(); //开始的行数,用于elasticsearch中的 from&size分页查询 int startLine= page == 1 ? 0 : (page-1)*pageSize; //索引名称+想要查询的type+查询关键字 String endPoint = "/" + indexName + "/" + indexType +"/"+"_search"; XContentBuilder builder; try { builder = JsonXContent.contentBuilder() .startObject() .field("from",startLine) .field("size", pageSize) .startObject("sort") .startObject("creatTime") .field("order", "desc") .endObject() .endObject() .startObject("query") .startObject("bool") .startObject("must") .startObject("range") .startObject("callTime") .field("from", startTime) .field("to", endTime) .field("include_lower", "true") .field("include_upper", "true") .endObject() .endObject() .endObject() .startObject("must") .startObject("match") .field("name", "小明") .endObject() .endObject() .startObject("must") .startObject("match") .field("age", "18") .endObject() .endObject() .endObject() .endObject() .endObject(); IndexRequest indexRequest = new IndexRequest(); indexRequest.source(builder); String source = indexRequest.source().utf8ToString(); HttpEntity entity = new NStringEntity(source, ContentType.APPLICATION_JSON); Request request = new Request("POST",endPoint); request.setEntity(entity); Response response = restClient.performRequest(request); //以字符串的形式得到返回的数据,此时可以将拿到的数据根据自己加工 String responeString = EntityUtils.toString(response.getEntity()); return responeString; } catch (IOException e) { System.out.println(e.getMessage()); return null; } }
注:
(1) startObject和endObject 需要成对使用;
(2) 在from&size分页查询中, from代表为开始的行数,默认为0; size 代表的是需要的总条数
(3) 在添加条件时 query 后面必须带上 bool,否则会有语法报错,抽取部分写法如下:
.startObject("query")
.startObject("bool")
/*
*添加需要的条件, 如: 需要添加名字叫小明的查询条件
.startObject("must")
.startObject("match")
.field("name", "小明")
.endObject()
.endObject()
*/
.endObject()
.endObject();
参考了官方文档Java REST Client 5.4地址为: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.4/index.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。