#withIndex vs withSearchIndex

5 messages · Page 1 of 1 (latest)

wispy mesa
#

what's the difference between using ".withIndex" and ".withSearchIndex" when trying to query with arguments?

dim nacelleBOT
#

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 .withIndex queries. 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 .withSearchIndex with .withIndex or .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
#

Best practice: Use .withIndex for structured queries on specific fields, and .withSearchIndex when you need to perform full text search. Always try to put as many filters as possible into the index or search index for best performanceBest Practices.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: