#search index order creationtime

3 messages · Page 1 of 1 (latest)

steep latch
#

how can i order by creation time when using withSearchIndex

  public static async listByName({
    ctx,
    paginationOpts,
    search,
  }: {
    ctx: QueryCtx;
    paginationOpts: PaginationOptions;
    search?: string;
  }) {
    return await (
      search
        ? ctx.db.query("projects").withSearchIndex("search_name", (q) => q.search("name", search))
        : ctx.db.query("projects")
    ).paginate(paginationOpts);
  }
hushed hingeBOT
#

Hi @steep latch. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can’t change the sort order of a search index query: results from .withSearchIndex are always returned in relevance order, and the docs explicitly say you can’t override that with another order (e.g. by _creationTime). [Search queries; withSearchIndex]

So you have two options:

  1. No search term → order by _creationTime
    This already works: a plain ctx.db.query("projects") is ordered by _creationTime by default, and you can make it explicit:

    return await (
      search
        ? ctx.db
            .query("projects")
            .withSearchIndex("search_name", q => q.search("name", search))
        : ctx.db
            .query("projects")
            .order("desc") // or "asc"
    ).paginate(paginationOpts);
    
  2. With search term → you must accept relevance order
    There’s no supported way (in the docs) to have .withSearchIndex and then re‑order by _creationTime. You can only add extra .filter conditions, not change the ordering. [Search queries]

If you absolutely need “search by name, then sort by creation time”, the knowledge sources only mention workarounds at a high level (e.g. fetching results and sorting in JS, or using an external search service), but they don’t provide an official Convex pattern that preserves both perfect relevance and _creationTime ordering for large datasets.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: