【问题标题】:Elasticsearch Bulk Index - Update only if existsElasticsearch 批量索引 - 仅在存在时更新
【发布时间】:2016-08-14 15:45:26
【问题描述】:

我正在使用Elasticsearch Bulk Index 更新文档的一些统计信息,但我尝试更新的文档可能不存在 - 在这种情况下,我希望它什么也不做。

我不希望它在这种情况下创建文档。

我在文档中没有找到任何内容,或者可能错过了。

我当前的操作(在这种情况下它会创建文档):

{
    update: {
        _index: "index1",
        _type: "interaction",
        _id: item.id
    }
},
{
    script: {
        file: "update-stats",
        lang: "groovy",
        params: {
            newCommentsCount: newRetweetCount,
        }
    },
    upsert: normalizedItem
}

如果文档存在,我如何更新文档,否则什么都不更新?

谢谢

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    不要使用 upsert 并使用正常更新。 此外,如果更新时文档不存在,更新将失败。 它应该适合你。

    【讨论】:

    • 没有 upsert 子句的更新将失败并创建异常。如果应用程序在设计上需要这种仅在存在时更新的功能,那么将以这种方式抛出许多异常。鉴于一些关于异常速度有多慢的 SO Q&A 点,这种解决方案不会引起性能问题吗?
    【解决方案2】:

    以下为我使用 elasticsearch 7.15.2 工作(需要检查支持的最低版本,参考:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html#update-api-example

    curl --location --request POST 'http://127.0.0.1:9200/exp/_update/8' \
    --header 'Content-Type: application/json' \
    --data-raw '
    {
      "scripted_upsert": true,
      "script": {
        "source": "if ( ctx.op == \"create\" )  {ctx.op=\"noop\"} else  {ctx._source.name=\"updatedName\"} ",
        "params": {
          "count": 4
        }
      },
      "upsert": {}
    }
    
    '
    

    如果 ES 即将创建一条新记录(ctx.op 是 "create" 那么我们将 op 更改为 "noop" 并且什么都不做,否则我们通过脚本进行正常更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2016-04-16
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      相关资源
      最近更新 更多