convex-queries
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseConvex Queries
Convex 查询
Query Pattern with Index
带索引的查询模式
typescript
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();
},
});typescript
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();
},
});Avoid .filter()
on Database Queries
.filter()避免在数据库查询中使用.filter()
.filter()Use instead - has same performance as filtering in code:
.withIndex().filter()typescript
// 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");Finding usage: Search with regex
.filter()\.filter\(\(?qException: Paginated queries benefit from .
.filter()请改用——的性能与在代码中过滤完全相同:
.withIndex().filter()typescript
// 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()Only Use .collect()
with Small Result Sets
.collect()仅在小结果集场景下使用.collect()
.collect()For 1000+ documents, use indexes, pagination, or limits:
typescript
// 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);当处理1000条以上文档时,请使用索引、分页或限制数量:
typescript
// 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);Index Configuration
索引配置
typescript
// 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"]),
});typescript
// 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"]),
});Check for Redundant Indexes
检查冗余索引
by_fooby_foo_and_barby_foo_and_bartypescript
// 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();Exception: is really + . Keep separate if you need that sort order.
by_foofoo_creationTimeby_fooby_foo_and_barby_foo_and_bartypescript
// 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_foofoo_creationTimeDon't Use Date.now()
in Queries
Date.now()不要在查询中使用Date.now()
Date.now()Queries don't re-run when changes:
Date.now()typescript
// 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);当的值变化时,查询不会重新执行:
Date.now()typescript
// 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);Write Conflict Avoidance (OCC)
写入冲突避免(乐观并发控制OCC)
Make mutations idempotent:
typescript
// 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;
},
});确保变更操作具有幂等性:
typescript
// 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;
},
});