用途
本技能提供 Convex 数据库查询、索引与过滤的最佳实践,适用于在 Convex 中编写或审查数据库查询、处理 .filter()、设计索引以及优化查询性能的场景。
主要能力
使用索引的查询模式
推荐使用 .withIndex() 配合参数校验与返回类型声明:
export const listUserTasks = query({
args: { userId: v.id("users") },
returns: v.array(v.object({
_id: v.id("tasks"),
_creationTime: v.number(),
title: v.string(),
completed: v.boolean(),
})),
handler: async (ctx, args) => {
return await ctx.db
.query("tasks")
.withIndex("by_user", (q) => q.eq("userId", args.userId))
.order("desc")
.collect();
},
});
避免在数据库查询中使用 .filter()
应改用 .withIndex(),因为 .filter() 的性能与在代码中过滤相同:
// Bad - using .filter()
const tomsMessages = await ctx.db
.query("messages")
.filter((q) => q.eq(q.field("author"), "Tom"))
.collect();
// Good - use an index
const tomsMessages = await ctx.db
.query("messages")
.withIndex("by_author", (q) => q.eq("author", "Tom"))
.collect();
// Good - filter in code (if index not needed)
const allMessages = await ctx.db.query("messages").collect();
const tomsMessages = allMessages.filter((m) => m.author === "Tom");
查找 .filter() 用法:使用正则 \.filter\(\(?q 搜索。
例外:分页查询可以从 .filter() 中受益。
仅在结果集较小时使用 .collect()
对于 1000 条以上文档,应使用索引、分页或限制:
// Bad - potentially unbounded
const allMovies = await ctx.db.query("movies").collect();
// Good - use .take() with "99+" display
const movies = await ctx.db
.query("movies")
.withIndex("by_user", (q) => q.eq("userId", userId))
.take(100);
const count = movies.length === 100 ? "99+" : movies.length.toString();
// Good - paginated
const movies = await ctx.db
.query("movies")
.withIndex("by_user", (q) => q.eq("userId", userId))
.order("desc")
.paginate(paginationOptions);
索引配置
// convex/schema.ts
export default defineSchema({
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
sentAt: v.number(),
})
.index("by_channel", ["channelId"])
.index("by_channel_and_author", ["channelId", "authorId"])
.index("by_channel_and_time", ["channelId", "sentAt"]),
});
检查冗余索引
by_foo 与 by_foo_and_bar 通常是冗余的,只保留 by_foo_and_bar:
// Bad - redundant
.index("by_team", ["team"])
.index("by_team_and_user", ["team", "user"])
// Good - single combined index works for both
const allTeamMembers = await ctx.db
.query("teamMembers")
.withIndex("by_team_and_user", (q) => q.eq("team", teamId)) // Omit user
.collect();
const specificMember = await ctx.db
.query("teamMembers")
.withIndex("by_team_and_user", (q) => q.eq("team", teamId).eq("user", userId))
.unique();
例外:by_foo 实际上是 foo + _creationTime。如果需要该排序顺序,则保留为独立索引。
不要在查询中使用 Date.now()
当 Date.now() 变化时,查询不会重新运行:
// Bad - stale results, cache thrashing
const posts = await ctx.db
.query("posts")
.withIndex("by_released_at", (q) => q.lte("releasedAt", Date.now()))
.take(100);
// Good - boolean field updated by scheduled function
const posts = await ctx.db
.query("posts")
.withIndex("by_is_released", (q) => q.eq("isReleased", true))
.take(100);
写冲突规避(OCC)
使 mutation 幂等:
// Good - idempotent, early return if already done
export const completeTask = mutation({
args: { taskId: v.id("tasks") },
returns: v.null(),
handler: async (ctx, args) => {
const task = await ctx.db.get("tasks", args.taskId);
if (!task || task.status === "completed") return null; // Idempotent
await ctx.db.patch("tasks", args.taskId, { status: "completed" });
return null;
},
});
// Good - patch directly without reading when possible
export const updateNote = mutation({
args: { id: v.id("notes"), content: v.string() },
returns: v.null(),
handler: async (ctx, args) => {
await ctx.db.patch("notes", args.id, { content: args.content });
return null;
},
});
// Good - parallel updates with Promise.all
export const reorderItems = mutation({
args: { itemIds: v.array(v.id("items")) },
returns: v.null(),
handler: async (ctx, args) => {
await Promise.all(
args.itemIds.map((id, index) => ctx.db.patch("items", id, { order: index }))
);
return null;
},
});
使用方式
在编写或审查 Convex 数据库查询时,按上述模式应用索引、限制结果集、避免 .filter() 与 Date.now(),并采用幂等 mutation 规避写冲突。
适用场景
- 编写或审查 Convex 数据库查询
- 处理
.filter()与索引设计 - 优化查询性能与结果集大小
- 规避写冲突(OCC)
限制
资料未提供关于收费、价格、平台支持范围或具体效果保证的信息。
参考资料
- Indexes: https://docs.convex.dev/database/indexes
- Best Practices: https://docs.convex.dev/understanding/best-practices/