# _uid field

原文链接 : [https://www.elastic.co/guide/en/elasticsearch/reference/5.3/mapping-uid-field.html](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/mapping-uid-field.html)

译文链接 : [http://www.apache.wiki/display/Elasticsearch/_uid+field](http://www.apache.wiki/display/Elasticsearch/_uid+field)

贡献者 : [朱彦安](/display/~zhuyanan)，[ApacheCN](/display/~apachecn)，[Apache中文网](/display/~apachechina)

每个索引的文档都与一个 **[_type](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/mapping-type-field.html)**（请参见“**[Mapping Types](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/mapping.html#mapping-type)[edit](https://github.com/elastic/elasticsearch/edit/5.3/docs/reference/mapping.asciidoc)**”一节）和一个 **[_id](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/mapping-id-field.html) **相关联。

这些值组合为 **{type}＃{id} **并作为 **_uid **字段编入索引。

该 **_uid**字段的值可以在 **queries**（查询），**aggregations**（聚合），**scripts**（脚本）以及 **sorting**（排序）时访问 : 

```
# Example documents
curl -XPUT 'localhost:9200/my_index/my_type/1?pretty' -H 'Content-Type: application/json' -d'
{
  "text": "Document with ID 1"
}
'
curl -XPUT 'localhost:9200/my_index/my_type/2?refresh=true&pretty' -H 'Content-Type: application/json' -d'
{
  "text": "Document with ID 2"
}
'
curl -XGET 'localhost:9200/my_index/_search?pretty' -H 'Content-Type: application/json' -d'
{
  "query": {
    "terms": {
      "_uid": [ "my_type#1", "my_type#2" ] # 1
    }
  },
  "aggs": {
    "UIDs": {
      "terms": {
        "field": "_uid", # 2
        "size": 10
      }
    }
  },
  "sort": [
    {
      "_uid": { # 3
        "order": "desc"
      }
    }
  ],
  "script_fields": {
    "UID": {
      "script": {
         "lang": "painless",
         "inline": "doc['_uid']" # 4
      }
    }
  }
}
'
```

| 1 | 在 **_uid** 字段上查询 (也可以参考 **[ids query](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/query-dsl-ids-query.html)**) |
| 2 | 在 **_uid** 字段上聚合 |
| 3 | 在 **_uid** 字段上排序 |
| 4 | 在脚本中访问 **_uid** 字段 |