How to sort GraphQL query results

Is there a way to either create both a collection and sorted index via GraphQL schema import, or update an existing GraphQL schema to enable queries utilizing the sorted index? Our wish is to utilize the sorted index to sort query results for a specific collection.

1 Like

Hi, @cjwooo!

At the moment, it is not possible to define sorting during the schema definition (i.e., when importing the schema). For further info about possible future implementations on sorting, see Sorting in autogenerated GraphQL queries.

Alternatively, the @index directive cannot currently be used for a sorted Index directly either since it does not work with Indexes that define a specific set of values (this is required for establishing sorting when creating an Index). For further info, see Allow @index directive to work with Indexes defining values other than All.

That being said, you can use the @resolver directive and create a UDF that calls the sorted Index within it.

Below there’s a comprehensive example for doing so:

1. Import schema:

type Post {
  title: String!
  content: String!
}

type Query {
  allPostsSortedByTitle: [Post!]! @resolver(name: "all_posts_sorted_by_title", paginated: true)
}

2. Create index

CreateIndex(
  {
    "name": "all_posts_sorted_by_title",
    "source": Collection("Post"),
    "terms": [],
    "values": [
      {
        "field": [
          "data",
          "title"
        ]
      },
      {
        "field": [
          "ref"
        ]
      }
    ],
  }
);

3. Update UDF:

Update(
  Function("all_posts_sorted_by_title"),
  {
    body: Query(Lambda(["size", "after", "before"],
      Let(
        {
          match: Match(Index("all_posts_sorted_by_title")),
          page: If(
            Equals(Var("before"), null),
            If(
              Equals(Var("after"), null),
                Paginate(Var("match"), { size: Var("size") }),
                Paginate(Var("match"), { size: Var("size"), after: Var("after") })
            ),
            Paginate(Var("match"), { size: Var("size"), before: Var("before") }),
          )
        },
        Map(Var("page"), Lambda("values", Get(Select(1, Var("values")))))
      )
    ))
  }
)

Let me know if it works for you! Thank you!

1 Like

it would be great if fauna would support filtering/sorting via GraphQL without having to resort to a custom resolver

1 Like