seaswalker / posts

0 stars 0 forks source link

ElasticSearch update by query #26

Open seaswalker opened 3 years ago

seaswalker commented 3 years ago

ES版本5.6, Jest客户端:

UpdateByQuery updateByQuery = new UpdateByQuery.Builder(payload).addIndex(indexName).build();
UpdateByQueryResult result;
try {
    result = jestClient.execute(updateByQuery);
} catch (IOException e) {
    throw new IllegalStateException(e);
}
if (result.isSucceeded()) {
    log.info("更新索引: {}成功.", indexName, result.getUpdatedCount());
} else {
    throw new IllegalStateException(String.format("更新索引: %s失败, message: %s", indexName, result.getErrorMessage()));
}

jestClient来源于注入:

@Autowired
private JestClient jestClient;

核心是payload:

{
    "script": {
      "source": "ctx._source['fieldA']=params.variableA",
      "params": {
        "variableA": "%s"
      }
    },
    "query": {
      "bool": {
        "must": [
          {
            "match": {
              "conditionA": "%s"
            }
          },
          {
            "match": {
              "conditionB": "%s"
            }
          }
        ]
      }
    }
  }

注意引用变量variableA的时候必须有params.前缀,这一点可能在新版本ES上不需要了。另外source字段不要写成:

"source": "ctx._source['fieldA']='%s'"

不然请求次数过多出现错误: script.max_compilations_per_minute超出限制。 参考: Too many dynamic script compilations within, max: [75/5m]问题处理