#Schema Indexes

4 messages · Page 1 of 1 (latest)

tiny plover
#

looking at my schema, do i need set indexes on v.id fields? so like the userId on collections or the collectionId on the collectionCards table? do i need to specific a .index for all them or does convex automatically index fields that have corresponding v.ids set?

tribal cometBOT
#

Hi @tiny plover. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Convex does not automatically create indexes for v.id fields, so you will need to explicitly define indexes for fields like userId or collectionId if you plan to query by those fields.

Indexes in Convex are defined as part of your schema and are necessary for efficient querying when your tables grow larger. Without an index, Convex performs a full table scan, which becomes inefficient as your data grows.

Here's how you would define indexes for your userId and collectionId fields:

export default defineSchema({
  collections: defineTable({
    userId: v.id("users"),
    // other fields...
  }).index("by_userId", ["userId"]),
  
  collectionCards: defineTable({
    collectionId: v.id("collections"),
    // other fields...
  }).index("by_collectionId", ["collectionId"])
});

As explained in the Convex documentation, indexes allow you to speed up your document queries by telling Convex how to organize your documents. Each index consists of a name (which must be unique per table) and an ordered list of fields to index Database > Reading-data > Indexes.

When you define an index, Convex creates an additional data structure that is sorted by the specified field(s), making queries that filter on those fields much more efficient Stack > Intro to Convex Query Performance.

Remember that indexes are created during npx convex dev and npx convex deploy, and the first deploy that defines an index might be slower than normal as Convex needs to backfill your index.

#

I recommend adding indexes for any fields you frequently query by, especially foreign key fields like v.id references to other tables.

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