欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring boot2集成ES详解

程序员文章站 2023-01-29 15:26:54
一:运行环境 JDK:1.8 ES:5.6.4 二:学习内容 如何构建spring-data-elasticsearch环境? 如何实现常用的增删改查? 如何实现对象嵌套也就是1对多这种关系? 三:JAVA依赖环境 根据spring-data-elasticsearch官网说明,我这采用的是3.0. ......

一:运行环境

    jdk:1.8

    es:5.6.4

二:学习内容

    如何构建spring-data-elasticsearch环境?

    如何实现常用的增删改查?

    如何实现对象嵌套也就是1对多这种关系?

三:java依赖环境

    根据spring-data-elasticsearch官网说明,我这采用的是3.0.6.release版本,spring boot采用的是2.0.1.release;

<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.0.1.release</version>
		<relativepath />
	</parent>


	<groupid>com.huize.pluto.els</groupid>
	<artifactid>demo</artifactid>
	<version>1.0.0-snapshot</version>
	<packaging>jar</packaging>

	<name>demo</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceencoding>utf-8</project.build.sourceencoding>
		<elasticsearch.version>5.6.4</elasticsearch.version>
		<java.version>1.8</java.version>
	</properties>

	<repositories>
		<repository>
			<id>spring-libs-milestone</id>
			<url>https://repo.spring.io/libs-milestone</url>
		</repository>
	</repositories>

	<pluginrepositories>
		<pluginrepository>
			<id>spring-plugins-release</id>
			<url>https://repo.spring.io/plugins-release</url>
		</pluginrepository>
	</pluginrepositories>

	<dependencies>
		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-web</artifactid>
		</dependency>
		
		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-test</artifactid>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupid>org.springframework.data</groupid>
			<artifactid>spring-data-elasticsearch</artifactid>
			<version>3.0.6.release</version>
		</dependency>
        
        <!-- 强制声明es版本 -->
		<dependency>
			<groupid>org.elasticsearch</groupid>
			<artifactid>elasticsearch</artifactid>
			<version>${elasticsearch.version}</version>
		</dependency>
		
        <!-- 因为要采用java编码直接操作es所以需要引入 -->
		<dependency>
			<groupid>org.elasticsearch.client</groupid>
			<artifactid>transport</artifactid>
			<version>${elasticsearch.version}</version>
			<exclusions>
				<exclusion>
					<groupid>commons-logging</groupid>
					<artifactid>commons-logging</artifactid>
				</exclusion>
			</exclusions>
		</dependency>
		
	</dependencies>


	<build>
		<plugins>
			<plugin>
				<groupid>org.apache.maven.plugins</groupid>
				<artifactid>maven-compiler-plugin</artifactid>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<compilerversion>1.8</compilerversion>
					<encoding>utf-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

 

四、spring-data-elasticsearch详解

4.1:配置es

声明 elasticsearchtemplate  bean ;(当然也可以采用spring boot自动配置方法来实现,因为后面还得直接用java api操作es,所以这用代码配置了)

/***
 ** 配置es,支持集群
 */
@configuration
public class elasticconfigration {

    @value("${elasticsearch.host}")
    private string eshost;

    @value("${elasticsearch.port}")
    private int esport;

    @value("${elasticsearch.clustername}")
    private string esclustername;
    
    private transportclient client;
    
    @postconstruct
    public void initialize() throws exception {
	   settings essettings = settings.builder()
                  .put("cluster.name", esclustername)
                  .put("client.transport.sniff", true).build();
	   client = new prebuilttransportclient(essettings);

	   string[] eshosts = eshost.trim().split(",");
	   for (string host : eshosts) {
	       client.addtransportaddress(new inetsockettransportaddress(inetaddress.getbyname(host), 
           esport));
	   }
    }
    
    @bean
    public client client() {
	   return client;
    }
    
    
    @bean
    public elasticsearchtemplate elasticsearchtemplate() throws exception {
	   return new elasticsearchtemplate(client);
    }
    
    
    @predestroy
    public void destroy() {
	  if (client != null) {
	       client.close();
	   }
    }

}

4.2:编写实体类

声明各个字段类型及相应属性:

/**
 * 声明 user实体,注意有一个1对多关系的roles
 **/
@document(indexname = "test-user", type = "user",replicas=0,shards=3)
public class user {
    
    @id
    private string id;
    
    @field(type=fieldtype.keyword)
    private string username;
    
    @field(type=fieldtype.integer)
    private integer age;
    
    @field(type=fieldtype.date)
    private date birthday;
    
    /**
     * 声明分词器为ik_smart (注意 es要安装ik分词器插件)
     */
    @field(searchanalyzer="ik_smart",analyzer="ik_smart",type=fieldtype.text)
    private string description;
    
    /**
     * 1对多在spring-data-elasticsearch 统一为nested类型
     **/
    @field(type=fieldtype.nested,includeinparent=true)
    private list<role> roles;
    
    
    public user() {}
    
    public user(string username,integer age,date birthday,string description) {
	   this.username = username;
	   this.age = age;
	   this.birthday = birthday;
	   this.description = description;
    }
    
    public string getid() {
        return id;
    }

    
    public void setid(string id) {
        this.id = id;
    }

    
    public string getusername() {
        return username;
    }

    
    public void setusername(string username) {
        this.username = username;
    }

    
    
    public date getbirthday() {
        return birthday;
    }


    
    public void setbirthday(date birthday) {
        this.birthday = birthday;
    }


    public integer getage() {
        return age;
    }

    
    public void setage(integer age) {
        this.age = age;
    }

    
    public string getdescription() {
        return description;
    }

    
    public void setdescription(string description) {
        this.description = description;
    }

    
    public list<role> getroles() {
        return roles;
    }

    
    public void setroles(list<role> roles) {
        this.roles = roles;
    }
    
    
}


@document(indexname = "test-role", type = "role",replicas=0,shards=3)
public class role {
    
    @id
    private string id;
    
    @field(type=fieldtype.keyword)
    private string name;
    
    @field(type=fieldtype.date)
    private date createtime;
    
    @field(searchanalyzer="ik_smart",analyzer="ik_smart",type=fieldtype.text)
    private string description;
    
    public role() {}
    
    public role(string name,string description,date createtime) {
	this.name = name;
	this.description = description;
	this.createtime = createtime;
    }
    
    public string getid() {
        return id;
    }

    
    public void setid(string id) {
        this.id = id;
    }

    
    public string getname() {
        return name;
    }

    
    public void setname(string name) {
        this.name = name;
    }

    
    public date getcreatetime() {
        return createtime;
    }

    
    public void setcreatetime(date createtime) {
        this.createtime = createtime;
    }

    
    public string getdescription() {
        return description;
    }

    
    public void setdescription(string description) {
        this.description = description;
    }
    
}

4.3:编写dao

只要继承elasticsearchrepository就具有常用的增删减查功能了,可以新增一些其他需要用到的查询

public interface userrepository extends elasticsearchrepository<user,string>{
    
    //按username like查询
    list<user> findbyusernamelike(string username);
    
    //按role的name属性查询
    list<user> findbyrolesname(string name);
    
    //按role的name属性查询 两种方式都可以
    list<user> findbyroles_name(string name);
    
}

4.4:编写service

@service
public class userstandardservice implements standardservice{
    
    @autowired
    private userrepository userrepository;
    
    @autowired
    private elasticsearchtemplate elasticsearchtemplate;
    
    /**
     * 批量新增
     **/
    @override
    public void batchadduser(list<user> users) {
	   if(collectionutils.isempty(users)) {
	      return ;
	   }
	   list<indexquery> queries = lists.newarraylistwithexpectedsize(users.size());
	   indexquery indexitem  = null;
	   for(user user :users) {
	       indexitem = new indexquery();
	       indexitem.setobject(user);
	       queries.add(indexitem);
	   }
	   elasticsearchtemplate.bulkindex(queries);
    }
    
    @override
    public void adduser(user user) {
	   userrepository.save(user);
    }

    @override
    public void deleteduserbyid(string id) {
	   userrepository.deletebyid(id);
    }

    /**
     * 根据userid更新信息
     */
    @override
    public void updateuser(user user) {
	   updatequery updatequery = new updatequery();
	   updatequery.setid(user.getid());
	   updatequery.setclazz(user.class);
	   user.setid(null);
	   updaterequest request = new updaterequest();
	   request.doc(jsonutils.beantojson(user));
	   updatequery.setupdaterequest(request);
	   elasticsearchtemplate.update(updatequery);
    }

    @override
    public list<user> querybyusername(string username) {
	   return userrepository.findbyusernamelike(username);
    }

    @override
    public list<user> querybyrolename(role role) {
	   return userrepository.findbyroles_name(role.getname());
    }

}

 

4.5:启动

主要要加上 @enableelasticsearchrepositories 注解;

@enableelasticsearchrepositories(basepackages = "com.test.els.demo.core.user.repository")
@springbootapplication
public class demoapplication {
    
    private static final logger logger = loggerfactory.getlogger(demoapplication.class);
    
    public static void main(string[] args) {
	
	   springapplication.run(demoapplication.class, args);
	   logger.info("start completed !");
    }
    
    
}

ok,到这spring-data-elasticsearch 实践完了。