创建完索引后,我们就要添加数据开始处理业务了,不知道如何创建索引的同学可以看这篇文章
spring cloud 整合elasticsearch 创建索引支持ik中文分词和拼音分词_u010401588的博客-CSDN博客??????
?添加有两种:单个(同步),批量(异步)添加文档
1.单个同步添加数据
/**
* 单条添加文档
* @param indexEnum 索引
* @param key id
* @param jsonValue 文档json
* @param xContentBuilder 索引信息
* @return
*/
public boolean addOne(IndexEnum indexEnum, String key, String jsonValue, XContentBuilder xContentBuilder) {
//获得连接
RestHighLevelClient client=this.restHighLevelClient();
try {
//创建索引
createIndex(indexEnum, xContentBuilder);
IndexRequest indexRequest = new IndexRequest(indexEnum.getCode());
//将文档源设置为索引,文档内容类型
indexRequest.source(jsonValue, XContentType.JSON);
indexRequest.id(key);
//添加数据
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
log.info("add doc status:{} ,mas:{}", indexResponse.status(), JSON.toJSONString(indexResponse));
return indexResponse != null && indexResponse.status() == RestStatus.OK;
} catch (Exception e) {
log.info("addOne doc 异常! info:{}",jsonValue);
return false;
}finally {
try {
//关闭连接
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
?调用测试
public void create( ){
ProductIndex productIndex = new ProductIndex();
productIndex.setProductName("美国雅诗兰黛特润修护肌透精华露小棕瓶精华(七代)100ml");
productIndex.setBrandName("雅诗兰黛");
productIndex.setProductId(12345678987654321L);
String key = productIndex.getProductId().toString();
XContentBuilder xContentBuilder = ElasticsearchConfig.generateBuilder(ProductIndex.class);
boolean status = esService.addOne(IndexEnum.TEST, key, JSON.toJSONString(productIndex), xContentBuilder);
log.info("添加文档{}结果:{}",key,status?"成功":"失败");
}
|