spring boot2整合ES詳解

Tybyq發表於2018-11-28

一:執行環境

    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="	xsi:schemaLocation="	<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>	<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>		</repository>	</repositories>	<pluginRepositories>		<pluginRepository>			<id>spring-plugins-release</id>			<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,支援叢集
 */@Configurationpublic 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

@Servicepublic 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")@SpringBootApplicationpublic 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 實踐完了。


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31557424/viewspace-2222027/,如需轉載,請註明出處,否則將追究法律責任。

相關文章