ES学习四 -- Update

Update

Request

POST /<index>/_update/<_id>

Description

Enables you to script document updates. The script can update, delete, or skip modifying the document. The update API also supports passing a partial document, which is merged into the existing document. To fully replace an existing document, use the index API.

This operation

  1. Gets the document (collocated with the shard) from the index.
  2. Runs the specified script.
  3. Indexes the result.

Query parameters

  • if_seq_no
    (Optional, integer) Only perform the operation if the document has this sequence number. See Optimistic concurrency control.
  • if_primary_term
    (Optional, integer) Only perform the operation if the document has this primary term. See Optimistic concurrency control.
  • lang
    (Optional, string) The script language. Default: painless.
  • require_alias
    (Optional, Boolean) If true, the destination must be an index alias. Defaults to false.
  • refresh
    (Optional, enum) If true, Elasticsearch refreshes the affected shards to make this operation visible to search, if wait_for then wait for a refresh to make this operation visible to search, if false do nothing with refreshes. Valid values: true, false, wait_for. Default: false.
  • retry_on_conflict
    (Optional, integer) Specify how many times should the operation be retried when a conflict occurs. Default: 0.
  • routing
    (Optional, string) Target the specified primary shard.
  • _source
    (Optional, list) Set to false to disable source retrieval (default: true). You can also specify a comma-separated list of the fields you want to retrieve.
  • _source_excludes
    (Optional, list) Specify the source fields you want to exclude.
  • _source_includes
    (Optional, list) Specify the source fields you want to retrieve.
  • timeout
    (Optional, time units) Period to wait for the following operations:

Dynamic mapping updates
Waiting for active shards

Defaults to 1m (one minute). This guarantees Elasticsearch waits for at least the timeout before failing. The actual wait time could be longer, particularly when multiple waits occur.

  • wait_for_active_shards
    (Optional, string) The number of shard copies that must be active before proceeding with the operation. Set to all or any positive integer up to the total number of shards in the index (number_of_replicas+1). Default: 1, the primary shard.

Examples

First, let’s index a simple doc:

PUT test/_doc/1
{
  "counter" : 1,
  "tags" : ["red"]
}

To increment the counter, you can submit an update request with the following script:

POST test/_update/1
{
  "script" : {
    "source": "ctx._source.counter += params.count",
    "lang": "painless",
    "params" : {
      "count" : 4
    }
  }
}

Similarly, you could use and update script to add a tag to the list of tags (this is just a list, so the tag is added even it exists):

POST test/_update/1
{
  "script": {
    "source": "ctx._source.tags.add(params.tag)",
    "lang": "painless",
    "params": {
      "tag": "blue"
    }
  }
}

You could also remove a tag from the list of tags. The Painless function to remove a tag takes the array index of the element you want to remove. To avoid a possible runtime error, you first need to make sure the tag exists. If the list contains duplicates of the tag, this script just removes one occurrence.

POST test/_update/1
{
  "script": {
    "source": "if (ctx._source.tags.contains(params.tag)) { ctx._source.tags.remove(ctx._source.tags.indexOf(params.tag)) }",
    "lang": "painless",
    "params": {
      "tag": "blue"
    }
  }
}

You can also add and remove fields from a document. For example, this script adds the field new_field:

POST test/_update/1
{
  "script" : "ctx._source.new_field = 'value_of_new_field'"
}

Conversely, this script removes the field new_field:

POST test/_update/1
{
  "script" : "ctx._source.remove('new_field')"
}

Instead of updating the document, you can also change the operation that is executed from within the script. For example, this request deletes the doc if the tags field contains green, otherwise it does nothing (noop):

POST test/_update/1
{
  "script": {
    "source": "if (ctx._source.tags.contains(params.tag)) { ctx.op = 'delete' } else { ctx.op = 'none' }",
    "lang": "painless",
    "params": {
      "tag": "green"
    }
  }
}

update part of a document

The following partial update adds a new field to the existing document:

POST test/_update/1
{
  "doc": {
    "name": "new_name"
  }
}

If both doc and script are specified, then doc is ignored. If you specify a scripted update, include the fields you want to update in the script.

Detect noop updates

By default updates that don’t change anything detect that they don’t change anything and return "result": "noop":

POST test/_update/1
{
  "doc": {
    "name": "new_name"
  }
}

If the value of name is already new_name, the update request is ignored and the result element in the response returns noop:

{
   "_shards": {
        "total": 0,
        "successful": 0,
        "failed": 0
   },
   "_index": "test",
   "_type": "_doc",
   "_id": "1",
   "_version": 7,
   "_primary_term": 1,
   "_seq_no": 6,
   "result": "noop"
}

You can disable this behavior by setting "detect_noop": false:

POST test/_update/1
{
  "doc": {
    "name": "new_name"
  },
  "detect_noop": false
}

Upsert

If the document does not already exist, the contents of the upsert element are inserted as a new document. If the document exists, the script is executed:

POST test/_update/1
{
  "script": {
    "source": "ctx._source.counter += params.count",
    "lang": "painless",
    "params": {
      "count": 4
    }
  },
  "upsert": {
    "counter": 1
  }
}

Scripted upsert

To run the script whether or not the document exists, set scripted_upsert to true:

POST sessions/_update/dh3sgudg8gsrgl
{
  "scripted_upsert": true,
  "script": {
    "id": "my_web_session_summariser",
    "params": {
      "pageViewEvent": {
        "url": "foo.com/bar",
        "response": 404,
        "time": "2014-01-01 12:32"
      }
    }
  },
  "upsert": {}
}

Doc as upsert

Instead of sending a partial doc plus an upsert doc, you can set doc_as_upsert to true to use the contents of doc as the upsert value:

POST test/_update/1
{
  "doc": {
    "name": "new_name"
  },
  "doc_as_upsert": true
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,137评论 6 511
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,824评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,465评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,131评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,140评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,895评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,535评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,435评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,952评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,081评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,210评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,896评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,552评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,089评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,198评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,531评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,209评论 2 357

推荐阅读更多精彩内容