#withIndex vs withSearchIndex
5 messages · Page 1 of 1 (latest)
Hi @wispy mesa. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
The main difference between .withIndex and .withSearchIndex in Convex is the type of index they use and the kind of queries they support:
.withIndex
- Uses a standard index (B-tree style) defined on one or more fields in your table.
- Allows you to efficiently query documents by specifying equality and range conditions on the indexed fields, in the order they appear in the index.
- Example: To get all messages by a specific author:
const messages = await ctx.db .query("messages") .withIndex("by_author", q => q.eq("author", "Tom")) .collect(); - You can chain equality (
.eq) and range (.gt,.gte,.lt,.lte) conditions, but only in index order. You cannot skip fields or use "or"/"in"/"neq" conditions in.withIndexqueries. The results are ordered by the index fields unless you apply an explicit.order()Convex’s query syntax, Querying documents using indexes.
.withSearchIndex
- Uses a full text search index defined on a text field (or fields).
- Allows you to perform text search queries, ranking results by relevance to the search terms.
- You must provide a
.search()expression for the search field, and you can add equality filters for any additional filter fields defined in the search index. - Example: To search for messages containing "hello hi" in their body, within a specific channel:
const messages = await ctx.db .query("messages") .withSearchIndex("search_body", q => q.search("body", "hello hi").eq("channel", "#general") ) .take(10); - The results are ordered by relevance, not by the index fields. You cannot combine
.withSearchIndexwith.withIndexor.order()—it acts as both the index and the ordering for the queryRunning search queries, withSearchIndex API, Dynamic Query Builders.
Summary Table
| Feature | .withIndex |
.withSearchIndex |
|---|---|---|
| Index type | Standard (B-tree) | Full text search |
| Query type | Equality/range on fields | Text search + equality |
| Result order | By index fields or explicit | By relevance (search score) |
| Can combine with order | Yes (.order()) |
No (order is by relevance) |
| Use case | Structured queries | Text search queries |