SpringBoot Elasticsearch 商品搜索:厂家字段'或'关系匹配
在 Spring Boot 中使用 Elasticsearch 进行商品搜索时,可以使用 bool 查询来实现厂家字段的'或'关系匹配。
首先,您需要在 pom.xml 文件中添加 Elasticsearch 和 Spring Data Elasticsearch 的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
然后,您需要在您的实体类中定义商品的字段和注解:
@Document(indexName = "products")
public class Product {
@Id
private String id;
private String name;
private String manufacturer;
// getters and setters
}
接下来,您需要创建一个 Elasticsearch 的 Repository 接口来进行搜索操作:
@Repository
public interface ProductRepository extends ElasticsearchRepository<Product, String> {
List<Product> findByManufacturer(String manufacturer);
}
在这个 Repository 接口中,我们定义了一个 findByManufacturer 方法,它将根据厂家字段来搜索商品。
最后,在您的服务类中,您可以使用 ProductRepository 来执行搜索操作:
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> searchByManufacturer(String manufacturer) {
return productRepository.findByManufacturer(manufacturer);
}
}
通过调用 searchByManufacturer 方法,您可以根据厂家字段来搜索商品,并且它会返回与厂家字段匹配的所有商品。
请注意,以上示例假设您已经配置好了 Elasticsearch 的连接信息。您可以在 application.properties 文件中配置 Elasticsearch 的主机和端口:
spring.data.elasticsearch.cluster-nodes=localhost:9200
希望这可以帮助到您!
原文地址: https://www.cveoy.top/t/topic/b8i0 著作权归作者所有。请勿转载和采集!