springboot环境下在es内有门店索引、商品索引现将门店索引和商品索引联表查询分页返回门店商品集合
在Spring Boot环境下,可以使用Elasticsearch的Java高级客户端来实现门店索引和商品索引的联表查询,并进行分页返回门店商品集合。
首先,需要在pom.xml文件中添加Elasticsearch的Java高级客户端的依赖:
<dependencies>
...
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.7.0</version>
</dependency>
...
</dependencies>
接下来,创建一个Elasticsearch的配置类,用于配置Elasticsearch的连接信息:
@Configuration
public class ElasticsearchConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private int port;
@Bean
public RestHighLevelClient elasticsearchClient() {
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
在配置文件application.properties中添加Elasticsearch连接配置:
elasticsearch.host=localhost
elasticsearch.port=9200
然后,创建一个门店商品的实体类,用于映射门店索引和商品索引的数据:
public class StoreProduct {
private String storeId;
private String storeName;
private String productId;
private String productName;
// 省略getter和setter方法
}
接下来,创建一个门店商品的服务类,用于进行联表查询和分页返回门店商品集合:
@Service
public class StoreProductService {
@Autowired
private RestHighLevelClient elasticsearchClient;
public List<StoreProduct> getStoreProducts(int page, int size) throws IOException {
SearchRequest searchRequest = new SearchRequest("store_product_index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.from((page - 1) * size);
searchSourceBuilder.size(size);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
List<StoreProduct> storeProducts = new ArrayList<>();
for (SearchHit hit : searchResponse.getHits().getHits()) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
StoreProduct storeProduct = new StoreProduct();
storeProduct.setStoreId((String) sourceAsMap.get("storeId"));
storeProduct.setStoreName((String) sourceAsMap.get("storeName"));
storeProduct.setProductId((String) sourceAsMap.get("productId"));
storeProduct.setProductName((String) sourceAsMap.get("productName"));
storeProducts.add(storeProduct);
}
return storeProducts;
}
}
最后,在Controller类中调用门店商品的服务类,实现分页返回门店商品集合的接口:
@RestController
public class StoreProductController {
@Autowired
private StoreProductService storeProductService;
@GetMapping("/store-products")
public List<StoreProduct> getStoreProducts(@RequestParam int page, @RequestParam int size) throws IOException {
return storeProductService.getStoreProducts(page, size);
}
}
现在,可以通过访问/store-products?page=1&size=10接口来获取分页返回的门店商品集合
原文地址: https://www.cveoy.top/t/topic/h3xb 著作权归作者所有。请勿转载和采集!