How to Use Routing in Elasticsearch for Efficient Data Access
In Elasticsearch,
routing is used to control which shard a document is stored in or searched from by specifying a routing key. You add a routing parameter when indexing or querying documents to improve performance by targeting specific shards instead of all shards.Syntax
Routing in Elasticsearch is specified using the routing parameter in both indexing and search requests. This parameter determines the shard where the document is stored or searched.
- Indexing: Use
routingto assign a document to a shard. - Searching: Use
routingto limit search to a specific shard.
json
POST /my_index/_doc/1?routing=user123 { "field": "value" } GET /my_index/_search?routing=user123 { "query": { "match_all": {} } }
Example
This example shows how to index a document with a routing key and then search using the same routing key to query only the shard containing that document.
json
PUT /my_index/_doc/1?routing=user123 { "name": "Alice", "age": 30 } GET /my_index/_search?routing=user123 { "query": { "match": { "name": "Alice" } } }
Output
{
"hits": {
"total": 1,
"hits": [
{
"_id": "1",
"_source": {
"name": "Alice",
"age": 30
}
}
]
}
}
Common Pitfalls
Common mistakes when using routing include:
- Not using the same routing key for indexing and searching, causing queries to miss documents.
- Using routing unnecessarily, which can reduce Elasticsearch's ability to balance data across shards.
- Forgetting to specify routing on search requests when documents were indexed with routing, resulting in empty results.
json
/* Wrong: Index with routing but search without routing */ PUT /my_index/_doc/2?routing=user456 { "name": "Bob" } GET /my_index/_search { "query": { "match": { "name": "Bob" } } } /* Right: Search with the same routing */ GET /my_index/_search?routing=user456 { "query": { "match": { "name": "Bob" } } }
Quick Reference
| Operation | Routing Usage | Description |
|---|---|---|
| Indexing | Specify routing parameter | Assign document to shard based on routing key |
| Searching | Specify routing parameter | Limit search to shard with routing key |
| Update/Delete | Specify routing parameter | Target document shard for update or delete |
| No Routing | Omit routing | Elasticsearch uses default routing (document ID) |
Key Takeaways
Use the same routing key when indexing and searching to ensure correct shard targeting.
Routing improves performance by limiting operations to specific shards.
Avoid unnecessary routing to maintain balanced shard distribution.
Specify routing in update and delete requests if used during indexing.
If routing is not specified, Elasticsearch uses the document ID to route data.