dannyeloD
Convex Community16mo ago
18 replies
dannyelo

Search Index by Two or More Fields

Hello, I'm trying to retrive a query using searchIndex.
I need it to query documents by two or more fields.

This is what I tried so far, but is only retriving results for legalName.

customers: defineTable({
  organizationId: v.id('organizations'),
  alias: v.string(),
  legalName: v.optional(v.string()),
  // ...rest of the fields...
})
  .index('by_organizationId', ['organizationId'])
  .searchIndex('search_legal_name', {
    searchField: 'legalName',
    filterFields: ['organizationId'],
  })
  .searchIndex('search_alias', {
    searchField: 'alias',
    filterFields: ['organizationId'],
  }),


export const getCustomersSearch = query({
  args: {
    search: v.string(),
  },
  handler: async (ctx, args) => {
    const currentOrganization = await getCurrentOrganization(ctx)
    let customers: Doc<'customers'>[] = []

    const byLegalName = await ctx.db
      .query('customers')
      .withSearchIndex('search_legal_name', (q) =>
        q
          .search('legalName', args.search)
          .eq('organizationId', currentOrganization._id),
      )
      .take(10)

    const byAlias = await ctx.db
      .query('customers')
      .withSearchIndex('search_alias', (q) =>
        q
          .search('alias', args.search)
          .eq('organizationId', currentOrganization._id),
      )
      .take(10)

    customers = [...byLegalName, ...byAlias]

    return await Promise.all(
      customers.map(async (customer) => transformCustomer(customer._id, ctx)),
    )
  },
})
Was this page helpful?