【发布时间】:2013-11-03 00:00:04
【问题描述】:
是否可以在不覆盖其他字段的情况下更新 elasticsearch 中的某些特定字段值。 ?
【问题讨论】:
-
是的,感谢您的帮助。我使用了脚本格式并关注了update api
标签: search indexing elasticsearch
是否可以在不覆盖其他字段的情况下更新 elasticsearch 中的某些特定字段值。 ?
【问题讨论】:
标签: search indexing elasticsearch
作为对此答案的基于代码的贡献,可以使用以下查询:
POST /index/type/100100471/_update
{
"doc" : {
"yourProperty" : 10000
}
}
此查询更新yourProperty仅限属性。
因此,出现以下响应:
{
"_index": "index",
"_type": "type",
"_id": "100100471",
"_version": 1,
"_shards": {
"total": 0,
"successful": 1,
"failed": 0
}
}
【讨论】:
Validation Failed: 1: script or doc is missing; - 知道为什么吗?
在 ES 7.3 中,新格式为:
POST /myindex/_update/mydocid
{
"doc" : {
"myfield": "new value of my field"
}
}
【讨论】:
是的,Elasticsearch 支持部分更新。这意味着您可以提交:
看看update api。 在这两种情况下,由于底层 lucene 库的工作方式,底层发生的事情是检索要更新的文档,将更改应用于它,并且旧文档被新文档覆盖。归根结底,这实际上是对文档的完全重写,但您不必提交整个文档,除非您禁用默认启用的_source field,这是允许您检索的字段到整个文档,以便对其应用更改。
【讨论】:
如果您只想更新现有字段值,则必须尝试以下解决方案:
POST IndexName/_update_by_query
{
"script": {
"source": """
if (ctx._source?.Field != null)
{
ctx._source.remove('Field');
ctx._source.put('Field', 'Value');
}
""",
"lang": "painless"
},
"query": {
"terms": {
"_id": [
1 (Replace with Document ID)
]
}
}
}
如果您想添加具有值的新字段,则必须尝试以下解决方案:
POST IndexName/_update_by_query
{
"script": {
"source": """
if (ctx._source?.NewField == null)
{
ctx._source.hf.put('NewField', 'Value');
}
""",
"lang": "painless"
},
"query": {
"terms": {
"_id": [
1 (Replace with Document ID)
]
}
}
}
【讨论】:
您也可以使用批量更新来部分更新多个文档
POST /foo_v1/_bulk?pretty=true&error_trace=true
{"update":{"_index":"foo_v1","_type":"footype","_id":"397"}}
{"doc":{"Name":"foo","EmailId":"foo@test.com"}}
{"update":{"_index":"foo_v1","_type":"footype","_id":"398"}}
{"doc":{"Name":"foo1","EmailId":"foo1@test.com"}}
如果您不确定它是像 Upsert 这样的更新还是插入,那么您可以这样做:
POST /foo_v1/_bulk?pretty=true&error_trace=true
{"update":{"_index":"foo_v1","_type":"footype","_id":"397"}}
{"doc":{"Name":"foo","EmailId":"foo@test.com"}, "doc_as_upsert" : true}
使用 "doc_as_upsert" : true
【讨论】:
试试这个
curl -XPOST --header 'Content-Type: application/json' https://search-testarticle-2cwv6oh7wtz3hxowgxv3rprnsa.ap-south-1.es.amazonaws.com/test/_update/4gI4knQB7d5sAgV24YPy -d '{
"doc": { "name" : "Ankit Singh Raj" }
}'
【讨论】:
通过查询 API 更新
更新与指定查询匹配的文档。如果未指定查询,则在不修改源的情况下对数据流或索引中的每个文档执行更新,这对于获取映射更改很有用。
POST http://localhost:9200/INDEX_NAME/_update_by_query
{
"script": {
"source": "ctx._source.userName=new_user_name",
"lang": "painless"
},
"query": {
"term": {
"userName": "old_user_name"
}
}
}
在上面的示例中,userName 字段值将更新为 new_user_name
【讨论】:
让POST 呼叫{{host}}/{{index}}/_doc/{{id}}/_update
主体为
{
"doc": {
"field": "value"
}
}
输出类似于
{
"_index": "{{index}}",
"_type": "_doc",
"_id": "{{id}}",
"_version": 3,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 27,
"_primary_term": 2
}
【讨论】: