# 路由

当你索引一个文档，它被保存在单个的主分片上，Elasticsearch如何知道文档属于哪个分片呢？ 当我们创建一个新文档，它如何知道应该存储在分片1还是分片2上呢？

这个过程不能是随机的，因为我们将来需要取回该文档。 事实上，它是由一个非常简单的公式来决定的:

```
分片 = hash(routing) % 主分片数量
```

`routing` 值可以是任何的字符串， 默认是文档的 `_id` ，但也可以设置成一个自定义的值。 `routing` 字符串被传递到一个哈希函数以生成一个数字，然后除以索引的主分片的数量 得到余数 *remainder*. 余数将总是在 `0` 到 `主分片数量 - 1` 之间, 它告诉了我们用以存放 一个特定文档的分片编号。

这解释了为什么主分片的数量只能在索引创建时设置、而且不能修改。 如果主分片的数量一旦在日后进行了修改，所有之前的路由值都会无效，文档再也无法被找到。

所有文档 APIs (`get`, `index`, `delete`, `bulk`, `update` 和 `mget`) 都可以接受 `routing` 参数，用以自定义 文档-到-分片 的映射。 自定义的路由将用于确保所有的文档 -- 例如属于同一用户的所有文档 -- 保存在相同的分片上。 我们将在 `<<扩展>>` 中详细讨论你为什么希望这么做。


---

# 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://hezhiqiang.gitbook.io/elasticsearch/distributed_crud/routing.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.
