赞
踩
在Elasticsearch中,映射(mapping)是用于定义索引中字段(field)的结构和行为的重要组成部分。映射决定了如何分析文本、如何存储数值、日期以及其他复杂类型的数据。下面是一些实战中配置Elasticsearch映射的基本步骤和要点:
理解字段类型:
string
(text
和 keyword
)、numeric
(整数、浮点数)、boolean
、date
、object
、nested
、geo_point
、geo_shape
等。决定是否启用动态映射:
dynamic: true
- 自动添加新字段并根据内容推断类型。dynamic: false
- 忽略新字段,需要手动定义所有映射。dynamic: strict
- 当遇到未定义的新字段时,拒绝索引文档。PUT /my_index { "mappings": { "properties": { "title": { "type": "text", "analyzer": "standard" }, "content": { "type": "text", "fields": { "keyword": { "type": "keyword" } } }, "author": { "type": "keyword" }, "post_date": { "type": "date", "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis" }, "tags": { "type": "nested", "properties": { "name": { "type": "text" }, "category": { "type": "keyword" } } } } } }
my_index
的索引,并定义了其映射结构。title
字段被定义为text
类型,并使用标准分析器。content
字段包含一个子字段keyword
以支持全文搜索和精确匹配。author
字段作为keyword
处理,便于排序或聚合操作。post_date
是一个日期类型,指定了多种格式以便解析不同格式的日期字符串。tags
是一个嵌套(nested)对象,它内部有自己的属性映射。若要调整动态映射的行为,可以在索引级别或字段级别指定动态映射规则:
PUT /my_index
{
"mappings": {
"dynamic": "strict", // 或 "false"
"properties": {
"custom_field": {
"type": "text",
"dynamic": "true" // 即使全局动态映射关闭,此字段仍允许动态添加
}
}
}
}
如果你使用的是像Nest这样的客户端库,可以通过编写类映射(Poco Mapping)的方式来声明索引的映射结构,并通过客户端API将其发送到Elasticsearch服务器上创建或更新映射。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。