springboot与elasticsearch整合
Posted 艾格兹
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot与elasticsearch整合相关的知识,希望对你有一定的参考价值。
资源下载:
ElasticSearch官方下载地址:https://www.elastic.co/downloads/elasticsearch
curl下载地址:http://curl.haxx.se/download.html
Kibana下载地址:https://www.elastic.co/guide/en/kibana/4.6/index.html
sense下载地址:https://download.elastic.co/elastic/sense/sense-latest.tar.gz
ik分词器下载地址:https://github.com/medcl/elasticsearch-analysis-ik
logstash下载地址:https://www.elastic.co/cn/downloads/logstash
elasticsearch官网地址:https://www.elastic.co
注意:ElasticSearch和Kibana版本必须一致
我用到的elasticsearch版本和Kibana是 6.4.3
1,查看本地项目spring和springboot版本号
public static void main(String[] args) { System.out.println(SpringVersion.getVersion()); System.out.println(SpringBootVersion.getVersion()); }
2,导入相关依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
3,application.yml配置文件
#es配置 spring: data: elasticsearch: cluster-name: elasticsearch //默认集群名称 cluster-nodes: 127.0.0.1:9300 //默认启动集群节点
4,启动类配置@EnableElasticsearchRepositories(basePackages = “com.aigezi.cdd.entity.dao.es”), basePackages是es资源库所在包
@SpringBootApplication @EnableElasticsearchRepositories(basePackages = "com.aigezi.cdd.entity.dao.es") public class SpringbootElasticsearchApplication { public static void main(String[] args) { SpringApplication.run(SpringbootElasticsearchApplication.class, args); } }
5,索引文档实体 注意此时@Id注解的导入包来自import org.springframework.data.annotation.Id,索引名称必须为小写
@Document(indexName = "product", type = "book") @Data public class Book { @Id String id; String name; String message; String type; public Book(){} public Book(String id,String name,String message,String type){ this.id = id; this.name = name; this.message = message; this.type = type; } }
6,elasticsearch资源库 继承了ElasticsearchRepository,封装了很多API
@Component public interface BookRepository extends ElasticsearchRepository<Book,String> { // Book是索引文档实体,String是文档id类型 }
7,Controller 层 增删改查操作
@Resource BookRepository bookRepository; @ApiOperation("创建索引") @PostMapping("/auth/add") public String add(){ Book book = new Book(); book.setId("1"); book.setMessage("TTTTGGGGDDD"); book.setType("es"); book.setName("spring"); bookRepository.save(book); return "success"; }
8,在Kibana访问新建索引
GET /product/book/_search 查询结果: { "_index": "product", "_type": "book", "_id": "1", "_score": 1, "_source": { "id": "1", "name": "spring", "message": "TTTTGGGGDDD", "type": "es" } }
END !!!
以上是关于springboot与elasticsearch整合的主要内容,如果未能解决你的问题,请参考以下文章
Springboot2.1.1使用rest-high-level-client整合Elasticsearch6.4.3