简体   繁体   English

用字段条件替换 Elasticsearch 索引中的文档

[英]Replace document in Elasticsearch index with field condition

If I have indexed a document in Elasticsearch that contains a datetime parameter, or some kind of sequence number, can I update/replace the entire document with a new version if, and only if, the value in my new document is greater than that in the currently indexed document?如果我在 Elasticsearch 中索引了一个包含日期时间参数或某种序列号的文档,当且仅当我的新文档中的值大于当前索引的文档?

Searching has shown me so far how I can affect the values of specific fields through scripting, but I'm not sure if I can use a script or operation as an update criterion, and replace the whole document if it's met.到目前为止,搜索已经向我展示了如何通过脚本影响特定字段的值,但我不确定是否可以使用脚本或操作作为更新标准,并在满足时替换整个文档。

To be more specific, we have a document object that contains a timestamp of when it was placed on the queue for processing, and since we may have multiple processors pulling things off the queue we would like to ensure that we only index documents newer than the one we already have in the index, discarding any old changes.更具体地说,我们有一个文档对象,其中包含将其放入队列进行处理的时间戳,并且由于我们可能有多个处理器将事物从队列中取出,因此我们希望确保我们只索引比队列更新的文档我们已经在索引中的一个,丢弃任何旧的更改。

Try to use the _update_by_query Api.尝试使用_update_by_query Api。

Update By Query 按查询更新

Example:例子:

Mappings映射

PUT my_index
{
  "mappings": {
    "properties": {
      "user": {
        "type": "keyword"
      },
      "timestamp": {
        "type": "keyword"
      }
    }
  }
}

Indexing documents索引文件

POST my_index/_doc/1
{
  "user":"user1",
  "timestamp":1234
}

POST my_index/_doc/2
{
  "user":"user2",
  "timestamp":1235
}

Update By Query按查询更新

Let's update only documents with timestamp greater than 1234 .让我们只更新timestamp大于1234文档。

POST /my_index/_update_by_query
{
  "script": {
    "source": "ctx._source.user='new user';", ----> updating field user
    "lang": "painless"
  },
  "query": {
    "range": {
      "timestamp": {
        "gt": 1234
      }
    }
  }
}

You can update other fields or insert new ones, just play with "source": "ctx._source.user='new user';ctx._source.timestamp=456";ctx._source.new_field=value"您可以更新其他字段或插入新字段,只需使用"source": "ctx._source.user='new user';ctx._source.timestamp=456";ctx._source.new_field=value"

Results结果

 {
    "_index": "my_index",
    "_type": "_doc",
    "_id": "2",
    "_score": 1,
    "_source": {
      "user": "new user",
      "timestamp": 1235
    }
  }

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM