Springboot 整合elasticsearch 7.x

注意:
简单测试了一下,SpringBoot版本是2.3.0.RELEASE才兼容elasticsearch 7.x,可以使用ES的高级客户端。有误请指正,万分感谢。

1、依赖导入pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <groupId>com.dws.elasticsearch</groupId>
    <artifactId>elasticsearch-master</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
    </parent>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

2、编写application.yml配置文件

server:
  port: 8090
  servlet:
    context-path: /elasticsearch

# elasticsearch
spring:
  elasticsearch:
    rest:
      uris: http://localhost:9200
      

3、创建ES对应的实体对象

package com.dws.elasticsearch.entity;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

/**
 * @author: 
 * @date: 2021/9/27 16:12
 * @description:
 */
@Data
@NoArgsConstructor
@Accessors(chain = true)
@Document(indexName = "ems",type= "_doc",shards = 1,replicas = 0)
public class DocBean {
	@Id
	private Long id;

	@Field(type = FieldType.Keyword)
	private String firstCode;

	@Field(type = FieldType.Keyword)
	private String secordCode;

	@Field(type = FieldType.Text, analyzer = "ik_max_word")
	private String content;

	@Field(type = FieldType.Integer)
	private Integer type;

	public DocBean(Long id, String firstCode, String secordCode, String content, Integer type) {
		this.id = id;
		this.firstCode = firstCode;
		this.secordCode = secordCode;
		this.content = content;
		this.type = type;
	}
}

4、编写ElasticRepository接口

package com.dws.elasticsearch.mapper;

import com.dws.elasticsearch.entity.DocBean;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
 * @author: 
 * @date: 2021/9/27 16:16
 * @description:
 */
public interface ElasticRepository extends ElasticsearchRepository<DocBean,Long> {
}

想了解ElasticsearchRepository提供了哪些基础的CRUD操作,有兴趣的可以进入ElasticsearchRepository类中查看,通过自定义方法命名约定,提供了强大的自定义操作,在我的下一篇文章中有讲解,有兴趣可以去看看。

5、编写Service层

package com.dws.elasticsearch.service;

import com.dws.elasticsearch.entity.DocBean;
import org.springframework.data.domain.Page;

import java.util.Iterator;
import java.util.List;

/**
 * @author: 
 * @date: 2021/9/27 16:18
 * @description:
 */
public interface IElasticService {
	void createIndex();

	void deleteIndex(String index);

	void save(DocBean docBean);

	void isExist();

	void saveAll(List<DocBean> list);

	Iterator<DocBean> findAll();

	DocBean findById(Long id);

	Page<DocBean> findByContent(String content);

	Page<DocBean> findByFirstCode(String firstCode);

	Page<DocBean> findBySecordCode(String secordCode);

	Page<DocBean> query(String key);
}

实现逻辑:

package com.dws.elasticsearch.service.impl;

import com.dws.elasticsearch.entity.DocBean;
import com.dws.elasticsearch.mapper.ElasticRepository;
import com.dws.elasticsearch.service.IElasticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * @author: 
 * @date: 2021/9/27 16:19
 * @description:
 */
@Service
public class ElasticServiceImpl implements IElasticService {

	@Autowired
	private ElasticsearchRestTemplate elasticsearchRestTemplate;

	@Autowired
	private ElasticRepository elasticRepository;

	@Override
	public void createIndex() {
		elasticsearchRestTemplate.indexOps(IndexCoordinates.of("ems")).create();
	}

	@Override
	public void deleteIndex(String index) {

		elasticsearchRestTemplate.indexOps(IndexCoordinates.of("ems")).delete();

	}

	@Override
	public void save(DocBean docBean) {
		elasticRepository.save(docBean);
	}

	@Override
	public void isExist() {
		elasticsearchRestTemplate.indexOps(IndexCoordinates.of("ems")).exists();
	}

	@Override
	public void saveAll(List<DocBean> list) {
		elasticRepository.saveAll(list);
	}

	@Override
	public Iterator<DocBean> findAll() {
		Iterable<DocBean> repositoryAll = elasticRepository.findAll();
		return repositoryAll.iterator();
	}

	/**
	 * @param id:
	 * @return: com.dws.elasticsearch.entity.DocBean
	 * @author: 
	 * @date: 2021/9/28 10:28
	 * @description: 根据id查询数据
	 */
	@Override
	public DocBean findById(Long id) {
		Optional<DocBean> optional = elasticRepository.findById(id);
		DocBean docBean = null;
		if (optional.isPresent()){
			docBean = optional.get();
		}
		return docBean;
	}

	@Override
	public Page<DocBean> findByContent(String content) {

		return null;
	}

	@Override
	public Page<DocBean> findByFirstCode(String firstCode) {
		return null;
	}

	@Override
	public Page<DocBean> findBySecordCode(String secordCode) {
		return null;
	}

	@Override
	public Page<DocBean> query(String key) {
		return null;
	}
}

6、编写ElasticsearchController

package com.dws.elasticsearch.controller;

import com.dws.elasticsearch.entity.DocBean;
import com.dws.elasticsearch.service.IElasticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author: 
 * @date: 2021/9/27 17:11
 * @description:
 */
@RestController
@RequestMapping("/es")
public class ElasticsearchController {
	@Autowired
	private IElasticService elasticService;

	@GetMapping(value = "/add",name = "初始化索引,并添加数据")
	public void add(){
		elasticService.createIndex();
		List<DocBean> list =new ArrayList<>();
		list.add(new DocBean(1L,"1870975","dbywuhe","2ajsjhh",1));
		list.add(new DocBean(2L,"sajhjj","ajsbjah","jbasbakbjs",1));
		list.add(new DocBean(3L,"akbsabjb","ajsjnkaj","jhahsajh",1));
		elasticService.saveAll(list);

	}

	@GetMapping(value = "/all",name = "查询所有数据")
	public Iterator<DocBean> all(){
		return elasticService.findAll();
	}

	@GetMapping(value = "/delete",name = "删除索引")
	public String delete(){
		elasticService.deleteIndex("ems");
		return "delete index success!!!!";
	}

	@GetMapping(value = "/create",name = "创建索引")
	public String create(){
		elasticService.createIndex();
		return "create index success!!!!";
	}

}

7、编写SpringBoot启动类

package com.dws.elasticsearch;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author: 
 * @date: 2021/9/27 17:12
 * @description:
 */
@SpringBootApplication
public class ElasticsearchApplication {
	public static void main(String[] args) {
		SpringApplication.run(ElasticsearchApplication.class,args);
	}
}

8、测试

浏览器分别请求:
http://localhost:8090/elasticsearch/es/add
http://localhost:8090/elasticsearch/es/all
在这里插入图片描述


版权声明:本文为dws789456123原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。