elasticsearch实现商品搜索
数据初始化
在项目启动时对未初始化的索引进行数据的初始化。
使用restHighLevelClient操作es,注意使用高版本es,restHighLevelClient对低版本es支持不好。
在项目启动时使用springboot的application做数据初始化
实例化客户端
//创建低级客户端 ip,端口,请求方式http或https
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostName, Integer.parseInt(port), scheme));
//创建高级客户端
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);
判断索引是否存在
//判断商品索引是否存在
boolean zeastProductExists;
try {
GetIndexRequest zeastProductExistsRequest = new GetIndexRequest();
zeastProductExistsRequest.indices(zeastProductIndex);
zeastProductExists = restHighLevelClient.indices().exists(zeastProductExistsRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
logger.error("ES索引判断异常!",e);
throw new RuntimeException("ES索引判断异常!");
}
索引不存在时进行索引初始化
创建索引
CreateIndexRequest createIndexRequest = new CreateIndexRequest(zeastProductIndex);
//创建索引
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
boolean createIndexResult = createIndexResponse.isAcknowledged();
if(!createIndexResult){
logger.error("ES商品索引初始化失败!");
return CommonResult.failed("ES商品索引初始化失败!");
}
boolean shardsCreateIndexResult = createIndexResponse.isShardsAcknowledged();
if(!shardsCreateIndexResult){
logger.error("ES商品索引初始化失败!");
return CommonResult.failed("ES商品索引初始化失败!");
}
索引创建完成后设置索引mapping
mapping设置
PutMappingRequest putMappingRequest = new PutMappingRequest(zeastProductIndex);
//设置type
putMappingRequest.type(zeastProductType);
Map<String, Object> jsonMap = new HashMap<>();
Map<String, Object> properties = new HashMap<>();
Map<String, Object> productId = new HashMap<>();
productId.put("type", "keyword");
properties.put("productId", productId);
Map<String, Object> productName = new HashMap<>();
productName.put("type", "keyword");
properties.put("productName", productName);
//keyword不分词 text分词
Map<String, Object> keyword = new HashMap<>();
keyword.put("type", "text");
properties.put("keyword", keyword);
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
jsonMap.put(zeastProductType, mapping);
putMappingRequest.source(jsonMap);
putMappingRequest.timeout(TimeValue.timeValueMinutes(2));
putMappingRequest.masterNodeTimeout(TimeValue.timeValueMinutes(1));
AcknowledgedResponse putMappingResponse = restHighLevelClient.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT);
boolean mappingResult = putMappingResponse.isAcknowledged();
if(!mappingResult){
logger.error("ES商品映射初始化失败!");
return CommonResult.failed("ES商品映射初始化失败!");
}
mapping设置完成后开始全量数据初始化
数据初始化
查询数据部分省略,初始化代码大概如下,数据组装多开了几个线程同时跑。
BulkRequest request = new BulkRequest();
//在任务执行完成后解析返回值,
for(Future<List<SearchProductDo>> future :futures){
try {
List