ElasticSearch7入门(六)SpringBoot2.3.0集成ElasticSearch7.5.2-SpringData

简介: ElasticSearch7入门(六)SpringBoot2.3.0集成ElasticSearch7.5.2-SpringData

背景


上一篇使用HighLevelClient的方式实现了SpringBoot集成ElasticSearch。今天换作SpringDataElasticsearch来完成SpringBoot与ElasticSearch的集成。SpringData系列借助自定义的命名规则,直接定义完接口,它可以帮助我们自动实现接口。


核心依赖


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


领域模型


package com.heartsuit.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.time.LocalDateTime;
/**
 * @Author Heartsuit
 * @Date 2020-06-12
 */
@Data
//@Document(indexName = "book", useServerConfiguration = true, createIndex = false)
@Document(indexName = "book")
public class Book {
    @Id
    private String id;
    @Field(type = FieldType.Text)
    private String title;
    @Field(type = FieldType.Keyword, analyzer = "ik_smart", searchAnalyzer = "ik_smart")
    private String author;
    @Field(name = "word_count", type = FieldType.Integer)
    private Integer wordCount;
    /**
     * 1. Jackson日期时间序列化问题:
     * Cannot deserialize value of type `java.time.LocalDateTime` from String "2020-06-04 15:07:54": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2020-06-04 15:07:54' could not be parsed at index 10
     * 解决:@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     * 2. 日期在ES存为long类型
     * 解决:需要加format = DateFormat.custom
     * 3. java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=5, YearOfEra=2020, MonthOfYear=6},ISO of type java.time.format.Parsed
     * 解决:pattern = "uuuu-MM-dd HH:mm:ss" 即将yyyy改为uuuu,或8uuuu: pattern = "8uuuu-MM-dd HH:mm:ss"
     * 参考:https://www.elastic.co/guide/en/elasticsearch/reference/current/migrate-to-java-time.html#java-time-migration-incompatible-date-formats
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Field(name = "publish_date", type = FieldType.Date, format = DateFormat.custom, pattern = "uuuu-MM-dd HH:mm:ss")
    private LocalDateTime publishDate;
}


核心方法


package com.heartsuit.repository;
import java.util.List;
import com.heartsuit.domain.Book;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
 * @Author Heartsuit
 * @Date 2020-06-12
 */
public interface BookRepository extends ElasticsearchRepository<Book, String> {
  List<Book> findByAuthor(String author);
  List<Book> findByAuthorLike(String author);
  List<Book> findByTitle(String author);
  List<Book> findByWordCount(Integer wordCount);
  List<Book> findByAuthorAndTitle(String author, String title);
  @Query("{\"bool\" : {\"must\" : {\"match\" : {\"title\" : \"?0\"}}}}")
  List<Book> queryByTitle(String keyword);
}


测试接口


package com.heartsuit.controller;
import com.heartsuit.domain.Book;
import com.heartsuit.repository.BookRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.*;
/**
 * @Author Heartsuit
 * @Date 2020-06-12
 */
@RestController
@RequestMapping("/books")
@Slf4j
public class BookController {
    private final BookRepository bookRepository;
    public BookController(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }
    @GetMapping("/all")
    public List<Book> findAll() {
        Iterable<Book> result = bookRepository.findAll();
        Iterator<Book> res = result.iterator();
        List<Book> books = new ArrayList<>();
        while (res.hasNext()) {
            books.add(res.next());
        }
        log.info("List All, Size: {}", books.size());
        return books;
    }
    /**
     * 新增
     *
     * @param book
     * @return
     */
    @PostMapping("/")
    public Book create(@RequestBody Book book) {
        log.info("Saved OK: {}", book.getTitle());
        return bookRepository.save(book);
    }
    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Book findById(@PathVariable("id") String id) {
        log.info("Query ID: {}", id);
        Book orElse = bookRepository.findById(id).orElse(null);
        return orElse;
    }
    /**
     * 根据ID修改
     *
     * @param id
     * @param title
     * @param author
     * @param wordCount
     * @param publishDate
     * @return
     * Note: 报错:Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime';
     * 解决:在参数前添加注解:@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     */
    @PutMapping("/{id}")
    public Book update(@PathVariable("id") String id,
                       @RequestParam(name = "title", required = false) String title,
                       @RequestParam(name = "author", required = false) String author,
                       @RequestParam(name = "wordCount", required = false) Integer wordCount,
                       @RequestParam(name = "publishDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime publishDate) {
        Optional<Book> optional = bookRepository.findById(id);
        if (optional.isPresent()) {
            Book book = optional.get();
            if (title != null) {
                book.setTitle(title);
            }
            if (author != null) {
                book.setAuthor(author);
            }
            if (wordCount != null) {
                book.setWordCount(wordCount);
            }
            if (publishDate != null) {
                book.setPublishDate(publishDate);
            }
            return bookRepository.save(book);
        }
        return null;
    }
    /**
     * 根据ID删除
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") String id) {
        log.info("Deleted ID: {}", id);
        bookRepository.deleteById(id);
    }
    /**
     * 删除所有
     */
    @PostMapping("/clear")
    public void clear() {
        log.info("Delete All!");
        bookRepository.deleteAll();
    }
    /**
     * 根据作者查询
     *
     * @param author
     * @return
     */
    @PostMapping("/author")
    public List<Book> byAuthor(String author) {
        log.info("By Author");
        return bookRepository.findByAuthor(author);
    }
    /**
     * 根据作者检索
     *
     * @param author
     * @return
     */
    @PostMapping("/author/like")
    public List<Book> byAuthorLike(String author) {
        log.info("By Author Like");
        return bookRepository.findByAuthorLike(author);
    }
    /**
     * 根据标题查询
     *
     * @param title
     * @return
     */
    @PostMapping("/title")
    public List<Book> byTitle(String title) {
        log.info("By Title");
        return bookRepository.findByTitle(title);
    }
    /**
     * 根据字数查询
     *
     * @param wordCount
     * @return
     */
    @GetMapping("/wordCount/{count}")
    public List<Book> byWordCount(@PathVariable("count") Integer wordCount) {
        log.info("By WordCount");
        return bookRepository.findByWordCount(wordCount);
    }
    /**
     * 根据作者与标题查询
     *
     * @param author
     * @param title
     * @return
     */
    @PostMapping("/query")
    public List<Book> byAuthorAndTitle(String author, String title) {
        log.info("By AuthorAndTitle");
        return bookRepository.findByAuthorAndTitle(author, title);
    }
    /**
     * 根据标题查询@Query
     *
     * @param title
     * @return
     */
    @PostMapping("/query/title")
    public List<Book> queryByTitle(String title) {
        log.info("Query By Title");
        return bookRepository.queryByTitle(title);
    }
}


相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。 &nbsp;
目录
相关文章
存储 JSON Java
1214 0
|
缓存 监控 安全
电商API集成入门:从零开始搭建高效接口
在数字化电商时代,API集成成为企业提升效率、实现系统互联的关键。本文从零开始,逐步讲解如何搭建高效、可靠的电商API接口,适合初学者学习。内容涵盖API基础、认证安全、请求处理、性能优化等核心步骤,并提供Python代码示例与数学公式辅助理解。通过实践,读者可掌握构建优质电商API的技巧,提升用户体验与系统性能。
|
人工智能 运维 自然语言处理
Elasticsearch AI Assistant 集成 DeepSeek,1分钟搭建智能运维助手
Elasticsearch 新支持 DeepSeek 系列模型,使用 AI 助手,通过自然语言交互,为可观测性分析、安全运维管理及数据智能处理提供一站式解决方案。
2128 3
Elasticsearch AI Assistant 集成 DeepSeek,1分钟搭建智能运维助手
|
开发框架 缓存 .NET
GraphQL 与 ASP.NET Core 集成:从入门到精通
本文详细介绍了如何在ASP.NET Core中集成GraphQL,包括安装必要的NuGet包、创建GraphQL Schema、配置GraphQL服务等步骤。同时,文章还探讨了常见问题及其解决方法,如处理复杂查询、错误处理、性能优化和实现认证授权等,旨在帮助开发者构建灵活且高效的API。
701 3
|
消息中间件 监控 Java
您是否已集成 Spring Boot 与 ActiveMQ?
您是否已集成 Spring Boot 与 ActiveMQ?
751 0
|
开发框架 监控 搜索推荐
GoFly快速开发框架集成ZincSearch全文搜索引擎 - Elasticsearch轻量级替代为ZincSearch全文搜索引擎
本文介绍了在项目开发中使用ZincSearch作为全文搜索引擎的优势,包括其轻量级、易于安装和使用、资源占用低等特点,以及如何在GoFly快速开发框架中集成和使用ZincSearch,提供了详细的开发文档和实例代码,帮助开发者高效地实现搜索功能。
1291 0
|
Web App开发 JavaScript Java
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
这篇文章是关于如何使用Spring Boot整合Elasticsearch,并通过REST客户端操作Elasticsearch,实现一个简单的搜索前后端,以及如何爬取京东数据到Elasticsearch的案例教程。
1176 0
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
|
JSON Java 网络架构
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
这篇文章介绍了如何使用Spring Boot整合REST方式来搭建和操作Elasticsearch服务。
644 4
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务