关于elasticsearch:Elasticsearch修改字段类型方案

8次阅读

共计 2017 个字符,预计需要花费 6 分钟才能阅读完成。

Elasticsearch 的 mapings 相当于数据库的表构造,在应用过程中能够新增和删除字段,然而不反对批改字段类型,能够通过以下四个步骤来实现

  1. 创立新的指标 index
  2. 将源 index 的数据复制到指标 index
  3. 删除源 index
  4. 给指标 index 设置别名,别名为源 index 的名称。
    或者再建一个名称为源 index 的指标 index2, 数据从指标 index 复制到指标 index2

上面举个例子

源 index: my-index-order-1
蕴含两个字段:

  • createTime:下单工夫,类型:long
  • orderNo: 订单号,类型:text

以下操作都是在 Kinbana 的控制台中执行.

PUT /my-index-order-1?pretty
{
  "mappings": {
    "properties": {
      "createTime": {"type": "long"},
      "orderNo": {"type": "text"}
    }
  }
}

插入三条数据

PUT /my-index-order-1/_doc/1?pretty
{
  "createTime": 1637992973517,
  "orderNo": "7d7d5495-4db9-4513-a2c9-c5fb0454517e"
}
PUT /my-index-order-1/_doc/2?pretty
{
  "createTime": 1637993092000,
  "orderNo": "fb337ede-6e1d-4422-8e2b-453148064bba"
}
PUT /my-index-order-1/_doc/3?pretty
{
  "createTime": 1640585092000,
  "orderNo": "54ccb3a9-c168-487e-8594-893a2b7803bf"
}

需要剖析:把 my-index-order- 1 的 createTime 字段类型从 long 类型批改成 date 类型

1. 创立新的指标 index

PUT /my-index-order-2?pretty
{
  "mappings": {
    "properties": {
      "createTime": {"type": "date"},
      "orderNo": {"type": "text"}
    }
  }
}

2. 将源 index 的数据复制到指标 index

reindex 命令能够实现两个 index 之间数据的拷贝,

两个 index 的 mappings 不同,只会拷贝相互兼容的数据。

如果复制的数据量比拟大,_reindex 申请会超时,不要焦急,数据拷贝还在持续,
能够通过 GET _tasks?detailed=true&actions=*reindex 命令查问正在执行的工作,
GET _tasks/taskId:number查问某一个工作的执行详情。

reindex 更多参数参考官网文档:
https://www.elastic.co/guide/…

POST _reindex
{
  "source": {"index": "my-index-order-1"},
  "dest": {"index": "my-index-order-2"}
}

3. 删除源 index

DELETE /my-index-order-1/

4. 给指标 index 设置别名,别名为源 index 的名称

给 my-index-order- 2 加上 my-index-order- 1 的别名后,能够间接通过 my-index-order- 1 来操作 my-index-order-2

POST _aliases
{
  "actions":[
      {
        "add":{
          "index":"my-index-order-2",
          "alias":"my-index-order-1"
        }
      }
    ]
}

到此实现 mappings 字段类型的批改。能够欢快的对 createTime 做工夫的统计查问了

比方统计每个月的下单量:

GET /my-index-order-2/_search?pretty
{
  "size": 0,
  "aggs": {
    "orderCount": {
      "date_histogram": {
        "field": "createTime",
        "calendar_interval": "1M",
        "format": "yyyy-MM"
      }
    }
  }
}

查问后果:

{
    "took": 27,
    "timed_out": false,
    "_shards": {....},
    "hits": {....},
    "aggregations": {
        "orderCount": {
            "buckets": [
                {
                    "key_as_string": "2021-11",
                    "key": 1635724800000,
                    "doc_count": 2
                },
                {
                    "key_as_string": "2021-12",
                    "key": 1638316800000,
                    "doc_count": 1
                }
            ]
        }
    }
}

Elasticsearch 版本号:7.15.2
Kibana 版本号:7.15.2
Elasticsearch 中武官网 https://www.elastic.co/cn/

正文完
 0