Based on your previous question about pagination with filtering, I understand you're now looking for ways to search across multiple fields using Convex's ctx.db.query. There are several approaches to this in Convex:
Using Filter with OR Conditions
You can use the filter method with q.or to search across multiple fields:
const results = await ctx.db
.query("users")
.filter((q) =>
q.or(
q.eq(q.field("name"), searchTerm),
q.eq(q.field("email"), searchTerm)
)
)
.collect();
For partial matches, you can use string operations:
const results = await ctx.db
.query("users")
.filter((q) =>
q.or(
q.field("name").includes(searchTerm),
q.field("email").includes(searchTerm)
)
)
.collect();
Using Full Text Search
For more powerful text searching, you can use Convex's full-text search capabilities:
- First, define a search index in your schema:
export default defineSchema({
users: defineTable({
name: v.string(),
email: v.string(),
}).searchIndex("search_name", {
searchField: "name",
}).searchIndex("search_email", {
searchField: "email",
}),
});
- Then query using these search indexes:
const nameResults = await ctx.db
.query("users")
.withSearchIndex("search_name", (q) => q.search("name", searchTerm))
.collect();
const emailResults = await ctx.db
.query("users")
.withSearchIndex("search_email", (q) => q.search("email", searchTerm))
.collect();
Note that you can't directly combine multiple search indexes in a single query. You would need to run separate queries and merge the results in your code.
Using a Calculated Field
Another approach is to create a calculated field that combines multiple fields: