spring boot2集成ES详解

为什么80%的码农都做不了架构师?>>>   hot3.png

一:运行环境

    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;


	4.0.0

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.1.RELEASE
		
	


	com.huize.pluto.els
	demo
	1.0.0-SNAPSHOT
	jar

	demo
	http://maven.apache.org

	
		UTF-8
		5.6.4
		1.8
	

	
		
			spring-libs-milestone
			https://repo.spring.io/libs-milestone
		
	

	
		
			spring-plugins-release
			https://repo.spring.io/plugins-release
		
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
		
			org.springframework.data
			spring-data-elasticsearch
			3.0.6.RELEASE
		
        
        
		
			org.elasticsearch
			elasticsearch
			${elasticsearch.version}
		
		
        
		
			org.elasticsearch.client
			transport
			${elasticsearch.version}
			
				
					commons-logging
					commons-logging
				
			
		
		
	


	
		
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.5.1
				
					1.8
					1.8
					1.8
					UTF-8
				
			
		
	


 

四、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 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 getRoles() {
        return roles;
    }

    
    public void setRoles(List 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{
    
    //按userName like查询
    List findByUserNameLike(String userName);
    
    //按role的name属性查询
    List findByRolesName(String name);
    
    //按role的name属性查询 两种方式都可以
    List 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 users) {
	   if(CollectionUtils.isEmpty(users)) {
	      return ;
	   }
	   List 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 queryByUserName(String userName) {
	   return userRepository.findByUserNameLike(userName);
    }

    @Override
    public List 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 实践完了。

 

转载于:https://my.oschina.net/woter/blog/1842779

你可能感兴趣的:(java,大数据)