属性
的 properties
映射参数用于定义对象内或文档根部字段的结构和数据类型。它作为任何映射定义的核心,允许您显式指定字段名称、类型(如 text
、keyword
、date
或 float
),以及每个字段的附加设置或映射参数。
通过使用 properties
,您可以完全控制数据的索引和存储方式,从而实现精确的搜索行为、聚合支持和数据验证。
使用属性定义字段
以下请求使用 properties
参数创建一个名为 products
的索引,并带有结构化映射。它包含一个名为 dimensions
的嵌套对象字段,该字段带有子字段
PUT /products
{
"mappings": {
"properties": {
"name": {
"type": "text"
},
"sku": {
"type": "keyword"
},
"price": {
"type": "float"
},
"available": {
"type": "boolean"
},
"created_at": {
"type": "date",
"format": "yyyy-MM-dd"
},
"dimensions": {
"type": "object",
"properties": {
"width": { "type": "float" },
"height": { "type": "float" },
"depth": { "type": "float" }
}
}
}
}
}
索引文档
使用以下命令索引包含 嵌套字段 的文档
PUT /products/_doc/1
{
"name": "Wireless Mouse",
"sku": "WM-1001",
"price": 24.99,
"available": true,
"created_at": "2024-12-01",
"dimensions": {
"width": 6.5,
"height": 3.2,
"depth": 1.5
}
}
使用点表示法进行查询和聚合
您可以使用点表示法对对象子字段进行查询或聚合。使用以下命令执行查询:
- 过滤
dimensions.width
字段上的文档,返回width
在5
到10
之间的文档。 - 在
dimensions.depth
字段上创建 直方图聚合,使用0.5
的depth
间隔为产品创建桶。
POST /products/_search
{
"query": {
"range": {
"dimensions.width": {
"gte": 5,
"lte": 10
}
}
},
"aggs": {
"Depth Distribution": {
"histogram": {
"field": "dimensions.depth",
"interval": 0.5
}
}
}
}
以下响应显示了 dimensions.width
字段在指定范围内的匹配文档。它还包括 dimensions.depth
的直方图聚合结果。
{
...
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "products",
"_id": "1",
"_score": 1,
"_source": {
"name": "Wireless Mouse",
"sku": "WM-1001",
"price": 24.99,
"available": true,
"created_at": "2024-12-01",
"dimensions": {
"width": 6.5,
"height": 3.2,
"depth": 1.5
}
}
}
]
},
"aggregations": {
"Depth Distribution": {
"buckets": [
{
"key": 1.5,
"doc_count": 1
}
]
}
}
}