我有一个采用json对象并将其插入到aws弹性搜索服务中的方法,但我想编写另一种采用多个json对象并将其插入到aws弹性搜索中的方法
/**
* Create the Product in ElasticSearch
*
* @param product The Product
* @return The response string
* @throws JsonProcessingException Throws JsonProcessingException when response cannot be parsed
*/
public String createNewProduct(Product product) throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
final String json = objectMapper.writeValueAsString(product);
if (json != null) {
AwsResponse response = createDocument(ElasticSearchConstants.PRODUCTS_INDEX,
ElasticSearchConstants.PRODUCTS_DOCUMENT_TYPE,
json,
product.getPartNo());
// Creating a new document not seen before results in a 201 status, where as overwriting a previous document results in a 200
if (response != null && (response.getHttpResponse().getStatusCode() == HttpStatus.CREATED.value()
|| response.getHttpResponse().getStatusCode() == HttpStatus.OK.value())) {
LOGGER.info("Successfully created new Product", product.getPartNo(), product.getLevelOne());
return product.getPartNo();
}
}
return null;
}
/**
* Create new Products in ElasticSearch
* @param products The product
* @throws JsonProcessingException Throws JsonProcessingException when response cannot be parsed
*/
public String createNewProducts(ArrayList<Product> products) throws JsonProcessingException{
final ObjectMapper objectMapper = new ObjectMapper();
products.stream()
.map(product -> {
try {
return objectMapper.writeValueAsString(product);
} catch (JsonProcessingException e) {
return new JsonProcessingException(e){};
}
})
.forEach(product -> {
createDocument(ElasticSearchConstants.PRODUCTS_INDEX,
ElasticSearchConstants.PRODUCTS_DOCUMENT_TYPE,
product,
products.stream().forEach(p->p::getPartNo)
);
});
return null;
}
如您所见,createDocument方法需要4个参数,其中4个是字符串 第一种方法确实很好用,但是第二种方法有问题。 当我尝试获取partNo时,它像正常的“ void is notfunctional interface”一样给我一个错误,我该如何使其正常工作。
答案 0 :(得分:0)
您不需要执行map
,forEach
可以解决您的情况。在这种情况下,stream
的使用也不是很有效。您可以简单地编写一个for
循环并按以下步骤执行操作:
for (Product product : products) {
String json = objectMapper.writeValueAsString(product);
// handle the exception as well above
createDocument(ElasticSearchConstants.PRODUCTS_INDEX,
ElasticSearchConstants.PRODUCTS_DOCUMENT_TYPE,
json, product.getPartNo());
}