代码已提交至Github,有兴趣的同学可以下载来看看:https://github.com/ylw-github/SpringBoot-ElasticSearch-Demo
1.新建Maven项目Spring-ElasticSearch-Demo
2.添加maven依赖:
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.0.0.RELEASEversion>
<relativePath />
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
dependencies>
3.application.yml
spring:
data:
elasticsearch:
####集群名称
cluster-name: myes
####地址
cluster-nodes: 192.168.162.131:9300
4.实体类层
@Document(indexName = "user_dao", type = "user")
public class UserEntity {
private String id;
private String name;
private int sex;
private int age;
//getter/setter......
}
5.Dao类层
public interface UserReposiory extends CrudRepository<UserEntity, String> {
}
6.控制器层:
@RestController
public class EsController {
@Autowired
private UserReposiory userReposiory;
@RequestMapping("/addUser")
public UserEntity addUser(@RequestBody UserEntity user) {
return userReposiory.save(user);
}
@RequestMapping("/findUser")
public Optional<UserEntity> findUser(String id) {
return userReposiory.findById(id);
}
}
7.启动项目:
@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.ylw.springboot.es.repository")
public class AppEs {
public static void main(String[] args) {
SpringApplication.run(AppEs.class, args);
}
}
如果报以下异常:
None of the configured nodes are available:
说明没有配置cluster节点名,那么进入ElasticSearch配置文件目录配置:
[ylw@localhost root]$ cd /usr/local/elasticsearch-6.4.3/config/
[ylw@localhost config]$ vi elasticsearch.yml
配置内容:
cluster.name: myes
8.PostMan请求添加索引:http://127.0.0.1:8080/addUser
9.PostMan请求查询:http://127.0.0.1:8080/findUser?id=1,查询成功。
举个例子:调用RESTful创建文档(/索引/类型/id
)
1.创建文档,发送请求POST请求:http://192.168.162.131:9200/user_dao1/user/1
{
"name":"ylw",
"age":18,
"sex":0
}
2.查询文档,发送请求GET请求:http://192.168.162.131:9200/user_dao1/user/1