温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

elasticsearch如何设计映射

发布时间:2026-10-29 09:14:25 来源:亿速云 阅读:86 作者:小樊 栏目:软件技术

在 Elasticsearch 中,**映射(Mapping)**决定了索引中字段的类型、如何被索引和分析,以及如何被搜索和聚合。设计良好的映射对性能、存储和查询效果都非常重要。

下面从 设计原则 → 字段类型选择 → 常见设计模式 → 示例 → 最佳实践 系统讲一下。


一、Mapping 设计的核心原则

1. 明确字段类型,避免动态映射滥用

  • 动态映射(dynamic mapping)方便但不可控
  • 生产环境建议 显式定义 mapping
  • 对不需要搜索的字段关闭索引
"dynamic": "strict"  // 或 false

2. 只索引需要搜索的字段

  • index: false 可节省空间和写入性能
  • 如:日志原始内容、调试信息

3. 合理选择 analyzer

  • 中文:ik_max_word / ik_smart
  • 英文:standard / english
  • 不分词:keyword

4. 避免字段爆炸(Field Explosion)

  • 动态嵌套对象 + 高基数 key 会拖垮集群
  • 用 flattened 或 object + keyword

二、常用字段类型与设计建议

1. text vs keyword

类型 用途 是否分词
text 全文检索 ✅
keyword 精确匹配、聚合 ❌

✅ 常见写法(一个字段两种用途):

"name": {
  "type": "text",
  "fields": {
    "keyword": {
      "type": "keyword"
    }
  }
}

2. 数值类型

  • integer / long / float / double / scaled_float
  • 能用小的就用小的(节省空间)
"price": {
  "type": "scaled_float",
  "scaling_factor": 100
}

3. 日期类型

"created_at": {
  "type": "date",
  "format": "yyyy-MM-dd HH:mm:ss||epoch_millis"
}

4. 布尔

"is_deleted": {
  "type": "boolean"
}

5. 数组

ES 中字段天然支持数组,无需特殊类型:

"tags": ["es", "search"]

6. 对象与嵌套

object(默认,扁平化)

"user": {
  "properties": {
    "name": { "type": "keyword" },
    "age": { "type": "integer" }
  }
}

nested(避免数组对象交叉匹配)

"orders": {
  "type": "nested",
  "properties": {
    "product": { "type": "keyword" },
    "count": { "type": "integer" }
  }
}

7. 不需要搜索的字段

"raw_data": {
  "type": "text",
  "index": false
}

三、典型场景 Mapping 示例

1. 日志类(写入多、查询少)

{
  "mappings": {
    "dynamic": "false",
    "properties": {
      "timestamp": { "type": "date" },
      "level": { "type": "keyword" },
      "message": { "type": "text", "index": false },
      "service": { "type": "keyword" }
    }
  }
}

2. 商品搜索

{
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "title.keyword": {
        "type": "keyword"
      },
      "price": { "type": "scaled_float", "scaling_factor": 100 },
      "category": { "type": "keyword" },
      "tags": { "type": "keyword" }
    }
  }
}

3. 用户行为(高基数)

{
  "mappings": {
    "properties": {
      "user_id": { "type": "keyword" },
      "event": { "type": "keyword" },
      "props": { "type": "flattened" }
    }
  }
}

四、Mapping 设计最佳实践

✅ 生产环境

  • 使用 Put Mapping 显式定义
  • 关闭 dynamic 或设为 strict
  • 使用 keyword 做聚合
  • 使用 nested 处理对象数组

✅ 性能优化

  • 不需要搜索的字段 index: false
  • 不需要返回的字段 enabled: false
  • 大文本考虑 _source: false

✅ Schema 演进

  • ES 不支持修改字段类型
  • 只能:
    • 新增字段
    • Reindex 到新索引

五、总结一句话

Elasticsearch Mapping 设计的核心是:明确字段用途、减少不必要索引、合理分词、避免动态失控。

如果你有具体业务(如日志 / 搜索 / 时序 / 电商),我可以帮你直接设计一份可用 Mapping。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手