We’re overhauling Dgraph’s docs to make them clearer and more approachable. If you notice any issues during this transition or have suggestions, please let us know.

Schema

To set up a lambda query, first you need to define it on your GraphQL schema by using the @lambda directive.

get, query, and aggregate are reserved prefixes and they can’t be used to define Lambda queries.

For example, to define a lambda query for Author that finds out authors given an author’s name:

type Author {
  id: ID!
  name: String! @search(by: [hash, trigram])
  dob: DateTime
  reputation: Float
}

type Query {
  authorsByName(name: String!): [Author] @lambda
}

Resolver

Once the schema is ready, you can define your JavaScript query function and add it as resolver in your JS source code. To add the resolver you can use either the addGraphQLResolvers or addMultiParentGraphQLResolvers methods.

A Lambda Query resolver can use a combination of parents, args, dql, or graphql inside the function.

This example uses dql for the resolver function. You can find additional resolver examples using parent in the Lambda fields article, and using graphql in the Lambda mutations article.

For example, to define the JavaScript authorsByName() lambda function and add it as resolver:

async function authorsByName({ args, dql }) {
  const results = await dql.query(
    `query queryAuthor($name: string) {
        queryAuthor(func: type(Author)) @filter(eq(Author.name, $name)) {
            name: Author.name
            dob: Author.dob
            reputation: Author.reputation
        }
    }`,
    { $name: args.name },
  )
  return results.data.queryAuthor
}

self.addGraphQLResolvers({
  "Query.authorsByName": authorsByName,
})

Example

Finally, if you execute this lambda query

query {
  authorsByName(name: "Ann Author") {
    name
    dob
    reputation
  }
}

You should see a response such as

{
  "authorsByName": [
    {
      "name": "Ann Author",
      "dob": "2000-01-01T00:00:00Z",
      "reputation": 6.6
    }
  ]
}