一尘不染

在Elasticsearch中重命名字段

elasticsearch

我有这样的文件

{
    "_index": "testindex",
    "_type": "logs",
    "_id": "1",
    "_score": 1,
    "_source": {
      "field1": "data1",
      "field2": "data2"
    }
}

我需要更改field2Request.field3

{
    "_index": "testindex",
    "_type": "logs",
    "_id": "1",
    "_score": 1,
    "_source": {
      "field1": "data1",
      "Request": {
        "field3": "data2"
      }
    }
}

为此,首先将字段映射添加到现有索引

PUT testindex/_mapping/logs
{
    "properties": 
    { 
        "Request": 
        {
            "properties": 
            {
                "field3" : 
                {
                    "type": "string"
                }
            }
        }   
    }  
}

然后尝试重新索引

POST _reindex
{
    "source": {
        "index": "testindex"
    },
    "dest": {
        "index": "testindex1"
    },
    "script": {
        "inline": "ctx._source.Request.field3 = ctx._source.remove(\"field2\")"
    }
}

错误是

"reason": "failed to run inline script [ctx._source.Request.field3 = ctx._source.remove(\"field2\")] using lang [groovy]",
"caused_by": {
    "type": "null_pointer_exception",
    "reason": "Cannot set property 'field3' on null object"
}

阅读 2632

收藏
2020-06-22

共1个答案

一尘不染

Request字段在您的文档中尚不存在,因此您的脚本需要首先创建它:

POST _reindex
{
    "source": {
        "index": "testindex"
    },
    "dest": {
        "index": "testindex1"
    },
    "script": {
        "inline": "ctx._source.Request = [:]; ctx._source.Request.field3 = ctx._source.remove(\"field2\") ]"
    }
}

或更短一些:

POST _reindex
{
    "source": {
        "index": "testindex"
    },
    "dest": {
        "index": "testindex1"
    },
    "script": {
        "inline": "ctx._source.Request = [field3: ctx._source.remove(\"field2\") ]"
    }
}
2020-06-22