Sharding

Shard selection

StepOperation
Routing value
  • Elasticsearch uses request routing
  • When omitted, document _id becomes _routing
  • Pass tenant_id as routing to shard by tenant
Hash
  • Elasticsearch calculates hash(_routing)
  • The same routing value always produces the same hash
Indices created in 9.4+shard_num = hash(_routing) % number_of_primary_shards.
Earlier indices
  • Calculate routing_factor = number_of_routing_shards / number_of_primary_shards
  • Calculate shard_num = (hash(_routing) % number_of_routing_shards) / routing_factor
50 primariesThe modulo result selects exactly one primary shard from 0 to 49.
Search
  • routing targets its selected shard group
  • An omitted value targets all shard groups
  • Each group serves from its primary or a replica

Why shards can be empty

  • Hashing is deterministic and independent of node load or document count.
  • With routing_partition_size = 1, routing cardinality bounds populated shards; five values populate at most five of 50 shards and collisions can reduce that number.
  • An empty shard is allocated but has received no matching routing hash. UNASSIGNED means allocation failed.

Custom routing

# routing_partition_size = 1 maps one routing value to one shard; 100 routing shards allow a 50 → 100 split.
PUT /orders-v1
{
  "settings": {
    "number_of_shards": 50,
    "number_of_routing_shards": 100,
    "routing_partition_size": 1
  },
  "mappings": {
    "_routing": { "required": true },
    "properties": {
      "tenant_id": { "type": "keyword" },
      "order_id": { "type": "keyword" }
    }
  }
}

POST /orders-v1/_doc/order-1001?routing=tenant-42
{
  "tenant_id": "tenant-42",
  "order_id": "order-1001"
}

Check the selected shard

Use the same routing value used when indexing:

GET /orders-v1/_search_shards?routing=tenant-42

shards[0][*].shard is the shard number; the entries are its primary and replica copies. For default routing, pass the document _id as routing.