# null\_value（空值）

**null** 值不能被索引或者搜索.当一个字段被设置成 **null**（或者一个空数组,或者值全为 **null** 的数组）时， 该字段将被视为没有值。

**null\_value** 参数允许你用一个特殊的值替换一个显示的 **null** 值， 以确保这个字段能被索引和搜索。例如：

```
curl -XPUT 'localhost:9200/my_index?pretty' -H 'Content-Type: application/json' -d'
{
  "mappings": {
    "my_type": {
      "properties": {
        "status_code": {
          "type":       "keyword",
          "null_value": "NULL" #1
        }
      }
    }
  }
}
'
curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d'
{
  "status_code": null
}
'
curl -XPUT 'localhost:9200/my_index/my_type/2?pretty' -H 'Content-Type: application/json' -d'
{
  "status_code": [] #2
}
'
curl -XGET 'localhost:9200/my_index/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": {
    "term": {
      "status_code": "NULL" #3
    }
  }
}
'
```

| 1 | 用**NULL**代替显示的**null**值。                  |
| - | ----------------------------------------- |
| 2 | 没有显示的包含**null**的空数组，不会被**null\_value**替换。 |
| 3 | 搜索**NULL**将返回文档1，而不会返回文档2。                |

> 重点
>
> **null\_value**必须设置成相同类型的参数。例如，一个**long**型的字段不能被设置成**string**类型的**null\_value**。

## 解析:

null值比较特殊,传统的方式,无法搜索会报错

如下

```
PUT /my_index
{
  "mappings": {
    "my_type": {
      "properties": {
        "status_code": {
          "type": "keyword"
        }
      }
    }
  }
}

PUT /my_index/my_type/1
{
  "status_code": null
}

GET /my_index/_search
{
  "query": {
    "term": {
      "status_code": null
    }
  }
}
```

查询报错

```
{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "field name is null or empty"
      }
    ],
    "type": "illegal_argument_exception",
    "reason": "field name is null or empty"
  },
  "status": 400
}
```

所以为了解决这个问题,采用一个值来替换null值的情况. 如开始时候的例子,采用"NULL" 字符串采替换null值的情况进行搜索.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/elasticsearch/ji-chu/mapping/323mapping-parametersff08-ying-she-can-shu-ff09/nullvalue-ff08-kong-zhi-ff09.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
