SpringBoot Elasticsearch 关键字搜索:基于产品名称、厂家、SKU 的商品搜索
要使用 Spring Boot 和 Elasticsearch 进行关键字搜索,需要执行以下步骤:
-
首先,确保已经创建了一个名为'platform_drug_index' 的索引,并且索引中包含了产品名称('product_name')、厂家('manufacturer') 和 SKU('sku') 字段。
-
在 Spring Boot 项目中添加 Elasticsearch 相关的依赖,可以使用 Maven 或 Gradle 进行添加。
-
创建一个 Elasticsearch 的配置类,配置 Elasticsearch 的连接信息。例如,在 application.properties 文件中添加以下配置:
spring.data.elasticsearch.cluster-name=elasticsearch spring.data.elasticsearch.cluster-nodes=localhost:9300 -
创建一个 Elasticsearch 的 Repository 接口,用于执行搜索操作。例如,创建一个名为 DrugRepository 的接口,并继承自 ElasticsearchRepository:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface DrugRepository extends ElasticsearchRepository<Drug, Long> { }注意:这里的 Drug 是一个自定义的实体类,用于表示索引中的数据。
-
创建一个 Service 类,用于执行搜索操作。例如,创建一个名为 DrugService 的类:
import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DrugService { @Autowired private DrugRepository drugRepository; public Iterable<Drug> searchDrugs(String keyword) { SearchRequest searchRequest = new SearchRequest('platform_drug_index'); searchRequest.source().query(QueryBuilders.multiMatchQuery(keyword, 'product_name', 'manufacturer', 'sku')); return drugRepository.search(searchRequest).getHits(); } }注意:这里的 DrugRepository 是通过 @Autowired 注入的,所以确保已经创建了 DrugRepository 的 Bean。
-
在 Controller 中使用 DrugService 进行搜索操作。例如,创建一个名为 DrugController 的类:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping('/drugs') public class DrugController { @Autowired private DrugService drugService; @GetMapping('/search/{keyword}') public Iterable<Drug> searchDrugs(@PathVariable String keyword) { return drugService.searchDrugs(keyword); } }这样,当访问
/drugs/search/{keyword}接口时,就可以执行搜索操作并返回搜索结果。
请根据您的实际需求进行适当的修改和扩展。
原文地址: https://www.cveoy.top/t/topic/bZNr 著作权归作者所有。请勿转载和采集!