空值
通过 null_value
映射参数,您可以在索引期间将显式 null
值替换为预定义的值。默认情况下,如果字段设置为 null
,则不会对其进行索引,也无法搜索。如果定义了 null_value
,则将索引指定的替换值。这允许您查询或聚合原始字段为 null
的文档,而无需修改文档的 _source
。
null_value
必须与应用它的字段类型相同。例如,date
字段不能使用 boolean
类型的值(如 true
)作为其 null_value
;null_value
必须是有效的日期字符串。
在字段上设置 null_value
以下请求创建一个名为 products
的索引。category
字段的类型为 keyword
,并在索引期间将 null
值替换为 "unknown"
PUT /products
{
"mappings": {
"properties": {
"category": {
"type": "keyword",
"null_value": "unknown"
}
}
}
}
索引带有空值的文档
使用以下命令索引 category
字段设置为 null
的文档
PUT /products/_doc/1
{
"category": null
}
查询空值替代项
使用以下命令搜索 category
字段之前为 null
的文档
POST /products/_search
{
"query": {
"term": {
"category": "unknown"
}
}
}
响应包含匹配的文档
{
...
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.2876821,
"hits": [
{
"_index": "products",
"_id": "1",
"_score": 0.2876821,
"_source": {
"category": null
}
}
]
}
}
对空值替代项进行聚合
由于空值替代项已被索引,它也会出现在聚合中。使用以下命令对 category
字段执行 terms
聚合
POST /products/_search
{
"size": 0,
"aggs": {
"category_count": {
"terms": {
"field": "category"
}
}
}
}
响应包含聚合结果
{
...
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"aggregations": {
"category_count": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "unknown",
"doc_count": 1
}
]
}
}
}