How to rename keyspace in Apache Cassandra 4
Renaming keyspaces (and column families) is no supported in Apache Cassandra version 4. But if you need it, you can make a keyspace clone and delete old keyspce instead rename. This story was made by this answer on stack-overflow.
Steps to clone keyspace:
1 — Export the schema from the old keyspace to a file
/opt/cassandra/bin/cqlsh ip_cassandra -u user -p password -e "DESCRIBE keyspace_name;" > old_keyspace.cql
2 — Replace the keyspace name in the file to new keyspace
3 — Apply the schema to the new keyspace (and the keyspace itself) from the file
/opt/cassandra/bin/cqlsh ip_cassandra -u user -p password -f old_keyspace.cql
4 — Clear snapshots on each node
nodetool clearsnapshot --all
5 — Take snapshots from the old keyspace on each node
nodetool flush
nodetool snapshot -t clone old_keyspace
6 — Move the snapshots to the table folders in the new keyspace (see script bellow) on each node
sudo sh clone.sh old_keyspace new_keyspace
There is a code of clone.sh script:
#!/bin/bash
if [ "$#" -ne 2 ]; then
echo "Usage: $0 keyspace_from keyspace_to"
exit 1
fi
keyspace_from=$1
keyspace_to=$2
for src_table_dir in /data/cassandra/data/$keyspace_from/*-*
do
src_table=$(basename $src_table_dir)
table=$(echo $src_table | cut -d "-" -f 1)
if [ ! -d $src_table_dir/snapshots/clone ]; then
echo "NO SNAPSHOTS DIRECTORY IN $src_table_dir, SKIPPING..."
continue
fi
dest_table_dir=$(find /data/cassandra/data/$keyspace_to/ -maxdepth 1 -type d -name "$table-*")
if [ ! -d $dest_table_dir ]; then
echo "Destination table directory for $table does not exist in $keyspace_to, creating it..."
continue
fi
echo "Moving snapshots from $src_table_dir/snapshots to $dest_table_dir..."
for file in "$src_table_dir"/snapshots/clone/*; do
if [ -f "$file" ]; then
mv "$file" "$dest_table_dir/"
fi
done
mv $src_table_dir/snapshots/copy/* $dest_table_dir/
if [ $? -ne 0 ]; then
echo "Error during copying, exiting..."
exit 1
fi
done
echo "The clonning process done."
7 — Restart Cassandra on each node
sudo systemctl restart cassandra