SpringBoot整合ElasticSearch:基于SpringDataElasticSearch

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/

 

posted @ 2018-09-14 13:32  市井俗人  阅读(2941)  评论(0编辑  收藏