在 Elasticsearch 中,映射(Mapping) 用来定义索引中字段的类型、如何存储以及如何被搜索。可以理解为 索引的“表结构定义”,类似于关系型数据库中的 schema。
映射主要解决以下问题:
_source)一个映射通常包含:
{
"mappings": {
"properties": {
"title": {
"type": "text"
},
"price": {
"type": "double"
},
"created_at": {
"type": "date"
}
}
}
}
| 类型 | 说明 |
|---|---|
text |
全文搜索字段(会分词) |
keyword |
精确值(不分词,适合聚合、排序) |
integer / long |
数字 |
float / double |
浮点数 |
boolean |
布尔 |
date |
日期 |
object |
嵌套对象 |
nested |
嵌套文档 |
如果你不提前定义映射,Elasticsearch 会在写入数据时自动推断字段类型:
PUT /products/_doc/1
{
"name": "手机",
"price": 1999
}
自动推断结果类似:
{
"name": { "type": "text" },
"price": { "type": "long" }
}
⚠️ 动态映射可能导致字段类型不符合预期,生产环境建议显式定义映射。
"title": {
"type": "text"
}
"status": {
"type": "keyword"
}
✅ 常见做法:一个字段同时支持两种用途
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
}
GET /index_name/_mapping
⚠️ 已有字段的映射不能直接修改
可以:
PUT /new_index
{
"mappings": {}
}
POST /_reindex
{
"source": { "index": "old_index" },
"dest": { "index": "new_index" }
}
| Elasticsearch | 关系型数据库 |
|---|---|
| Index | Table |
| Mapping | Schema |
| Document | Row |
| Field | Column |
Elasticsearch 映射(Mapping)用于定义索引中字段的数据类型、索引方式和搜索行为,是控制数据如何被存储和查询的重要配置。
如果你愿意,我可以:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。