ElasticSearch7.6.2--SpringBoot

SpringBoot整合ElasticSearch7.6.2

0、前置条件

之前使用SpringBoot整合过ES的低版本,ES各个大版本之间有较大的变化。

ES中值得注意的事项:

​ type逐渐移除,预计版本8中将消失

​ head插件在高等级的版本中,不支持直接安装,需要nodejs支持。

​ SpringBoot与Es的整合,需要注意版本支持,且在7.x的ES版本中客户端更新为 High Level REST Client,在 SpringBoot中的ElasticSearchTemplate过时,建议使用 High Level REST Client或者ElasticSearchRestTemplate。

版本如果不适配,也无法运行。

从Spring的官网可以看到版本的信息:

在这里插入图片描述

这次使用的版本是:

SpringBoot 2.3.0

ES7.6.2

这个SpringBoot版本中自带的是7.6.2版本的客户端,依赖如下:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

ES数据如下:

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "boot",
        "_type" : "user",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "name" : "Smish",
          "age" : 16,
          "gender" : "male",
          "desc" : [
            "产品经理",
            "艺术家"
          ]
        }
      },
      {
        "_index" : "boot",
        "_type" : "user",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "name" : "Jaskson",
          "age" : 18,
          "gender" : "male",
          "desc" : [
            "码农",
            "直男",
            "女装大佬"
          ]
        }
      }
    ]
  }
}

1、使用High Level REST Client

高级客户端是ES提供的客户端,支持多种语言。

在SpringBoot中使用只需要使用一个配置类设置好参数即可。

直接继承Springboot依赖中提供的配置类或者自建,保证有高级客户端对象即可。

@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {

    @Override
    public RestHighLevelClient elasticsearchClient() {

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();

        return RestClients.create(clientConfiguration).rest();
    }
}

这个客户端提供了非常多的api供使用,测试如下:

//判断索引是否存在:

@SpringBootTest
@RunWith(SpringRunner.class)
public class ElasticTest {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Test
    public void test() throws IOException {

        final GetIndexRequest indexRequest = new GetIndexRequest("boot");
        final boolean exists = restHighLevelClient.indices().exists(indexRequest,RequestOptions.DEFAULT)
        System.out.println(exists);
    }

 
}

//通过id或者索引查询数据:

@Test
public void test01() throws Exception {
        final GetRequest request = new GetRequest("boot", "1");
        final GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        final String string = response.toString();
        System.out.println(string);
        System.out.println("-------------------------");
	
       
    }

{"_index":"boot","_type":"_doc","_id":"1","_version":2,"_seq_no":4,"_primary_term":3,"found":true,"_source":{"name":"Jaskson","age":18,"gender":"male","desc":["码农","直男","女装大佬"]}}

   
@Test
public void test02() throws Exception {
        SearchResponse search = restHighLevelClient.search(new SearchRequest("boot"), RequestOptions.DEFAULT);
        System.out.println(search);
    }


高级客户端内置api较多,这些操作也可以使用ElasticsearchRestTemplate操作。

2、ElasticsearchRestTemplate操作

ElasticsearchRestTemplate是使用高级 REST 客户端实现的接口,ElasticsearchTemplate自版本 4.0 开始弃用,不过其实操作差别不大。

首先需要一个实体类,加入注解。

@Document(indexName = "boot")
public class User {

    @Id
    private int id;
    @Field
    private String  name;
    @Field
    private Integer age;
    @Field
    private String gender;
    @Field
    private String desc;


    public User(int id, String name, Integer age, String gender, String desc) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.desc = desc;
    }

    public User(){};

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

测试查询:

    @Autowired
    ElasticsearchRestTemplate template;


    @Test
    public void test(){

        IndexOperations ops = template.indexOps(User.class);
        boolean exists = ops.exists();
        System.out.println(exists);
		
        //通过id查询,已经废弃
       	User user = template.queryForObject(GetQuery.getById("1"), User.class);
        System.out.println(user);
        
        //和上一样
        User user1 = template.get("1", User.class);
        System.out.println(user1);


        //查询所有
        final SearchHits<User> search = template.search(Query.findAll(), User.class);
        final Iterator<SearchHit<User>> iterator = search.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }


    }
posted @ 2020-10-15 15:29  cgl_dong  阅读(1136)  评论(1编辑  收藏  举报