Elasticsearch实战-update_by_query使用
提示:涵盖_update_by_query、_delete_by_query,字段移除,id查询等
一、update_by_query
1.语句
代码如下(示例):
POST /test/_update_by_query
{
"script": {
"source": "ctx._source.k_VENDORID = params.newValue; if (!ctx._source.containsKey('t_CLEANTIME')) {def dateFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss'); ctx._source.t_CLEANTIME = dateFormat.format(new Date()) ; }",
"lang": "painless",
"params": {
"newValue": "6666666666666666666666666666666666"
}
},
"query": {
"term": {
"_id": {
"value": "bg8lgooBm62Q6jNaiSK4"
}
}
}
}
POST test/_update_by_query
{
"query": {
"term": {
"_id": "bg8lgooBm62Q6jNaiSK4"
}
},
"script": {
"source": "ctx._source.remove('t_CLEANTIME')"
}
}
GET test/_doc/bg8lgooBm62Q6jNaiSK4
```es
POST /test/_delete_by_query
{
"query": {
"bool": {
"must": [
{
"term": {
"NAME": {
"value": "HB"
}
}
}
]
}
}
}
2.对应api
代码如下(示例):
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UpdateDateFieldExample {
public static void main(String[] args) throws IOException {
// 创建RestHighLevelClient实例
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 构建UpdateRequest
UpdateRequest request = new UpdateRequest("your_index", "your_document_id");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDate = dateFormat.format(new Date());
String script = "ctx._source.date_field = '" + currentDate + "'";
request.scriptedUpsert(true);
request.script(script, XContentType.JSON);
// 执行UpdateRequest并获取响应
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
// 处理响应
String index = response.getIndex();
String id = response.getId();
long version = response.getVersion();
// 关闭RestHighLevelClient
client.close();
}
}