0
点赞
收藏
分享

微信扫一扫

SpringBoot整合ElasticSearch

  • 本文讲述的是使用Springboot搭建的一个整合ElasticSearch的小demo,只做了一些简单的操作

1、pom.xml

  • 关键的依赖
   <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>
</dependency>

2、application.yml

  • 这里需要指定集群名称集群的地址,集群的名称我们可以这样获取得到。
    启动ElasticSearch.bat 等启动完毕后,我们在浏览器中输入127.0.0.1:9200

spring:
data:
elasticsearch:
####集群名称
cluster_name: elasticsearch
####地址
cluster-nodes: 127.0.0.1:9300

为什么是9300???
官方做出了如下的解释:

3、Entity

  • indexName 文档所在的索引名
  • type 文档所在的类型名
@Document(indexName = "myinfo", type = "user")
@Data
public class UserEntity {

@Id
private String id;
private String name;
private int sex;
private int age;
}

4、Dao

public interface UserReposiory extends CrudRepository<UserEntity, String> {
}

5、Controller

@RestController
public class UserController {

@Autowired
private UserReposiory userReposiory;

/***
* @Author wangxl
* @Description 添加一个用户信息
* @Date 11:46
* @Param [user]
* @return com.ustcinfo.es.entity.UserEntity
**/

@RequestMapping("/addUser")
public UserEntity addUser(@RequestBody UserEntity user) {
return userReposiory.save(user);
}

/***
* @Author wangxl
* @Description 根据id查询用户信息
* @Date 2019/11/13 11:46
* @Param [id]
* @return java.util.Optional<com.ustcinfo.es.entity.UserEntity>
**/

@RequestMapping("/findUser")
public Optional<UserEntity> findUser(String id) {
return userReposiory.findById(id);
}


/***
* @Author wangxl
* @Description findall方法返回的是一个迭代器,我们需要将它放进list中去,然后在返回
* @Date 2019/11/13 11:45
* @Param []
* @return java.util.List<com.ustcinfo.es.entity.UserEntity>
**/

@RequestMapping("/findAll")
public List<UserEntity> findAll() {
List<UserEntity> list = new ArrayList<>();
Iterable<UserEntity> iterable = userReposiory.findAll();
Iterator<UserEntity> it = iterable.iterator();
while (it.hasNext()){
list.add(it.next());
}
return list;
}

/***
* @Author wangxl
* @Description 先删除,然后在看看在数据库中是否还存在该id,存在则返回true,不存在则返回false。
* 在这里,删除成功-- false 删除失败 -- true .
* @Date 2019/11/13 11:43
* @Param [id]
* @return boolean
**/

@RequestMapping("/deleteUser")
public boolean deleteUser(String id) {
userReposiory.deleteById(id);
return userReposiory.existsById(id);
}
}

6、启动类

@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.ustcinfo.es.dao")
public class EsApplication {

public static void main(String[] args) {
SpringApplication.run(EsApplication.class, args);
}

}

6、测试

  • postman
  • 记得要先启动ElasticSearch,然后在启动本地项目

6.1 添加用户

6.2 获取所有用户

6.3 根据id查找

6.4 删除用户

这里为什么会返回一个false呢!
是因为,程序先执行userReposiory.deleteById(id);它是没有返回值,(不确定是否删除成功,所以我加上一个判断该ID是否存在的方法),然后在执行userReposiory.existsById(id),然后去查找,成功删除后,该ID不存在,所以返回的结果就是false。

举报

相关推荐

0 条评论