Skip to content

Statements

REBUILD

The REBUILD statement is used to rebuild indexes in SurrealDB. It is usually used in relation to a specified Index to optimise performance. It is useful to rebuild indexes because sometimes HNSW index performance can degrade due to frequent updates.

Rebuilding the index will ensure the index is fully optimised.

Note

By default, REBUILD INDEX waits until the rebuild finishes before the statement returns (the same behaviour as DEFINE INDEX without CONCURRENTLY). Adding CONCURRENTLY on the rebuild statement will cause it to return immediately, after which progress can be monitored via INFO FOR INDEX. Whether the index was originally created with CONCURRENTLY does not affect rebuilds. See the CONCURRENTLY clause on DEFINE INDEX for the same blocking vs non-blocking distinction when creating an index.

SurrealQL Syntax
REBUILD [
	INDEX [ IF EXISTS ] @name ON [ TABLE ] @table [ CONCURRENTLY ]
]
Note

The IF EXISTS and TABLE clauses are optional.

For example, if you have a table called book and you have an index called uniq_isbn on the isbn field, you can rebuild the index using the following query:

REBUILD INDEX uniq_isbn ON book;

The following queries show an example of how to rebuild resources using the IF EXISTS clause, which will only rebuild the resource if it exists.

REBUILD INDEX IF EXISTS uniq_isbn ON book;

An upgrade to a new release does not rewrite existing indexes. Most keep working as they are, and a few need REBUILD INDEX to repair results or to use a faster query plan. Rebuild them once every node in a cluster runs the new version. The indexes that apply to the move from 3.x to 4.0 are listed in Upgrading from 3.x to 4.0.

Run REBUILD INDEX as its own statement for an index with many records, not inside BEGIN ... COMMIT, a block or a function. From SurrealDB 4.0, a standalone REBUILD INDEX commits the change to the index definition first and then waits for the build. A build that outlasts the query timeout keeps running, and the statement reports that the timeout was exceeded rather than that the rebuild failed. Check progress with INFO FOR INDEX and leave the build to finish.

A rebuild inside a transaction still waits within that transaction, and on a large index the final commit can fail with a transaction conflict.

Was this page helpful?