概述
全文检索是指通过对文档进行索引和搜索,实现高效的文本搜索和匹配功能。Elasticsearch是一种开源的分布式全文搜索引擎,具有高性能、可扩展和易用的特点。本文将介绍如何使用Spring Boot整合Elasticsearch实现全文检索功能。
环境准备
在开始之前,需要准备以下环境:
- JDK 1.8及以上版本
- Spring Boot 2.5.3
- Elasticsearch 7.13.2
添加依赖
在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
配置Elasticsearch
在application.properties文件中添加以下配置:
spring.elasticsearch.rest.uris=http://localhost:9200
spring.elasticsearch.rest.username=user
spring.elasticsearch.rest.password=pass
创建实体类
创建一个实体类用于表示索引中的文档,例如:
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "articles", type = "article")
public class Article {
@Id
private String id;
private String title;
private String content;
// 省略getter和setter方法
}
创建ElasticsearchRepository
创建一个继承自ElasticsearchRepository
的接口,用于操作Elasticsearch的文档:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ArticleRepository extends ElasticsearchRepository<Article, String> {
Page<Article> findByTitleOrContent(String title, String content, Pageable pageable);
}
编写业务逻辑
在业务逻辑中使用ArticleRepository
进行全文检索操作,例如:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
@Service
public class ArticleService {
private final ArticleRepository articleRepository;
@Autowired
public ArticleService(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
public Page<Article> search(String keyword, int pageNumber, int pageSize) {
return articleRepository.findByTitleOrContent(keyword, keyword, PageRequest.of(pageNumber, pageSize));
}
}
编写控制器
编写一个Restful API的控制器,用于接收搜索请求,并调用ArticleService
处理请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ArticleController {
private final ArticleService articleService;
@Autowired
public ArticleController(ArticleService articleService) {
this.articleService = articleService;
}
@GetMapping("/search")
public Page<Article> search(@RequestParam String keyword, @RequestParam int pageNumber, @RequestParam int pageSize) {
return articleService.search(keyword, pageNumber, pageSize);
}
}
启动应用程序
运行Spring Boot应用程序,并访问http://localhost:8080/search?keyword=java&pageNumber=0&pageSize=10
进行全文检索,其中keyword
为搜索关键字,pageNumber
和pageSize
分别为分页参数。
结语
通过Spring Boot整合Elasticsearch,我们可以快速方便地实现全文检索功能。Elasticsearch提供了强大的搜索和匹配功能,可以大大提高文本搜索的效率。希望本文对你了解Spring Boot和Elasticsearch的整合有所帮助。
本文来自极简博客,作者:时光旅者,转载请注明原文链接:Springboot整合Elasticsearch实现全文检索功能