类型内的弹性搜索文档是否必须具有相同的字段结构

Do elasticsearch documents within a type have to have the same field structure

我正在研究 elasticsearch 指南中的示例。对于具有如下对象的类型:

{
               "first_name":  "John",
               "last_name":   "Smith",
               "age":         25,
               "about":       "I love to go rock climbing",
               "interests": [ "sports", "music" ]
            }

我可以索引这样的对象吗:

{ "middle_name": "lee", "age": 36 }

所以它缺少字段,并且一个额外的字段不在另一个字段中。

是否所有这些字段都已编入索引?或者每个文档是否必须具有相同的结构。

缺少字段不会造成问题。但是额外的字段可能会根据您在 dynamic mapping 属性.

中的设置创建

引用文档。

Fortunately, you can control this behavior with the dynamic setting, which accepts the following options:

true Add new fields dynamically—the default

false Ignore new fields

strict Throw an exception if an unknown field is encountered

Elasticsearch 默认使用 dynamic mapping,这意味着它第一次看到新字段时会为其创建一个映射。

在你的例子中,字段 middle_name 是新的,所以 Elasticsearch 会自动为你创建一个映射:

{
"middle_name": {
  "type":"string"
  }
}

所以是的,额外的字段将被索引。并非所有文档都必须具有所有字段。

但是,所有文档中的所有相同字段必须具有相同类型。也就是说,如果您尝试索引文档 {"age":26},然后索引文档 {"age":"old"},您将得到一个错误,因为在第一种情况下字段是数字,在第二种情况下是字符串:

{
   "error": "MapperParsingException[failed to parse [age]]; nested: NumberFormatException[For input string: \"adsf\"]; ",
   "status": 400
}

所有这些都可以通过玩 Marvel Sense 轻松尝试。通过 运行ning bin/plugin -i elasticsearch/marvel/latest 在您的 Elasticsearch 文件夹中安装它,然后转到 http://localhost:9200/_plugin/marvel/sense/index.html 并尝试 运行 以下命令自己尝试:

put typetest
put typetest/doc/2
{
  "age":25
}
put typetest/doc/2
{
  "age":"old"
}