spring boot2集成ES详解

时间:2021-07-11 17:11:22

一:运行环境

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 实践完了。

spring boot2集成ES详解的更多相关文章

  1. Spring Boot 集成 FreeMarker 详解案例&lpar;十五&rpar;

    一.Springboot 那些事 SpringBoot 很方便的集成 FreeMarker ,DAO 数据库操作层依旧用的是 Mybatis,本文将会一步一步到来如何集成 FreeMarker 以及配 ...

  2. Spring各个jar包详解

    Spring各jar包详解 spring.jar 是包含有完整发布模块的单个jar 包.但是不包括mock.jar,aspects.jar, spring-portlet.jar, and sprin ...

  3. Spring Batch&lpar;4&rpar;&colon; Job详解

    Spring Batch(4): Job详解 2016-03-26 18:46 870人阅读 评论(1) 收藏 举报  分类: Spring(6)  版权声明:本文为博主原创文章,未经博主允许不得转载 ...

  4. SpringBoot系列(六)集成thymeleaf详解版

    SpringBoot系列(六)集成thymeleaf详解版 1. thymeleaf简介  1. Thymeleaf是适用于Web和独立环境的现代服务器端Java模板引擎.  2. Thymeleaf ...

  5. 安卓集成发布详解(二)gradle

    转自:http://frank-zhu.github.io/android/2015/06/15/android-release_app_build_gradle/ 安卓集成发布详解(二) 15 Ju ...

  6. Spring Data操作Redis详解

    Spring Data操作Redis详解 Redis是一种NOSQL数据库,Key-Value形式对数据进行存储,其中数据可以以内存形式存在,也可以持久化到文件系统.Spring data对Redis ...

  7. elasticSearch&plus;spring 整合 maven依赖详解

    摘自:http://www.mayou18.com/detail/nTxPQSyu.html [Elasticsearch基础]elasticSearch+spring 整合 maven依赖详解 Ma ...

  8. Spring Aop底层原理详解

    Spring Aop底层原理详解(来源于csdn:https://blog.csdn.net/baomw)

  9. Spring Boot 自定义日志详解

    本节内容基于 Spring Boot 2.0. 你所需具备的基础 什么是 Spring Boot? Spring Boot 核心配置文件详解 Spring Boot 开启的 2 种方式 Spring ...

随机推荐

  1. hadoop从非HA转到NAMENODE HA时需要注意的一个问题

    配置core-site.xml 配置hdfs-site.xml 配置mapred-site.xml 配置yarn-site.xml 纷发至其他节点 修改RM 2 ..N 上面的节点信息 格式化ZK h ...

  2. MIT 6&period;824 &colon; Spring 2015 lab3 训练笔记

    摘要: 源代码参见我的github:https://github.com/YaoZengzeng/MIT-6.824 Lab3: Paxos-based Key/Value Service Intro ...

  3. STM32之------独立看门狗(IWDG)和窗体看门狗(WWDG)

    一     前沿废语: 之前有很风靡的游戏,名字叫<看门狗>.该游戏用了很新的引擎技术,打造出了一个辽阔庞大的世界,内容是玩家Aiden·Pearce(主角)是一名精通黑客技术的高手,当时 ...

  4. UWP 共享文件——发送者

    这一节,顾名思义,即使你要共享数据给别人,你是数据的提供者.分两步即可1.直接复制代码 protected override void OnNavigatedTo(NavigationEventArg ...

  5. c&num;抽取pdf文档标题(2)

    public class IETitle { public static List<WordInfo> WordsInfo = new List<WordInfo>(); pr ...

  6. building &&num;39&semi;twisted&period;test&period;raiser&&num;39&semi; extension error&colon; Microsoft Visual C&plus;&plus; 14&period;0 is required&period; Get it with &quot&semi;Microsoft Visual C&plus;&plus; Build Tools&quot&semi;&colon; http&colon;&sol;&sol;landinghub&period;visualstudio&period;com&sol;visual-cpp-build-tools

    Error msg: building 'twisted.test.raiser' extension error: Microsoft Visual C++ 14.0 is required. Ge ...

  7. Go语言中的string知识点

    1.Go语言String的本质就是一个[]byte,所以他们之间可以互相转换,byte数组的长度就是字符串的长度. func StringTest1() { str := "Hello,Wo ...

  8. 直接执行sql字符串

    $sql_tmp= "UPDATE `eabc_order_detail` set send_number=num where order_sn='".$model_order-& ...

  9. 使用Git,如何忽略不需要上传的文件(配置文件)

    步骤1:在目录下,选择GIt Bash Here 2.输入命令 : git update-index --assume-unchanged 文件名 3.再输入指令 git  status 查看修改文件 ...

  10. [转]Google 的开源技术protobuf 简介与例子

    本文来自CSDN博客:http://blog.csdn.NET/program_think/archive/2009/05/31/4229773.aspx 今天来介绍一下“Protocol Buffe ...