0.注意事項
SpringDataElasticSearch可能和遠程的ElasticSearch版本不匹配,會寶座
版本適配說明:https://github.com/spring-projects/spring-data-elasticsearch
如果版本不適配:2.4.6
1)、升級SpringBoot版本(不推薦)
2)、安裝對應版本的ES(推薦)
我這兒是又下了一個ES,docker pull 很快的
1.配置pom.xml文件
<!--SpringBoot默認使用SpringData ElasticSearch模塊進行操作--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
2.配置application.properties
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=tanghu.tk:9301
3.通過實現ElasticSearchRepository接口操作ES
1)、編寫一個ElasticSearchRepository
package com.fdzang.mblog.repository; import com.fdzang.mblog.pojo.es.EsBlog; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface EsBlogRepository extends ElasticsearchRepository<EsBlog,String> { }
2)、給實體類加上@Document注解,指定index跟type
package com.fdzang.mblog.pojo.es; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "thblog",type = "blog") public class EsBlog { @Id // 主鍵 private String id; private Long blogId; // Blog 的 id private String title; private String summary; private String content; public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getBlogId() { return blogId; } public void setBlogId(Long blogId) { this.blogId = blogId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
3)、測試類
@Autowired EsBlogRepository esBlogRepository; @Test public void test02(){ EsBlog esBlog=new EsBlog(); esBlog.setBlogId(10001l); esBlog.setId("10001"); esBlog.setContent("content"); esBlog.setSummary("summary"); esBlog.setTitle("title"); esBlogRepository.index(esBlog); }
注:ElasticSearchRepository也支持自定義方法(遵循Repository的方法命名規則)
同時也支持@Query注解
文檔地址:https://docs.spring.io/spring-data/elasticsearch/docs/3.0.10.RELEASE/reference/html/