Unsharded keyspaces
If you only have a single, unsharded keyspace in your database cluster, then your keyspace maps directly to your database cluster in PlanetScale. For example, if you have an unsharded PlanetScale database namedgymtracker
with the default primary and 2 replicas, you likely only have a single keyspace. You can reference this keyspace in the same way you normally would your database:
Sharded keyspaces
As your database grows, you may wish to shard some tables in your database cluster. To do this, you will create a new keyspace and add the shards to the sharded keyspace. The following diagram depicts a PlanetScale database with 2 keyspaces: one unsharded and one sharded. The unsharded keyspace has the default 1 primary and 2 replicas. The sharded keyspace contains two shards, each with 1 primary and 2 replicas.
use
syntax, but this time, specify the keyspace name. For example, if we created a sharded keyspace for gymtracker
, we may call it gymtracker_sharded
. You can directly target the keyspace with the following:
Routing queries in your application
One of the many perks of Vitess/PlanetScale is that you can distribute your data across hundreds of MySQL instances without complicating your application code. As mentioned earlier, all of these keyspaces and shards appear as a single MySQL instance to your application. Once you add multiple keyspaces, you no longer need to specify a database name in your application’s database connection configuration code. Our Global Edge Network will correctly route you to the correct Vitess cluster, and the VTGates in your cluster will handle routing the request to the correct keyspace and shard. Some frameworks and ORMs require a database name is specified. In these scenarios, you can set the database name to@primary
, and your requests will be automatically routed to the correct keyspace/shard. Alternatively, if you have specific queries that you wish to send to replicas, you can use @replica
.