当前位置:   article > 正文

SpringBoot整合ElasticSearch(RestHighLevelClient 方式增删改查)_springboot集成resthighlevelclient实现增删改查

springboot集成resthighlevelclient实现增删改查

项目用到了ES,不是很难,但是资料感觉比较少,而且方式还不少,但大多不适合自己,于是自己写个小demo测试了一下.
刚开始用的springdata,开发环境没问题,但是发到线上环境的时候有冲突,于是改成用RestHighLecelClient

依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
  <dependencies>
      <dependency>
          <groupId>org.elasticsearch.client</groupId>
          <artifactId>elasticsearch-rest-high-level-client</artifactId>
          <version>7.6.0</version>
          <exclusions>
              <exclusion>
                  <groupId>org.elasticsearch</groupId>
                  <artifactId>elasticsearch</artifactId>
              </exclusion>
              <exclusion>
                  <groupId>org.elasticsearch.client</groupId>
                  <artifactId>elasticsearch-rest-client</artifactId>
              </exclusion>
          </exclusions>
      </dependency>
      <dependency>
          <groupId>org.elasticsearch.client</groupId>
          <artifactId>elasticsearch-rest-client</artifactId>
          <version>7.6.0</version>
      </dependency>
      <dependency>
          <groupId>org.elasticsearch</groupId>
          <artifactId>elasticsearch</artifactId>
          <version>7.6.0</version>
      </dependency>
      <dependency>
          <groupId>org.springframework.data</groupId>
          <artifactId>spring-data-elasticsearch</artifactId>
          <version>3.0.10.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.6</version>
      </dependency>
  </dependencies>
</project>
  • 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

实体类

public class Users {
    private String name;
    private int age;
    public Users() {
    }

    public Users(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Users{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
  • 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

配置类

@Configuration
public class RestClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
        //如果是集群
//        RestHighLevelClient client = new RestHighLevelClient(
//                RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")
//                        , new HttpHost("127.0.0.1", 9201, "http")
//                        , new HttpHost("127.0.0.1", 9202, "http")));
        return client;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

实现增删改查

package com.jt.dubbo.controller;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
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.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 覃永福
 * @Date: 2020/06/27 0:33
 * @state:
 */
@org.springframework.web.bind.annotation.RestController
public class RestController {

    @Autowired(required = false)
    private RestHighLevelClient restHighLevelClient;

    @RequestMapping("hello")
    public String hello() {
        return "success";
    }

    /**
     * 添加索引
     *
     * @return
     */
    @RequestMapping("saveIndex")
    public String saveIndex() {
        try {
            CreateIndexRequest qyf = new CreateIndexRequest("qyf");
            restHighLevelClient.indices().create(qyf, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 查询索引是否存在
     *
     * @return
     */
    @RequestMapping("existIndex")
    public String existIndex() {
        try {
            GetIndexRequest qyf = new GetIndexRequest("qyf");
            boolean exists = restHighLevelClient.indices().exists(qyf, RequestOptions.DEFAULT);
            System.out.println(exists);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }


    /**
     * 添加文档
     *
     * @return
     */
    @RequestMapping("addDocument")
    public String addDocument() {
        try {
            Users user = new Users();
            user.setName("覃cc1");
            user.setAge(20);
            IndexRequest request = new IndexRequest("qyf");

            request.source(JSON.toJSONString(user), XContentType.JSON);
            request.id("1");
            IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            System.out.println(index.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    @RequestMapping("getDocument")
    public String getDocument() {
        GetResponse documentFields = null;
        try {
            GetRequest qyf = new GetRequest("qyf", "1");
            documentFields = restHighLevelClient.get(qyf, RequestOptions.DEFAULT);
            System.out.println(documentFields);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return documentFields.toString();
    }

    /**
     * 更新文档
     *
     * @return
     */
    @RequestMapping("updateDocument")
    public String updateDocument() {
        UpdateResponse update = null;
        try {
            UpdateRequest qyf = new UpdateRequest("qyf", "1");
            Users users = new Users();
            users.setName("覃帅帅");

            UpdateRequest doc = qyf.doc(JSON.toJSONString(users), XContentType.JSON);
            update = restHighLevelClient.update(qyf, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return update.toString();
    }

    /**
     * 删除文档
     * @return
     */
    @RequestMapping("deleteDocument")
    public String deleteDocument() {
        try {
            DeleteRequest qyf = new DeleteRequest("qyf", "1");
            DeleteResponse delete = restHighLevelClient.delete(qyf, RequestOptions.DEFAULT);
            System.out.println(delete.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 批量添加文档
     * 返回false表示没有失败
     *
     * @return
     */
    @RequestMapping("saveDocuments")
    public String saveDocuments() {
        try {
            BulkRequest bulkRequest = new BulkRequest();
            List<Users> list = new ArrayList<>();
            for (int i = 0; i < 100; i++) {
                list.add(new Users("覃帅帅" + i, 20 + 2 * i));
            }

            for (int i = 0; i < list.size(); i++) {
                bulkRequest.add(new IndexRequest("qyf").id("" + i + 10086).source(JSON.toJSONString(list.get(i)), XContentType.JSON));
            }

            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println(bulk.hasFailures());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 批量查询
     *
     * @return
     */
    @RequestMapping("findList")
    public List<Users> findList() {
        List<Users> list = null;
        try {
            //构建查询器
            SearchRequest request = new SearchRequest("qyf");
            //设置查询条件
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            //多条件查询
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //范围查询
            boolQueryBuilder.must(QueryBuilders.rangeQuery("age")
                    .gte(50).lte(90));
            //模糊匹配
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("name","*1*"));
            //多条件查询放入条件中
            sourceBuilder.query(boolQueryBuilder);
            //分页, ES从第0页开始,不设置默认只会显示10条记录
            sourceBuilder.from(0);
            sourceBuilder.size(500);
            //排序
            sourceBuilder.sort("age",SortOrder.ASC);
            //将条件放入查询器
            request.source(sourceBuilder);

            //请求
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = search.getHits().getHits();

            list = new ArrayList<>();
            for (SearchHit hit : hits) {
                Users users = new Users();
                users.setName(hit.getSourceAsMap().get("name").toString());
                users.setAge(Integer.parseInt(hit.getSourceAsMap().get("age").toString()));

                list.add(users);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("记录数:" + list.size());
        System.out.println(list);
        return list;
    }

	/**
	*查询全部
	*/
    @RequestMapping("findAll")
    public List<Users> findAll() {
        List<Users> list = null;
        try {
            //构建查询器
            SearchRequest rq = new SearchRequest("qyf");
            //设置查询条件
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            //ES从第0页开始,不设置默认只会显示10条记录
            sourceBuilder.from(0);
            sourceBuilder.size(500);
            //将条件放入查询器
            rq.source(sourceBuilder);
            SearchResponse search = restHighLevelClient.search(rq, RequestOptions.DEFAULT);
            SearchHit[] hits = search.getHits().getHits();

            list = new ArrayList<>();
            for (SearchHit hit : hits) {
                Users users = new Users();
                users.setName(hit.getSourceAsMap().get("name").toString());
                users.setAge(Integer.parseInt(hit.getSourceAsMap().get("age").toString()));

                list.add(users);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("记录数:" + list.size());
        System.out.println(list);
        return list;
    }
}
  • 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
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/68715
推荐阅读
相关标签
  

闽ICP备14008679号