Elasticsearch映射-同一字段中的不同数据类型

Mor*_*erg 5 elasticsearch elasticsearch-mapping

我正在尝试创建一个映射,使我可以拥有一个如下所示的文档:

{
    "created_at" : "2014-11-13T07:51:17+0000",
    "updated_at" : "2014-11-14T12:31:17+0000",
    "account_id" : 42,
    "attributes" : [
    {
        "name" : "firstname",
        "value" : "Morten",
        "field_type" : "string"
    },
    {
        "name" : "lastname",
        "value" : "Hauberg",
        "field_type" : "string"
    },
    {
        "name" : "dob",
        "value" : "1987-02-17T00:00:00+0000",
        "field_type" : "datetime"
    }
]
Run Code Online (Sandbox Code Playgroud)

}

而且attributes数组必须是嵌套的并且是动态的类型,因此我可以向数组中添加更多对象,并根据该field_type值对其进行索引。

这有可能吗?

我一直在看dynamic_templates。我可以使用吗?

小智 16

您实际上可以使用多字段映射和ignore_malformed参数将多个数据类型索引到同一字段中,如果您愿意查询特定的字段类型,如果您想进行特定类型的查询(如比较)。

这将允许 elasticsearch 填充与每个输入相关的字段,并忽略其他字段。这也意味着您不需要在索引代码中做任何事情来处理不同的类型。

例如,对于名为 user_input 的字段,您希望能够对用户输入的内容进行日期或整数范围查询,或者在用户输入字符串时进行常规文本搜索,您可以执行以下操作下列的:

PUT multiple_datatypes
{
  "mappings": {
    "_doc": {
      "properties": {
        "user_input": {
          "type": "text",
          "fields": {
            "numeric": {
              "type": "double",
              "ignore_malformed": true
            },
            "date": {
              "type": "date",
              "ignore_malformed": true
            }
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以添加一些具有不同用户输入的文档:

PUT multiple_datatypes/_doc/1
{
  "user_input": "hello"
}

PUT multiple_datatypes/_doc/2
{
  "user_input": "2017-02-12"
}

PUT multiple_datatypes/_doc/3
{
  "user_input": 5
}
Run Code Online (Sandbox Code Playgroud)

当您搜索这些时,范围和其他特定于类型的查询按预期工作:

// Returns only document 2
GET multiple_datatypes/_search
{
  "query": {
    "range": {
      "user_input.date": {
        "gte": "2017-01-01"
      }
    }
  }
}

// Returns only document 3
GET multiple_datatypes/_search
{
  "query": {
    "range": {
      "user_input.numeric": {
        "lte": 9
      }
    }
  }
}

// Returns only document 1
GET multiple_datatypes/_search
{
  "query": {
    "term": {
      "user_input": {
        "value": "hello"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我在这里写了一篇博客文章

  • 这在索引单个值时很有用,但不适用于至少其中一个不可转换的多值。示例:`PUT multiple_datatypes/_doc/2 { "user_input": ["hello", "2017-02-12"] }`。即使在索引级别设置“ignore_malformed=true”也无济于事。我认为这是elasticsearch的一个问题。 (2认同)

Oll*_*ank 5

否-同一类型内的同一字段不能有不同的数据类型。

例如,该字段index/type/value不能同时是字符串和日期。


甲动态模板可以用于设置数据类型和分析器基于字段名称的格式

例如:将所有字段名称以“ _dt”结尾的字段设置为datetime。

但这对您的情况无济于事,一旦设置了数据类型,就无法更改它。