From 42e25dcfa0a06b961dbea86bacf673b7f77b7525 Mon Sep 17 00:00:00 2001 From: Andrew Atkinson Date: Fri, 24 Apr 2026 21:57:29 -0500 Subject: [PATCH] Add reindex shell script with tmux and psql Invoke manual REINDEX commands, either specific indexes or all indexes for a table Use "VERBOSE" and "CONCURRENTLY" options Set a high statement_timeout to allow enough time for a REINDEX operation to finish Add a link to a query to monitor concurrent index build progress --- db/db_reindex_batch.sh | 30 ++++++++++++++++++++++++++++++ db/reindex_batch.sql | 14 ++++++++++++++ 2 files changed, 44 insertions(+) create mode 100755 db/db_reindex_batch.sh create mode 100755 db/reindex_batch.sql diff --git a/db/db_reindex_batch.sh b/db/db_reindex_batch.sh new file mode 100755 index 0000000..70afb4d --- /dev/null +++ b/db/db_reindex_batch.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# Dependencies: +# - tmux (detach "ctrl-b" and re-attach e.g. "tmux attach -t db_reindex") +# - export DATABASE_URL (must be set) to be set to DB connection string URL +# - reindex_batch.sql to have the reindex commands +# - monitor progress: https://github.com/andyatkinson/pg_scripts/blob/main/concurrent_index_build_progress.sql +# - run monitor SQL above repeatly, every 1s: "psql> \watch 1" + +# Configuration +SESSION_NAME="db_reindex" +SQL_FILE="reindex_batch.sql" + +# Create new tmux session and detach from it +tmux new-session -d -s $SESSION_NAME + +# Send the psql command to the tmux session and execute it +tmux send-keys -t $SESSION_NAME "psql -d $DATABASE_URL -f $SQL_FILE" C-m + +# List the sessions +tmux ls + +# Reattach later on +echo +echo "Reindexing is now taking place inside session '$SESSION_NAME' and you're detached from it" +echo +echo "To re-attach, find the session name w/ 'tmux ls'. Hint: 'tmux attach -t $SESSION_NAME'" +echo +echo "To monitor concurrent index build progress: https://github.com/andyatkinson/pg_scripts/blob/main/concurrent_index_build_progress.sql" +echo diff --git a/db/reindex_batch.sql b/db/reindex_batch.sql new file mode 100755 index 0000000..2c56ab5 --- /dev/null +++ b/db/reindex_batch.sql @@ -0,0 +1,14 @@ +set statement_timeout='2h'; -- or whatever max is needed to perform the longest one of these + +reindex (verbose) index concurrently trips_pkey; +reindex (verbose) index index_trips_on_driver_id; +reindex (verbose) index index_trips_on_rating; +reindex (verbose) index index_trips_on_trip_request_id; + +reindex (verbose) index trip_requests_pkey; +reindex (verbose) index index_trip_requests_on_end_location_id; +reindex (verbose) index index_trip_requests_on_rider_id; +reindex (verbose) index index_trip_requests_on_start_location_id; + +-- users table has 3 indexes, reindex all indexes for table +reindex (verbose) table concurrently users;