我正在使用 Spring Data Elasticsearch 开发 Spring Boot 应用程序,并且尝试使用通配符查询和更新字段的脚本来执行批量更新。以下是我的服务等级:
考虑到此查询可以在 Elasticsearch 开发工具上执行并更新文档
@Slf4j
@Service
@RequiredArgsConstructor
public class ElasticsearchBulkUpdateService {
private final ElasticsearchOperations elasticsearchOperations;
public void updateProfitForPattern(String idPattern, String indexName) {
log.info("Executing simple query on index '{}':", indexName);
Query query = new StringQuery("""
{
"query": {
"wildcard": {
"id": {
"value": "*-14030701"
}
}
},
"script": {
"source": "
if (ctx._source.fundUnit != null) {
ctx._source.profit = ctx._source.fundUnit * 5;
}
",
"lang": "painless"
}
}
""");
UpdateQuery searchQuery = UpdateQuery.builder(query).build();
IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);
ByQueryResponse byQueryResponse = elasticsearchOperations.updateByQuery(searchQuery, indexCoordinates);
System.err.println(byQueryResponse);
}
}
当我运行此代码时,出现以下异常:
org.springframework.data.elasticsearch.UncategorizedElasticsearchException:[es / update_by_query]失败:[parsing_exception]未知查询[查询]
Elasticsearch 查询似乎没有被正确识别。我将 Spring Data Elasticsearch 与 ElasticsearchOperations 结合使用。谁能指出我做错了什么或如何解决这个问题?
Spring启动版本:3.2.5 spring-boot-starter-data-elasticsearch 版本:5.2.5
发生这种情况是因为向 Elasticsearch 发送了结构错误的请求以进行 UpdateQuery 操作。
UpdateQuery 请求需要清楚地区分标识要更新文档的查询和概述如何执行这些更新的脚本。如果这些组件没有正确分离,Elasticsearch 将触发解析异常。
我在下面做了一些调整,
@Slf4j
@Service
@RequiredArgsConstructor
public class ElasticsearchBulkUpdateService {
private final ElasticsearchOperations elasticsearchOperations;
public void updateProfitForPattern(String indexName) {
System.out.println("Executing simple query on index '{}':" + indexName);
// Define the wildcard query to find documents to update
String queryString = """
{
"query": {
"wildcard": {
"id": {
"value": "*-14030701"
}
}
}
}
""";
// Define the update script
String script = """
{
"script": {
"source": "
if (ctx._source.fundUnit != null) {
ctx._source.profit = ctx._source.fundUnit * 5;
}
",
"lang": "painless"
}
}
""";
UpdateQuery updateQuery = UpdateQuery.builder(queryString)
.withScript(script)
.build();
IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);
ByQueryResponse byQueryResponse = elasticsearchOperations.updateByQuery(updateQuery, indexCoordinates);
System.err.println(byQueryResponse);
}
}