【Elasitcsearch 开发笔记】

182 阅读2分钟

索引模板的使用

为了防止同一个索引中的商品数据越来越多,我们根据数据的时间维度把商品索引进行分月处理,分月后索引的名称为 product_info_yyyyMM,然后在将所有的分月索引用 all_product_info 作为别名。再插入新一月的数据时,我们总是将创建索引的语句以及起别名的语句嵌入到我们的代码里,然而这些创建语句只需要执行一次,这样会导致代码的臃肿,这时我们就会用到索引模板。

索引模板

创建索引模板

PUT _template/product_info_month_template
{
  "order": 0,
  "index_patterns": [
    "product_info_*"
  ],
  "mappings": {
    "properties": {
      "annual_rate" : {
          "type" : "keyword"
       },
       "describe" : {
         "type" : "text"
       },
       "productName" : {
         "type" : "text"
       }
    }
  },
  "settings": {
    "index": {
      "number_of_shards": "1",
      "number_of_replicas": "1"
    }
  },
  "aliases": {
    "lwt_douyin_video": {}
  }
}

reindex 流程

# 使用 product_info_month_template 创建一个新的索引 product_info_202205_v2,保证和其他月份的索引配置一样。
PUT product_info_202205_v2

# 删除 product_info_202205_v2 的别名,不要被 all_product_info 检索到,如果不删除会导致数据重复
POST _aliases
{
  "actions": [
    {
      "remove": {
        "index": "product_info_202205_v2",
        "alias": "all_product_info"
      }
    }
  ]
}
# 迁移数据
POST _reindex
{
  "source": {
    "index": "product_info_202205"
  },
  "dest": {
    "index": "product_info_202205_v2"
  }
}
# 删除 product_info_202205 的别名,添加 product_info_202205_v2 的别名 all_product_info, product_info_202205 
# 这样 product_info_202205_v2 就代替了之前的 product_info_202205 而不用改代码
POST _aliases
{
  "actions": [
    {
      "remove": {
        "index": "product_info_202205",
        "alias": "all_product_info"
      },
      "add": {
        "index": "product_info_202205_v2",
        "alias": "all_product_info"
      }
    }
  ]
}

# 至此 product_info_202205 reindex 完成,可以选择保留或者删除。删除后修改 product_info_202205_v2 的别名
POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "product_info_202205_v2",
        "alias": "product_info_202205"
      }
    }
  ]
}

reindex 修改字段名、删除原index中字段等


POST _reindex
{
  "source": {
    "index": "product_info_202205"
  },
  "dest": {
    "index": "product_info_202205_v2"
  },
  "script": {
    "source": "ctx._id = ctx._source.product_id;ctx._source.remove("@version");ctx._source.remove("@timestamp");"
  }
}