重命名elasticsearch中的字段

时间:2016-11-15 10:22:02

标签: elasticsearch

我有这样的文件

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

我需要将field2更改为Request.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"
}

2 个答案:

答案 0 :(得分:16)

您的文档中尚不存在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\") ]"
    }
}

答案 1 :(得分:0)

重命名 字段名称的最简单方法是使用 _update_by_query API:

示例: POST http:// localhost:9200 / INDEX_NAME / _update_by_query

{
  "query": { 
    "bool": {
        "must_not": {
            "exists": {
                "field": "NEW_FIELD_NAME"
            }
        }
    }
  },
  "script" : {
    "inline": "ctx._source.NEW_FIELD_NAME = ctx._source.OLD_FIELD_NAME; ctx._source.remove(\"OLD_FIELD_NAME\");"
  }
}