springboot与elasticsearch整合

2020-05-16 16:04:58来源:博客园 阅读 ()

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

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 !!!


原文链接:https://www.cnblogs.com/aigezi/p/12900835.html
如有疑问请与原作者联系

标签:HTMLAVIEHTTPSPOSTHTTP

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Java面试常被问到这道题:如何保证缓存与数据库的双写一致性?

下一篇:工作五年程序员,没扛过阿里的三面,究竟输在了哪?