Day28:ElasticSearch入门、Spring整合ES、开发社区搜索功能
由于篇幅所限,我将提供ElasticSearch入门和Spring整合ES的核心代码示例。
ElasticSearch入门
安装ElasticSearch并启动服务。
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
sudo apt-get install apt-transport-https
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list
sudo apt-get update && sudo apt-get install elasticsearch
sudo systemctl start elasticsearch.service
Spring整合ES
- 添加依赖到
pom.xml
。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>
- 配置
application.yml
。
spring:
elasticsearch:
rest:
uris: "http://localhost:9200"
- 创建实体类。
@Document(indexName = "community")
public class DiscussPost {
@Id
private int id;
// 其他属性
}
- 创建Repository接口。
public interface DiscussPostRepository extends ElasticsearchRepository<DiscussPost, Integer> {
}
- 使用Repository进行搜索。
@Service
public class SearchService {
@Autowired
private DiscussPostRepository discussPostRepository;
public Page<DiscussPost> findDiscussPosts(String keyword, int page, int size) {
PageRequest pageRequest = PageRequest.of(page, size);
if (StringUtils.isNotBlank(keyword)) {
// 使用关键字搜索
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.multiMatchQuery(keyword, "title", "content"))
.withPageable(pageRequest)
.build();
return discussPostRepository.search(query);
} else {
// 不使用关键字搜索
return discussPostRepository.findAll(pageRequest);
}
}
}
开发社区搜索功能
@Controller
@RequestMapping("/search")
public class SearchController {
@Autowired
private SearchService searchService;
@RequestMapping(method = RequestMethod.GET)
public String getSearchPage(Model model, @RequestParam(name = "keyword", required = false) String keyword,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue
评论已关闭