#Is it possible to make an index on a nested key within an object?
3 messages · Page 1 of 1 (latest)
Hi @urban forum. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, it is possible to create an index on a nested key within an object in Convex.
Convex supports indexing on nested properties using dot notation. Here's how you can define an index on a nested field:
export default defineSchema({
blocks: defineTable({
// ... other fields
properties: {
gridLayout: {
i: v.string()
}
}
}).index("by_parent_grid_idx", ["parentBlockId", "properties.gridLayout.i"])
});
In this example, we're creating an index called "by_parent_grid_idx" that includes both the "parentBlockId" field and the nested "properties.gridLayout.i" field.
You can then use this index in your queries:
const block = await context.db
.query("blocks")
.withIndex("by_parent_grid_idx", (q) =>
q.eq("parentBlockId", parentBlockId).eq("properties.gridLayout.i", gridLayout.i)
)
.unique();
It's worth noting that while TypeScript might have issues with nested property types, the indexing itself is supported by Convex. You may need to use type assertions in some cases to work around TypeScript limitations.
Source: Discord support thread: Nested field indexes and query filters (https://discord.com/channels/1019350475847499849/1249001022278336532)