Skip to content

Indexes

Index types and strategies

Indexes speed up the shapes of queries you run often: equality filters, uniqueness checks, text search, and similarity over vectors.

You need the same namespace/database scope and privileges as other DEFINE statements. Clause-by-clause detail can be found in the DEFINE INDEX page.

SurrealDB offers a range of indexing capabilities designed to optimise data retrieval and search efficiency. The examples below build the indexes for a recipe site one at a time. Each recipe record has a slug for its URL, a title, an author, a cuisine and a published flag, and each example adds the index that one feature of the site needs.

An index with FIELDS or COLUMNS and no special clause (UNIQUE, COUNT, FULLTEXT, etc.) is a standard B-tree index - the default secondary index type.

The site has a page for each cuisine, which lists the recipes with a filter on cuisine. A standard index on that field lets the query read the matching records directly instead of scanning the table.

DEFINE INDEX recipe_cuisine ON TABLE recipe FIELDS cuisine;

INSERT INTO recipe [
	{ id: recipe:risotto, title: 'Mushroom risotto', cuisine: 'Italian' },
	{ id: recipe:dal, title: 'Tarka dal', cuisine: 'Indian' }
] RETURN NONE;

SELECT title FROM recipe WHERE cuisine = 'Italian';
Output
[{ title: 'Mushroom risotto' }]

A unique index ensures that each value in the index is unique. A unique index helps enforce uniqueness across records by preventing duplicate entries in fields such as user IDs, email addresses, and other unique identifiers.

Two recipes cannot share a URL, so the slug field gets a unique index. The INFO statement shows the indexes defined on a table.

DEFINE INDEX recipe_slug ON TABLE recipe FIELDS slug UNIQUE;

INFO FOR TABLE recipe;
Output
{
	events: {},
	fields: {},
	indexes: {
		recipe_slug: 'DEFINE INDEX recipe_slug ON recipe FIELDS slug UNIQUE'
	},
	lives: {},
	tables: {}
}

As the slug field has a UNIQUE index, a second recipe with the same slug is refused with an error.

-- Setup from the example above
DEFINE INDEX recipe_slug ON TABLE recipe FIELDS slug UNIQUE;

CREATE recipe:shakshuka SET slug = 'shakshuka', title = 'Shakshuka';
CREATE recipe:green_shakshuka SET slug = 'shakshuka', title = 'Green shakshuka';
Error output
"Database index `recipe_slug` already contains 'shakshuka', with record `recipe:shakshuka`"

A composite index spans multiple fields of a table. With UNIQUE, it enforces uniqueness when the definition of what is unique pertains to more than one field.

Many authors publish a recipe called "Hummus", but each author should publish it only once. A unique index on author and title together accepts the first two records below and refuses the third.

DEFINE INDEX recipe_author_title ON recipe FIELDS author, title UNIQUE;

CREATE recipe:hummus_y SET author = 'Yotam', title = 'Hummus';
CREATE recipe:hummus_n SET author = 'Nigella', title = 'Hummus';
CREATE recipe:hummus_y2 SET author = 'Yotam', title = 'Hummus';
Error output
"Database index `recipe_author_title` already contains ['Yotam', 'Hummus'], with record `recipe:hummus_y`"

A composite index also serves queries. The query planner uses it for a WHERE clause that filters on its leading fields: author = 'Yotam' alone, author = 'Yotam' AND title = 'Hummus', or an equality on author followed by a range on the next field. A filter that skips the first field, such as title = 'Hummus' on its own, cannot use the index. Use EXPLAIN to confirm which index a query uses.

Note

Before SurrealDB 2.2.0, the query planner used a composite index only for conditions on its first field. Range conditions on a field after an equality prefix use the index from 3.0.0.

A count index uses the COUNT special clause instead of the usual FIELDS / COLUMNS form (which defines a standard B-tree index). Use it with count() and GROUP ALL.

  • COUNT - full-table counts: SELECT count() FROM <table> GROUP ALL.

  • COUNT WHERE <condition> - filtered counts when the query WHERE exactly matches the index condition.

An unconditional count index is optional for full-table counts; SurrealDB already uses a CountScan fast path that counts keys without deserialising records. COUNT WHERE is most useful for repeated filtered counts without scanning the whole table.

The home page of the recipe site shows how many recipes the site holds, and how many of them are published. Each of the two counts has an index of its own:

DEFINE INDEX recipe_count ON recipe COUNT;
DEFINE INDEX recipe_published_count ON recipe COUNT WHERE published = true;

INSERT INTO recipe [
	{ id: recipe:shakshuka, title: 'Shakshuka', published: true },
	{ id: recipe:risotto, title: 'Mushroom risotto', published: true },
	{ id: recipe:dal, title: 'Tarka dal', published: false }
] RETURN NONE;

SELECT count() FROM recipe GROUP ALL;
//- [{ count: 3 }]
SELECT count() FROM recipe WHERE published = true GROUP ALL;
//- [{ count: 2 }]

A standard index (DEFINE INDEX … FIELDS … on the same field) can also accelerate filtered counts when it fully covers the WHERE clause; you typically choose one approach, not both. For choosing between standard and count indexes (including storage tradeoffs), see When to use which. For counting several statuses (IN lists vs per-status totals), see Multiple conditions.

Enables efficient searching through textual data, supporting advanced text-matching features like proximity searches and keyword highlighting.

The Full-Text search index helps implement comprehensive search functionalities in applications, such as searching through articles, product descriptions, and user-generated content.

The recipe site has a search box for recipe titles. A full-text index on title finds a word in any position of the title, and search::highlight marks it in the result:

INSERT INTO recipe [
	{ id: recipe:risotto, title: 'Mushroom risotto' },
	{ id: recipe:dal, title: 'Tarka dal' }
] RETURN NONE;

DEFINE ANALYZER recipe_text TOKENIZERS class FILTERS lowercase, ascii;
DEFINE INDEX recipe_title_search ON TABLE recipe FIELDS title
    FULLTEXT ANALYZER recipe_text BM25 HIGHLIGHTS;

SELECT id, search::highlight('<b>', '</b>', 1) AS title
    FROM recipe WHERE title @1@ 'Risotto';
Output
[{ id: recipe:risotto, title: 'Mushroom <b>risotto</b>' }]
  • FULLTEXT: enables full-text search on the specified field. Before SurrealDB 3.0.0 this clause was SEARCH, which 3.x rejects as a parse error.

  • ANALYZER recipe_text: uses a custom analyzer called recipe_text, which splits the text with the class tokenizer and passes each word through the lowercase and ascii filters, so a search for Risotto matches risotto.

  • BM25: Ranking algorithm used for relevance scoring.

  • HIGHLIGHTS: Allows keyword highlighting in search results output when using the search::highlight function

  • FIELDS: a full-text search index can only be used on one field at a time. To use full-text search on more than one field, use a separate DEFINE INDEX statement for each one.

Indexes can be rebuilt using the REBUILD statement. This can be useful when you want to update the index definition or when you want to rebuild the index to optimise performance.

You may want to rebuild an index over time to ensure that the index is up-to-date with the latest data in the table.

-- Setup from the examples above
DEFINE INDEX recipe_slug ON TABLE recipe FIELDS slug UNIQUE;

REBUILD INDEX recipe_slug ON recipe;

Building indexes can be lengthy and may time out before they're completed. Without CONCURRENTLY, DEFINE INDEX blocks until the index is ready. The CONCURRENTLY clause can be used when the statement should return immediately while the build runs in the background, during which progress can be monitored with INFO FOR INDEX.

When the recipe site adds a page for each author, the table already holds every recipe, so the index on author is built in the background:

INSERT INTO recipe [
	{ id: recipe:shakshuka, title: 'Shakshuka', author: 'Yotam' },
	{ id: recipe:risotto, title: 'Mushroom risotto', author: 'Nigella' }
] RETURN NONE;

DEFINE INDEX recipe_author ON recipe FIELDS author CONCURRENTLY;
INFO FOR INDEX recipe_author ON recipe;
Possible output
{
	building: {
		active: false,
		armed_shards: 0,
		compacting: false,
		queued: false,
		status: 'started'
	}
}

Run INFO FOR INDEX again until status is ready.

Warning

DEFER is available in SurrealDB 2.5 through 2.x only. On 3.x the clause is rejected at parse time, and this section applies to 2.x deployments, so its example uses the 2.x SEARCH ANALYZER clause that 3.x renamed to FULLTEXT ANALYZER. On 3.x, use CONCURRENTLY to build an index in the background - note that it addresses initial builds, not the ongoing write-path queueing DEFER provided.

Index updates in SurrealDB occur synchronously during document operations. This ensures immediate consistency, in which all reads return the most recent write. However, this can become a bottleneck during high-volume parallel ingestion, leading to write-write conflicts and increased latency, particularly with Full-Text or Vector indexes.

The DEFER clause can be used in this case if eventual consistency is acceptable, namely a setting in which reads may return stale data for a short period, but will eventually converge to the most recent write. An index with this clause will be enqueued in a persistent background queue so that ingestion and indexing are decoupled. On a 2.x deployment of the recipe site that imports thousands of recipes at once, the title search index can be deferred:

DEFINE ANALYZER recipe_text TOKENIZERS class FILTERS lowercase, ascii;
DEFINE INDEX recipe_title_search ON recipe FIELDS title
    SEARCH ANALYZER recipe_text BM25 HIGHLIGHTS DEFER;

Note: As unique indexes offer a guarantee that no records that contravene the index will ever exist, the UNIQUE clause cannot be used together with DEFER.

When defining indexes, consider which fields are most frequently queried.

Indexes may improve the performance of SurrealQL statements. This may not be noticeable with small tables but it can be significant for large tables; especially when the indexed fields are used in the WHERE clause of a SELECT statement.

Indexes can also impact the performance of write operations (INSERT, UPDATE, DELETE) since the index needs to be updated accordingly, so the need for read performance has to be balanced against write performance.

Was this page helpful?

Last updated