SpringBoot2>07 - 集成spring data elasticsearch

扯淡:

Spring Data Elasticsearch 是spring data对elasticsearch进行的封装。所以在springboot项目中使用es非常方便,直接在 dao 接口继承 ElasticsearchRepository,即可使用内部封装好的API,这种方式类似spring data jpa、以及前面涉及到的MongoDB。另外一种方式,在项目中使用@Autowired注入ElasticsearchTemplate,然后完成相应操作。本文采用spring data 项目。

 springboot、springcloud、docker学习目录:【传送门

使用:

依赖、配置:

1、pom:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

2、application.yml

server:
  port: 8090

spring:
  application:
    name: es

  data:
    elasticsearch:
      cluster-nodes: 127.0.0.1:9300
      repositories:
        enabled: true

实体类:

1、新建Article文章实体类:

/**
 * @Auther: xf
 * @Date: 2019/1/13 18:38
 * @Description:
 *
 * indexName: 索引(数据库)
 * type:类型(表)
 */
@Document(indexName = "article", type = "articles")
public class Article {

    private Long id;

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String name;

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String content;

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String writer;

    getter/setter...
}

关键:@Document、@Feign。

2、@Document注解:

一条记录。

public @interface Document {

    // 索引库的名称,无默认值
    String indexName();

    // 类型(表),建议以实体的名称命名
    String type() default "";

    boolean useServerConfiguration() default false;

    short shards() default 5;

    short replicas() default 1;

    // 刷新间隔
    String refreshInterval() default "1s";

    // 索引文件存储类型
    String indexStoreType() default "fs";

    // 没有索引,是否创建索引
    boolean createIndex() default true;
}

3、@Feign注解:

索引中的域。

public @interface Field {

    // 字段的类型 自动检测 也可指定具体值
    FieldType type() default FieldType.Auto;

    // 该字段是否可以被索引 默认 true
    boolean index() default true;

    DateFormat format() default DateFormat.none;
    String pattern() default "";

    // 默认不存储原文
    boolean store() default false;

    boolean fielddata() default false;

    // 搜索时指定的分词器
    String searchAnalyzer() default "";

    // 建立索引时指定的分词器
    String analyzer() default "";

    String normalizer() default "";
    String[] ignoreFields() default {};
    boolean includeInParent() default false;
    String[] copyTo() default {};
}

Repository:

类似data jpa、MongoDB 中的操作,继承相关的Repository即可具备基本的CRUD操作,复杂的可在接口中按照规则增加方法。

1、dao

/**
 * 继承 ElasticsearchRepository<实体类, 实体类主键类型>
 */
public interface ArticleRepository extends ElasticsearchRepository<Article,Long> {

   // Pageable为分页使用,不需要分页是去除。    
   Page<Article> findByName(String name, Pageable pageable);
    Page<Article> findByNameLike(String name, Pageable pageable);

}

2、自定义查询方法:

使用find、By、And、Not等等。参看官网:https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/

public interface ArticleRepository extends ElasticsearchRepository<Article,Long> {

    // Pageable为分页使用,不需要分页是去除。
    Page<Article> findByName(String name, Pageable pageable);
    Page<Article> findByNameLike(String name, Pageable pageable);

    /**
     * 参考 官网 https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/
     * 仅仅作为理解,与本项目无关
     */
    /* 以Name 开头 */
    List<Book> findByNameStartingWith(String name);
    /* 以Name 结尾 */
    List<Book> findByNameEndingWith(String name);
    /* 包含 Name */
    List<Book> findByNameContaining(String name);
    /* 年龄在 ageFrom 到 ageTo 之间 */
    List<Book> findByAmountBetween(Integer amountFrom, Integer amountTo);
    /* 名称为name 和 价格为 price 的 */
    List<Book> findByNameAndPrice(String name, Integer price);
    /* 名称为name 和 价格为 price 的 按照价格排序 */
    List<Book> findByNameAndPriceOrderByPriceDesc(String name, Integer price);

}

Controller、Service:

较简单,下面为搜索结果分页,完整代码下载源码。

// controller
@RestController
public class ArticleController {

    @Autowired
    ArticleService articleService;

    @GetMapping(value = "article/query")
    public ApiResult query(@RequestParam(value = "pageNumber",required = false, defaultValue = "1") int pageNumber,
                           @RequestParam(value = "pageSize",required = false, defaultValue = "10") int pageSize,
                           @RequestParam(value = "searchContent") String searchContent){

        Page<Article> query = articleService.query(pageNumber, pageSize, searchContent);
        return ApiResult.ok(query.getContent());
    }

}

// service
@Service
public class ArticleService {

    @Autowired
    ArticleRepository articleRepository;

    public Page<Article> query(int pageNumber, int pageSize, String searchContent) {
        // 分页
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);
        Page<Article> articles = articleRepository.findByNameLike(searchContent, pageRequest);
        return articles;
    }

}

测试:

1、ES中已添加数据

2、查询:http://127.0.0.1:8090/article/query?searchContent=电视剧我的团长&pageSize=10

至此,springboot 项目使用spring data elasticsearch实现es 的操作完成。

总结:

1、@Document、@Feign的使用
2、使用spring data elasticsearch,dao接口继承ElasticsearchRepository即可使用CRUD操作的API,复杂操作可按照规则定义方法。
3、ES的实际使用中增删改操作较少,重点是查询。ES的索引和数据库的同步一般不会使用API操作。下章将将诶是

TIP:

ES的实际使用中增删改操作较少,重点是查询,ES的索引和数据库的同步一般不会使用API操作,而是使用工具操作。

代码地址:

https://gitee.com/cpla026/springboot-account2/tree/master/springboot2_parent/springboot2_article_elasticsearch


个人学习分享
更多 springboot、springcloud、docker 文章,关注微信公众号吧:

猜你喜欢

转载自blog.csdn.net/cp026la/article/details/86551135
今日推荐