SpringBoot Elasticsearch 多字段精准查询 - 使用 MultiMatchQueryBuilder
在 Spring Boot 中使用 Elasticsearch 进行多字段精确查询可以使用'MultiMatchQueryBuilder'类型。'MultiMatchQueryBuilder'允许指定多个字段并设置它们的权重,以便根据指定的查询条件在这些字段中进行搜索。
下面是一个使用 Spring Boot 和 Elasticsearch 进行多字段精确查询的示例:
- 首先,确保您的 Spring Boot 项目已经配置了 Elasticsearch 依赖项。在'pom.xml'文件中添加以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
- 创建一个 Elasticsearch 的 Repository 接口,用于定义查询方法。例如,创建一个'BookRepository'接口:
@Repository
public interface BookRepository extends ElasticsearchRepository<Book, String> {
List<Book> searchByTitleAndAuthor(String title, String author);
}
- 创建一个实体类'Book',并使用'@Document'注解标记为 Elasticsearch 的文档类型:
@Document(indexName = "books")
public class Book {
@Id
private String id;
private String title;
private String author;
// getters and setters
}
- 在'BookRepository'接口中定义一个使用'MultiMatchQueryBuilder'进行多字段精确查询的方法:
@Repository
public interface BookRepository extends ElasticsearchRepository<Book, String> {
@Query("{"multi_match": {"query": "?0", "fields": ["title^3", "author^2"]}}")
List<Book> searchByTitleAndAuthor(String query);
}
这里使用了'@Query'注解来定义查询语句,其中'?0'表示第一个参数,'title^3'和'author^2'表示字段及其权重。
- 在 Service 或 Controller 中使用'BookRepository'进行查询:
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public List<Book> searchBooks(String query) {
return bookRepository.searchByTitleAndAuthor(query);
}
}
这样就可以通过调用'searchBooks'方法来执行多字段精确查询了。
注意:在进行多字段查询时,需要确保指定的字段在文档中存在,并且已经正确建立了索引。
原文地址: https://www.cveoy.top/t/topic/0x7 著作权归作者所有。请勿转载和采集!