Changing the Schema
If an index’s schema is changed, it must be rebuilt. This includes:- Adding a field to the index
- Removing a field from the index
- Renaming an indexed column in the underlying table
- Changing a field’s tokenizer
search_idx, and we want to create a new index called search_idx_v2.
First, use CREATE INDEX CONCURRENTLY to build a new index in the background.
The
CONCURRENTLY clause is required. CONCURRENTLY allows the existing
index to continue serving queries while the new index is being built.pg_stat_progress_create_index to track the progress of the new index.
Once the new index is done building, confirm that it is valid:
Expected Response
true, the original index can safely be dropped, which will redirect queries to the new index.
Rebuilding the Index
REINDEX is used to rebuild an index without changing the schema.
The basic syntax for REINDEX is:
REINDEX CONCURRENTLY:
REINDEX CONCURRENTLY is slower than a plain REINDEX. Generally speaking, REINDEX CONCURRENTLY is recommended for
production systems that cannot tolerate temporarily blocked writes.
Important Caveats
AlthoughCREATE INDEX CONCURRENTLY and REINDEX CONURRENTLY run in the background, Postgres requires that the
session that is executing the command remain open. If the session is closed,
Postgres will cancel the operation. This is relevant if you are using a
connection pooler like pgbouncer, which may terminate
sessions after a certain idle timeout is reached.
If REINDEX CONCURRENTLY fails or is cancelled, an invalid transient index will be left behind that must be dropped manually.
To check for invalid indexes in psql, run \d <table_name> and look for INVALID indexes.