10

I am trying to to create a mapping that will allow me to have a document looking like this:

{
    "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"
    }
]

}

And the attributes array must be of type nested, and dynamic, so i can add more objects to the array and index it by the field_type value.

Is this even possible?

I have been looking at the dynamic_templates. Can i use that?

4

2 回答 2

19

如果您愿意查询特定的字段类型,如果您想要执行特定类型的查询(如比较),您实际上可以使用多字段映射和参数将多个数据类型索引到同一字段中。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
            }
          }
        }
      }
    }
  }
}

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

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
}

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

// 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"
      }
    }
  }
}

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

于 2018-11-30T15:59:12.400 回答
5

否 - 对于同一类型中的同一字段,您不能有不同的数据类型。

例如,该字段index/type/value不能既是字符串又是日期。


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

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

但这对您的方案没有帮助,一旦设置了数据类型,您就无法更改它。

于 2014-11-14T14:47:19.380 回答