首页 > 解决方案 > 如何在 ElasticSeach 的嵌套对象中添加新字段?

问题描述

假设,我有一些预定义模式的索引,比如

     "mappings": {
          "transactions": {
            "dynamic": "strict",
            "properties": {
              
              "someDate": {
                "type": "date"
              },
              "nestedOjects": {
                "type": "nested",
                "properties": {
                  "someField": {
                    "type": "text"
                  }
              }
            }

现在我需要通过将新字段添加到嵌套对象中来更新此映射。即我想实现这样的目标:

     "mappings": {
          "transactions": {
            "dynamic": "strict",
            "properties": {
              
              "someDate": {
                "type": "date"
              },
              "nestedOjects": {
                "type": "nested",
                "properties": {
                  "someField": {
                    "type": "text"
                  },
                  "newField": {
                    "type": "text"
                  }
              }
            }

标签: elasticsearch

解决方案


假设您尚未创建任何索引。首先,我们将使用您现有的映射创建索引,如下所示(使用的索引名称demo-index):

创建索引:

PUT demo-index
{
  "mappings": {
    "dynamic": "strict",
    "properties": {
      "someDate": {
        "type": "date"
      },
      "nestedOjects": {
        "type": "nested",
        "properties": {
          "someField": {
            "type": "text"
          }
        }
      }
    }
  }
}

要查看上面创建的索引的映射,您可以点击 api:GET demo-index/_mapping

更新现有的demo-indexnewFieldnestedOjects.

更新索引映射:

PUT demo-index/_mapping
{
  "dynamic": "strict",
  "properties": {
    "someDate": {
      "type": "date"
    },
    "nestedOjects": {
      "type": "nested",
      "properties": {
        "someField": {
          "type": "text"
        },
        "newField": {
          "type": "text"
        }
      }
    }
  }
}

现在,如果您再次点击 api GET demo-index/_mapping,您将获得更新的映射。

如果您需要transactions作为头对象和其中的所有其他内容,则可以执行以下操作(在创建索引时相同):

PUT demo-index/_mapping
{
  "dynamic": "strict",
  "properties": {
    "transactions": {
      "type": "nested",
      "properties": {
        "someDate": {
          "type": "date"
        },
        "nestedOjects": {
          "type": "nested",
          "properties": {
            "someField": {
              "type": "text"
            },
            "newField": {
              "type": "text"
            }
          }
        }
      }
    }
  }
}
  1. 创建索引参考API
  2. 更新映射参考API

推荐阅读