> For the complete documentation index, see [llms.txt](https://xiaoxiami.gitbook.io/elasticsearch/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://xiaoxiami.gitbook.io/elasticsearch/ji-chu/33-apis/342wen-dang-apis-document-apis/huo-53d6-pi-liang-huo-53d6-3e-wen-dang.md).

# 获取/批量获取->文档

## Get API 获取文档API

**get api**允许从一个基于其id的 **index**中获取一个 JSON格式的**document**，下面的示例是从一个在名称为tweet的 **type** 下的id为1，名称为twitter的 **index** 中获取一个JSON格式的 **document**。

```
curl -XGET 'http://localhost:9200/twitter/tweet/1'
```

以上 get 操作的结果如下

```
{
    "_index" : "twitter",
    "_type" : "tweet",
    "_id" : "1",
    "_version" : 1,
    "found": true,
    "_source" : {
        "user" : "kimchy",
        "postDate" : "2009-11-15T14:12:12",
        "message" : "trying out Elasticsearch"
    }
}
```

以上结果包括 **document** 的 \_index，\_type，\_id以及\_version等我们想要检索的，包括实际的 \_source 如果它可以被发现（相应结果中的found字段）

API还可以检查**document**是否使用 HEAD，例如：

```
curl -XHEAD -i 'http://localhost:9200/twitter/tweet/1'
```

### Realtime

默认情况下，get API 是实时的，而且它不受**index**刷新频率的影响（当数据对search操作可见）。如果**document**已经修改完但没还有刷新，get API将会执行 in-place刷新操作使得**document**可见。这也会导致其他**docuemnt**发生改变。若要禁止 GET的实时操作，可以设置 **realtime**参数为false。

### Option Type

get API允许`_type 作为可选参数，设置它为_all可以从所有的匹配的type中获取第一个docuemnt。`

### Source filtering

默认情况下，get 操作返回 \_source字段的内容，除非你使用stored\_fields参数或\_source字段是禁止的。你可以使用\_source参数来关闭\_source检索。

```
curl -XGET 'http://localhost:9200/twitter/tweet/1?_source=false'
```

如果你只需要从完整的 \_source中获取一个或两个字段，你可以使用\_source\_include&`_source_exclude`参数用来包含或过滤其他部分。这个功能很有用在大文件 **document** 部分检索的时候可以节省网络开销。所有的参数可以用普通的分隔符连接或者通配符表达式。示例如下：

```
curl -XGET 'http://localhost:9200/twitter/tweet/1?_source_include=*.id&_source_exclude=entities'
```

如果你只是想要指定包含的，你可以使用比较剪短的表达式：

```
curl -XGET 'http://localhost:9200/twitter/tweet/1?_source=*.id,retweeted'
```

### Stored Fields

get 操作允许指定一系列的stored 字段，这些字段将会被返回通过传递stored\_fields参数。如果请求的字段没有被储存，将会被忽略。参考以下示例：

```
PUT twitter
{
   "mappings": {
      "tweet": {
         "properties": {
            "counter": {
               "type": "integer",
               "store": false
            },
            "tags": {
               "type": "keyword",
               "store": true
            }
         }
      }
   }
}
```

现在我们可以添加 document：

```
PUT twitter/tweet/1
{
    "counter" : 1,
    "tags" : ["red"]
}
```

1.尝试去检索：

```
GET twitter/tweet/1?stored_fields=tags,counter
```

以上get操作的结果是：

```
{
   "_index": "twitter",
   "_type": "tweet",
   "_id": "1",
   "_version": 1,
   "found": true,
   "fields": {
      "tags": [
         "red"
      ]
   }
}
```

从 **document**中获取的字段的值通常是array。由于counter字段没有存储，当尝试获取stored\_fields时get会将其忽略。

可以对元数据字段进行检索，比如\_routing和\_parent：

```
PUT twitter/tweet/2?routing=user1
{
    "counter" : 1,
    "tags" : ["white"]
}

GET twitter/tweet/2?routing=user1&stored_fields=tags,counter
```

以上get操作的结果是：

```
{
   "_index": "twitter",
   "_type": "tweet",
   "_id": "2",
   "_version": 1,
   "_routing": "user1",
   "found": true,
   "fields": {
      "tags": [
         "white"
      ]
   }
}
```

只有leaf的字段可以通过stored\_field选项返回。所以object字段无法返回并且这个请求会失败

### Generated fields

如果在索引和刷新过程中没有发生刷新操作，GET会访问transaction日志来获取 **document**。然而，一些字段只会在索引时创建。如果你尝试访问那些只有在创建索引时才会创建的字段，默认情况下会得到一个异常。你可以通过设置 **ignore\_errors\_on\_generated\_fields=true** 来忽略那些字段。

### Getting the \_source directly

使用/{index}/{type}/{id}/\_source 可以只获取 **document** 的\_source字段，不会有其他多余的内容，例如：

```
curl -XGET 'http://localhost:9200/twitter/tweet/1/_source'
```

你也可以使用过滤参数来控制\_source的哪些部分可以被返回：

```
curl -XGET 'http://localhost:9200/twitter/tweet/1/_source?_source_include=*.id&_source_exclude=entities'
```

注意，同样有一个HEAD变量来检测document \_source 是否存在。一个存在的 **document**不会有\_source，如果它在 **mapping** 里被禁止，例如：

```
curl -XHEAD -i 'http://localhost:9200/twitter/tweet/1/_source'
```

### Routing

当创建索引时想要控制路由，为了获取 **document**，routing 的值也因该提供，例如：

```
curl -XGET 'http://localhost:9200/twitter/tweet/1?routing=kimchy'
```

以上的操作会获取id为1的tweet，但是是基于用户被路由的。注意，如果没有设置正确的路由，将会导致 **document** 无法被获取。

## Preference <a href="#getapi-preference" id="getapi-preference"></a>

控制共享的副本去执行get请求的优先权。默认情况下，是在共享的副本中随机操作的。

`preference` 可以设置为：

**\_primary**

```
操作会在主要的共享副本执行。
```

**\_local**

操作会优先在本地的共享副本执行

**Custom(String)value**

自定义值会被用来保证相同的共享副本使用相同的自定义值。这个帮助 "jumping values" 当不同的共享副本在不同的refresh states。这个值类似于web session id或者user name。

## Refresh <a href="#getapi-refresh" id="getapi-refresh"></a>

refresh 参数可以设置为true，为了使其能在get操作和使其可检索前刷新相关的共享副本。将其设置为true应该要谨慎，应为这将导 致系统资源负载增大（也会减慢索引的创建）。

## Distributed <a href="#getapi-distributed" id="getapi-distributed"></a>

get操作会从一个指定的副本id得到散列值。然后会重定向到那个shard id的其中一个副本上并返回结果。副本是primary shard而且他的副本是在同一个shard id 组。这意味着副本数越多，GET的性能越好。

## Versioning support <a href="#getapi-versioningsupport" id="getapi-versioningsupport"></a>

你可以使用 version 参数去检索**document**，只有在当前的 version 和你指定的version 相同的情况下。这个特性同样适用于所有的 version types,当我们希望要检索的 **document** 的version与我们指定的version相同。

在内部，**Elasticsearch**已经标记了已经删除的旧的 **document**并且增加了新的 **document**。旧版本的 **document** 不会马上出现，并且你也不能访问。**Elasticsearch**会在后台清理已经删除的**document** 以便可以索引更多的数据。

## Multi Get API 批量获取文档API

多 GET API 允许基于索引，类型（可选）和ID（也可能路由）获取多个文档。响应包括获取的 `docs` 列表，每个文件的结构都类似于 GET API 提供文件的结构。下面是一个例子：

```
curl 'localhost:9200/_mget' -d '{
    "docs" : [
        {
            "_index" : "test",
            "_type" : "type",
            "_id" : "1"
        },
        {
            "_index" : "test",
            "_type" : "type",
            "_id" : "2"
        }
    ]
}'
```

`mget`也可以针对一个索引（在 body 体中不需要）：

```
curl 'localhost:9200/test/_mget' -d '{
    "docs" : [
        {
            "_type" : "type",
            "_id" : "1"
        },
        {
            "_type" : "type",
            "_id" : "2"
        }
    ]
}'
```

类型如下：

```
curl 'localhost:9200/test/type/_mget' -d '{
    "docs" : [
        {
            "_id" : "1"
        },
        {
            "_id" : "2"
        }
    ]
}'
```

在这种情况下，id 可以被用作发起简单的请求：

```
curl 'localhost:9200/test/type/_mget' -d '{
    "ids" : ["1", "2"]
}'
```

### 可选类型

该 MGET API 允许`_type`是可选的。将其设置为 `_all 或`空，以获取第一个文档匹配所有类型的ID。

如果不设置类型，许多文件共享相同的 `_id`，你最终将只得到第一个匹配的文件。

例如，如果你有文件1包含 typeA 和 typeB ，那么下面的请求会给你同一个文档两次：

```
curl 'localhost:9200/test/_mget' -d '{
    "ids" : ["1", "1"]
}'
```

你需要在这种情况下，明确设置`_type`：

```
GET /test/_mget/
{
  "docs" : [
        {
            "_type":"typeA",
            "_id" : "1"
        },
        {
            "_type":"typeB",
            "_id" : "1"
        }
    ]
}
```

### Source filtering

默认情况下，`_source`将为每个文档返回（如果储存）。类似于 GET API，你可以检索的只是部分 `_source`使用的 `_source`参数。您还可以使用URL参数 `_source`，`_source_include`及`_source_exclude 来指定`默认值。例如：

```
curl 'localhost:9200/_mget' -d '{
    "docs" : [
        {
            "_index" : "test",
            "_type" : "type",
            "_id" : "1",
            "_source" : false
        },
        {
            "_index" : "test",
            "_type" : "type",
            "_id" : "2",
            "_source" : ["field3", "field4"]
        },
        {
            "_index" : "test",
            "_type" : "type",
            "_id" : "3",
            "_source" : {
                "include": ["user"],
                "exclude": ["user.location"]
            }
        }
    ]
}'
```

### Fields

通过每个文档来可以指定具体存储字段，类似于 Get API 中 stored\_fields 参数。例如：

```
curl 'localhost:9200/_mget' -d '{
    "docs" : [
        {
            "_index" : "test",
            "_type" : "type",
            "_id" : "1",
            "stored_fields" : ["field1", "field2"]
        },
        {
            "_index" : "test",
            "_type" : "type",
            "_id" : "2",
            "stored_fields" : ["field3", "field4"]
        }
    ]
}'
```

或者，可以指定 `stored_fields`作为默认值被应用到所有文件中来查询字符串参数。

```
curl 'localhost:9200/test/type/_mget?stored_fields=field1,field2' -d '{
    "docs" : [
        {
            "_id" : "1"  # 1
        },
        {
            "_id" : "2",
            "stored_fields" : ["field3", "field4"] # ２
        }
    ]
}'
```

| 1 | 返回 `field1`和 `field2` |
| - | --------------------- |
| 2 | 返回 `field3`和 `field4` |

### Generated fields

见 “[Generated fields](https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-get.html#generated-fields)”

### Routing

您也可以指定 routing 作为参数：

```
curl 'localhost:9200/_mget?routing=key1' -d '{
    "docs" : [
        {
            "_index" : "test",
            "_type" : "type",
            "_id" : "1",
            "_routing" : "key2"
        },
        {
            "_index" : "test",
            "_type" : "type",
            "_id" : "2"
        }
    ]
}'
```

在这个例子中，文件 `test/type/2`将从对应于 routing ＝ `key1 的分片中获取。`但文件 `test/type/1`将被从对应于 routing ＝ `key1 的分片中获取。`

### 安全

见 [*URL-based access control*](https://www.elastic.co/guide/en/elasticsearch/reference/5.2/url-access-control.html)
