alixi
alixi•8mo ago

How nested are the fields you are

How nested are the fields you are searching inside the object? one possible approach might be to normalize your data more
7 Replies
Hmza
Hmza•8mo ago
mainPhoneNumber: v.string(), if i have to search this i can do q = q.filter((q) => q.eq(q.field("mainPhoneNumber"), args.phone)); lets say this phoneNumbers: v.array(v.object({type: v.string(),number: v.string(),})), now in my head i can do q.eleMatch or just try filter with phoneNumbers.number which in case of trpc works. but not in convex. i didn't explore more q. functions though. if you know, i'm happy to listen carefully! 🙂
lee
lee•8mo ago
there's an equally-efficient alternative to .filter which allows you to do this (which is to say, neither are efficient and indexes are more efficient) https://stack.convex.dev/complex-filters-in-convex
Stack
Using TypeScript to Write Complex Query Filters
There’s a new Convex helper to perform generic TypeScript filters, with the same performance as built-in Convex filters, and unlimited potential.
Hmza
Hmza•8mo ago
ah, thanks lee. will you still suggestion in-memory filtering in convex ts file though? because this works perfectly for me , but obviously i'm fetching all clients from database here. (i can have filters to cut that down though ) const clients = await ctx.db.query("clients").collect(); const phoneNumberExists = clients.some(client => client.phoneNumbers.some(phone => phone.number === phoneNumber) );
lee
lee•8mo ago
as long as you don't have many clients, this looks great to me. if you have many clients, filters won't help; you need indexes
Hmza
Hmza•8mo ago
gotcha! i am obviously not going to hurt the db to get all clients. there will be thousands. i'll cut the initial query down and ofcourse, i'm on the line to do indexes because i also want to explore the vector and db search later! thanks
lee
lee•8mo ago
great! The doc mentioned above describes how to do the filter you want using indexes, btw
Hmza
Hmza•8mo ago
return await filter(clientsQuery, (client) =>client.mainPhoneNumber === args.phone || client.phoneNumbers.some(p => p.number === args.phone)).collect(); beautifully works! i'll be handling indexes seperately later. thanks again!

Did you find this page helpful?