Service:
/**
* 添加文档
* @param obj
*/
public String createDoc(Object obj){
/**
* 设置索引,必须是小写,所以使用toLowerCase()方法进行转换
*/
IndexRequest request = new IndexRequest(obj.getClass().getSimpleName().toLowerCase());
/**
* 设置文档id。如果不设置,系统会自动生成
*/
//request.id("xxxx");
request.source(JSONObject.toJSONString(obj), XContentType.JSON);
try {
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
log.info(JSONObject.toJSONString(response));
if(DocWriteResponse.Result.CREATED == response.getResult()){
return response.getId();
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 批量处理文档
* @param list 需要处理的文档列表
*/
public void createMultiDoc(List list){
BulkRequest request = new BulkRequest();
/**
* 遍历
* IndexRequest不设置id,让系统自己添加
* DeleteRequest 批量删除
* UpdateRequest 批量更新
*/
list.forEach((obj)->{
request.add(new IndexRequest(obj.getClass().getSimpleName().toLowerCase())
.source(JSONObject.toJSONString(obj), XContentType.JSON));
});
try {
BulkResponse bulkResponse = client.bulk(request,RequestOptions.DEFAULT);
log.info(JSON