1. 引言
代码已提交至Github,有兴趣的同学可以下载来看看:https://github.com/ylw-github/SpringBoot-ElasticSearch-Demo
2. SpringBoot整合ElasticSearch
1.新建Maven项目Spring-ElasticSearch-Demo
2.添加maven依赖:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <dependencies> <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> </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,查询成功。
3. 9300与9200的区别
- 「9300端口」: ES节点之间通讯使用。
- 「9200端口」: ES节点 和 外部 通讯使用。
- 「9300端口」:是TCP协议端口号,ES集群之间通讯端口号。
- 「9200端口」:暴露ES RESTful接口端口号。
举个例子:调用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