DavidKim
DavidKim3y ago

Potentially a dumb question about which

Potentially a dumb question about which type of "query" is the most performant in Convex
5 Replies
DavidKim
DavidKimOP3y ago
Read the docs explaining the performance gain of using indexes (I loved the explanation). I have usecases where I want to grab a document by it's _id . And I was wondering if
const space = await db.query("spaces").filter((q) => {
return q.eq("_id", spaceId)
}).unique();
const space = await db.query("spaces").filter((q) => {
return q.eq("_id", spaceId)
}).unique();

is faster or
const space = await db.get(spaceId) as Document<"spaces"> ;
const space = await db.get(spaceId) as Document<"spaces"> ;
or
const space = await db
.query("spaces")
.withIndex("by_id", (q) =>
q.eq("_id", spaceId)
).unique()
const space = await db
.query("spaces")
.withIndex("by_id", (q) =>
q.eq("_id", spaceId)
).unique()
And if it's the last option, is it possible to index by _id ?
sujayakar
sujayakar3y ago
hi @DavidKim ! not a dumb question at all. (2) and (3) are pretty much the same, where it's a single lookup against the index. (1) is a full table scan, where it has to look at every document in spaces (I think you already read it, but https://docs.convex.dev/understanding/indexes-and-query-perf has more details). so, I'd recommend using (2), since it's less verbose. we currently don't allow including _id as an indexed field in user defined indexes, but let us know if that'd be helpful!
Introduction to Indexes and Query Performance | Convex Developer Hub
How do I ensure my Convex database queries are fast
DavidKim
DavidKimOP3y ago
If 2 is the same as indexing by _id, I have no need for indexing by _id ! so 2 it is ! thank you ! From DX perspective, I think the only downside of
const space = await db.get(id) as Document<"spaces">;
const space = await db.get(id) as Document<"spaces">;
is that I have to type it with as where as the indexed query can infer the type for me but not sure if this is a big deal
sshader
sshader3y ago
For the types, I believe that if id has type Id<"spaces" the return type of await db.get(id) will be Document<"spaces"> | null so alternatively const space: Document<"spaces"> = (await db.get(id))! should work (or explicitly handling the null). (and actually our latest release has unique returning a Document or null too, so you'd need the null handling with (3) as well)
DavidKim
DavidKimOP3y ago
ahh you're right; it wasn't inferring properly because I originally did not type the id correctly. Thank you !!

Did you find this page helpful?