Spring Boot Elasticsearch 多字段或精确搜索教程
在 Spring Boot 中,可以使用 Elasticsearch 进行多字段或精确搜索。你可以使用 Elasticsearch 的 QueryBuilders 来构建查询。
以下是一个示例,说明如何在 Spring Boot 中使用 Elasticsearch 进行多字段或精确搜索:
- 首先,确保你已经在 pom.xml 文件中添加了 Elasticsearch 的依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
- 创建一个 Elasticsearch 的 repository 接口,继承自 ElasticsearchRepository。假设我们要搜索一个名为'User'的实体。
@Repository
public interface UserRepository extends ElasticsearchRepository<User, String> {
List<User> findByFirstNameOrLastName(String firstName, String lastName);
}
- 在 Service 或 Controller 中使用该 repository 接口进行搜索。
@Autowired
private UserRepository userRepository;
public List<User> searchUsers(String keyword) {
return userRepository.findByFirstNameOrLastName(keyword, keyword);
}
在上面的示例中,findByFirstNameOrLastName 方法将根据给定的 firstName 或 lastName 字段进行搜索。
这样,你就可以在 Spring Boot 中使用 Elasticsearch 进行多字段或精确搜索了。
原文地址: http://www.cveoy.top/t/topic/bFDr 著作权归作者所有。请勿转载和采集!