设计 Elasticsearch 的映射(Mapping)字段,核心目标是:贴合业务查询场景、控制存储成本、避免性能坑。下面我从「设计思路 → 字段类型选择 → 常见场景示例 → 最佳实践」一步一步讲。
Mapping 用来定义:
⚠️ Elasticsearch 写入数据后,部分 Mapping 不能修改(如类型变更),所以一开始就设计好很重要。
不要从数据库表结构直接照搬。
问自己:
text"title": {
"type": "text",
"analyzer": "ik_max_word"
}
keyword"status": {
"type": "keyword"
}
multi-fields(非常推荐)一个字段同时支持:
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
}
查询:
name → 模糊搜索name.keyword → 排序 / 聚合| 场景 | 类型 |
|---|---|
| 标题、内容 | text |
| ID、状态码 | keyword |
| 时间 | date |
| 数量、价格 | integer / long / scaled_float |
| 是否 | boolean |
| 经纬度 | geo_point |
| 对象 | object / nested |
| IP | ip |
PUT /products
{
"mappings": {
"properties": {
"id": { "type": "keyword" },
"title": {
"type": "text",
"analyzer": "ik_max_word",
"fields": {
"keyword": { "type": "keyword" }
}
},
"price": { "type": "scaled_float", "scaling_factor": 100 },
"status": { "type": "keyword" },
"tags": { "type": "keyword" },
"create_time": { "type": "date" },
"location": { "type": "geo_point" }
}
}
}
"remark": {
"type": "text",
"index": false
}
ES 默认 _source 已包含全部字段,一般不用 store: true
"tags": ["a", "b"]
直接 keyword 即可
nested普通 object 会“扁平化”,导致查询错误
"comments": {
"type": "nested",
"properties": {
"user": { "type": "keyword" },
"content": { "type": "text" }
}
}
默认 ES 会自动推断类型,容易出问题。
✅ 建议:
"dynamic": "strict"
或
"dynamic": "false"
如果你愿意,可以告诉我:
我可以直接帮你设计一份“可用、可扩展”的 Elasticsearch Mapping。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。