public Boolean updateArray(String indexName, QueryBuilder queryBuilder, Map<String, Object> params) throws IOException {
UpdateByQueryRequest updateByQuery = new UpdateByQueryRequest();
updateByQuery.indices(indexName);
updateByQuery.setQuery(queryBuilder);
StringBuilder sb = new StringBuilder(params.size());
params.forEach((k, v) -> {
if (v instanceof Map) {
Map<String, Object> arrayList = (Map<String, Object>) v;
sb.append(StrUtil.format("ctx._source.{} = new ArrayList();", k, arrayList.size(), k, k));
arrayList.forEach((a, f) -> {
sb.append(StrUtil.format("ctx._source.{}.add(params.{}.{});", k, k, a));
});
} else {
sb.append(StrUtil.format("ctx._source.{} = params.{};", k, k));
}
});
Script script = new Script(ScriptType.INLINE, "painless", sb.toString(), params);
updateByQuery.setScript(script);
BulkByScrollResponse bulkByScrollResponse = restHighLevelClient.updateByQuery(updateByQuery, RequestOptions.DEFAULT);
if (bulkByScrollResponse.getUpdated() > 0) {
refresh(indexName);
return true;
}
return false;
}
public void refresh(String indexName) throws IOException {
restHighLevelClient.indices().refresh(new RefreshRequest().indices(indexName), RequestOptions.DEFAULT);
}
public void test(){
Map<String, Object> params = new HashMap<>(2);
Map<String, Object> paramList = new HashMap<>(2);
paramList.put("a1", 1);
paramList.put("a2", 2);
params.put("list", paramList);
params.put("name", "li");
updateArray("indexName",new QueryBuilder(), params);
}
标签:Map,java,updateByQuery,indexName,更新,params,sb,new,es
From: https://www.cnblogs.com/eoore/p/17516462.html