当前位置:   article > 正文

Springboot 使用 RestClient 集成低版本 elasticsearch_springboot elasticsearch降低版本

springboot elasticsearch降低版本

Springboot 使用 RestClient 集成低版本 elasticsearch (es版本为5.4.2)

1.引入依赖

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.8.0</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2. 创建 RestClient 实例

 @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();
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

(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;
         }
     }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

(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;

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

注: 我们使用的低版本中非常依赖于索引中的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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

注:
(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();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

参考了官方文档Java REST Client 5.4地址为: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.4/index.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/80972
推荐阅读
相关标签
  

闽ICP备14008679号