通常ES存储数据是直接插入JSON数据(此操作在另一篇博文中记录:ES中JSON文档存储),而在实际Java开发中一般定义数据接收对象是个实体对象,对ES进行新增修改操作时就需要进行进一步的转换;
1.新增保存
public boolean save(T entity) {
boolean result = false;
String index = indexName(entity);
Assert.notNull(index, INDEX_NULL);
IndexRequest request = new IndexRequest(index).source(removeNull(entity));
if(isNotEmpty(entity.get_id())){
//指定id,如果ES中存在则更新,不存在则新增
//不指定时,ES自己生成唯一主键
request.id(entity.get_id());
}
if(isNotEmpty(entity.getRouting())){
//指定routing,在插入父子文档数据时为必需
request.routing(entity.getRouting());
}
try {
client.index(request, RequestOptions.DEFAULT);
result = true;
} catch (IOException e) {
log.error("保存数据失败:", e);
}
return result;
}
entity转map,过滤null
private Map<String, Object> removeNull(T entity) {
BeanMap beanMap = BeanMap.create(entity);
Map<String, Object> map = new HashMap<>();
beanMap.forEach((key, value) -> {
if (null != value && !EXCLUDE_FIELD.contains(String.valueOf(key))) {
if(value instanceof List){
map.put(String.valueOf(key), parseArray(JSON.toJSONString(value)));
}else if(value instanceof EvntRel)