public void batchInsert(List<Map> orders) { StringBuilder bulkRequestBody = new StringBuilder(); int count = 1 ; for (Map order : orders) { String actionMetaData = String.format( "{ \"index\" : {\"_id\" : \"%s\"} }%n" , order.get(OrderEsConstant.ORDER_ID)); String orderJson = JSON.toJSONString(order, SerializerFeature.WriteNullStringAsEmpty); bulkRequestBody.append(actionMetaData); bulkRequestBody.append(orderJson); bulkRequestBody.append( "\n" ); if (count % 5000 == 0 || count == orders.size()) { Response response; Map result = Maps.newHashMap(); String router = String.format(BASIC_FORMAT, ES_INDEX, ES_TYPE, "_bulk" ); try { response = restClient.performRequest(POST, router, Collections.emptyMap(), new StringEntity(bulkRequestBody.toString(), ContentType.APPLICATION_JSON)); result = objectMapper.readValue(response.getEntity().getContent(), Map. class ); } catch (IOException e) { log.info( "ES批量插入异常" ); } List<Map> itemResults = ((List<Map>) result.get( "items" )).stream().map(p -> (Map) p.get( "index" )).collect(Collectors.toList()); List errorMsgs = itemResults.stream().filter(p -> 200 != (Integer) p.get( "status" )).map( this ::getErrorMsg).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(errorMsgs)) { log.warn( "数据插入失败 -> {}" , errorMsgs); } log.info( "批处理完成,总条数: {}" , itemResults.size()); } count++; } } |