elasticsearch添加字段数据类型

本文详细介绍了Elasticsearch中如何为索引设置映射,包括`mediaTag`字段的文本分析配置以及在ES7之后的`social_post_info_facebook`索引中`userName`字段的关键词类型。此外,还展示了动态模板的使用,如何针对以`Date`结尾的字段设定日期格式,并默认将其他字符串字段设为关键词类型。这些配置对于有效管理和检索信息至关重要。

PUT /es_medias/_mapping/esmedias
{
  "properties": {
    "mediaTag": {
      "type": "text",
      "analyzer": "ik_max_word",
      "search_analyzer": "ik_smart"
    }
  }
}

es7之后

PUT /social_post_info_facebook/_mapping
{
  "properties": {
    "userName": {
      "type": "keyword"
    }
  }
}

 

动态index新增字段的默认数据类型

PUT /es_medias/_mapping/esmedias
{
  "dynamic_templates": [
    {
      "date_default": {
        "match": "*Date",
        "match_mapping_type": "string",
        "mapping": {
          "type": "date",
          "format": "yyyy-MM-dd HH:mm:ss"
        }
      }
    },
     {
      "notanalyzeds": {
        "match": "*",
        "match_mapping_type": "string",
        "mapping": {
          "type": "keyword"
        }
      }
    }
  ]
}

Elasticsearch 中,添加字段并为其设置默认值并不是直接支持的功能,因为 Elasticsearch 是一个 **schema-less** 的分布式搜索引擎,它允许动态地添加字段。不过,可以通过定义 **mapping** 或使用 **ingest pipeline** 来实现类似“默认值”的行为。 ### 使用 Mapping 设置默认值 在创建索引时,可以定义字段的 mapping,并通过 `null_value` 参数为字段设置默认值。此方法适用于希望在字段缺失或为 `null` 时提供一个默认值的场景。 例如,定义一个字段 `status`,当其值为 `null` 时,默认值为 `"active"`: ```json PUT /users { "mappings": { "properties": { "status": { "type": "keyword", "null_value": "active" } } } } ``` 在插入文档时,如果 `status` 字段为 `null`,Elasticsearch 将自动将其替换为 `"active"`: ```json POST /users/_doc/1 { "status": null } ``` 查询时,该字段将显示为 `"active"` [^1]。 ### 使用 Ingest Pipeline 设置默认值 另一种更灵活的方式是使用 **ingest pipeline**。通过定义一个处理器(processor),可以在文档被索入前检查字段是否存在,并在必要时设置默认值。 以下是一个使用 `script` 处理器为字段 `status` 添加默认值的示例: ```json PUT _ingest/pipeline/set_default_status { "description": "Set default status if missing", "processors": [ { "script": { "source": """ if (ctx._source.status == null) { ctx._source.status = 'active'; } """ } } ] } ``` 在插入文档时指定该 pipeline: ```json POST /users/_doc?pipeline=set_default_status { "name": "Alice" } ``` 此时,即使未显式提供 `status` 字段,也会自动设置为 `"active"` [^2]。 ### 动态字段映射与默认行为 如果未显式定义 mapping,Elasticsearch 会根据插入的文档自动推断字段类型。然而,这种方式无法设置默认值,因此建议在生产环境中始终使用显式 mapping 来确保数据一致性。 ### 示例代码:使用 Python 添加字段并设置默认值 以下是一个使用 Python 和 `elasticsearch-py` 客户端创建索引并设置默认值的示例: ```python from elasticsearch import Elasticsearch es = Elasticsearch() # 创建索引并定义 mapping es.indices.create(index="users", body={ "mappings": { "properties": { "status": { "type": "keyword", "null_value": "active" } } } }) # 插入文档 es.index(index="users", id=1, body={"status": None}) ``` ### 注意事项 - `null_value` 仅在字段值为 `null` 时生效,不能用于处理字段缺失的情况。 - 如果希望在字段缺失时设置默认值,推荐使用 **ingest pipeline**。 - 使用 `null_value` 时,该字段的类型必须为 `keyword` 或 `text`,不支持数值类型。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值