索引复杂的数组结构

时间:2014-11-18 06:52:26

标签: json elasticsearch

我有一些json(下面)我需要在elasticsearch中编制索引:

{
  "array": [
      "item1",
      {
        "name": "item2"
      }
    ]
}

当我尝试索引这种类型的json结构时,我收到一个错误:

{
   "error": "MapperParsingException[failed to parse [array]]; nested: ElasticsearchIllegalArgumentException[unknown property [name]]; ",
   "status": 400
}

现在我明白弹性搜索会变得混乱,因为数组包含第1项的stings类型,然后是item2的对象。

我的问题是,如何定义处理此类数据的映射?

1 个答案:

答案 0 :(得分:1)

这可行的唯一方法是define your index mapping so that the array field is not enabled,因此无法搜索(Elasticsearch避免解析该字段)。

curl -XPUT localhost:9200/your-index -d '{
  "mappings": {
    "your-type" : {
      "properties" : {
        "array" : {
          "type" : "object",
          "enabled" : false
        }
      }
    }
  }
}'

你必须这样做是因为Elasticsearch会根据它看到的内容动态映射类型(如果你不告诉它的映射)。第一个元素将在您的示例中成为一个字符串,因此它会将array映射到一个字符串。当它然后击中对象时,它不知道该怎么做,所以它必须停止。

这并不像听起来那么无用,因为您仍然可以从文档array中检索_source的值(假设它已存储,它是默认的)。但是,它确实意味着array中的信息不能在Elasticsearch中搜索。您可以通过搜索获取请求来获取_source

正如安德烈所评论的那样,你可能会因拥有一个更干净的物体而受益,但有时这就是它的方式。