Elasticsearch实战-update_by_query使用

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();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值