映射用例
映射控制着数据的索引和查询方式,从而针对各种用例实现优化的性能和高效的存储。
示例:忽略格式错误的 IP 地址
以下示例展示了如何创建映射,以指定 OpenSearch 应忽略任何包含不符合 ip
数据类型的格式错误的 IP 地址的文档。您可以通过将 ignore_malformed
参数设置为 true
来实现此目的。
创建一个带有 ip
映射的索引
要创建一个带有 ip
映射的索引,请使用 PUT 请求
PUT /test-index
{
"mappings" : {
"properties" : {
"ip_address" : {
"type" : "ip",
"ignore_malformed": true
}
}
}
}
然后添加一个带有格式错误 IP 地址的文档
PUT /test-index/_doc/1
{
"ip_address" : "malformed ip address"
}
当您查询索引时,ip_address
字段将被忽略。您可以使用以下请求查询索引
GET /test-index/_search
响应
{
"took": 14,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "test-index",
"_id": "1",
"_score": 1,
"_ignored": [
"ip_address"
],
"_source": {
"ip_address": "malformed ip address"
}
}
]
}
}
将字符串字段映射到 text
和 keyword
类型
要创建一个名为 movies1
的索引,并使用动态模板将所有字符串字段映射到 text
和 keyword
类型,您可以使用以下请求
PUT movies1
{
"mappings": {
"dynamic_templates": [
{
"strings": {
"match_mapping_type": "string",
"mapping": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
]
}
}
此动态模板确保文档中的任何字符串字段都将同时作为全文 text
类型和 keyword
类型进行索引。