Report Issue Edit Page

GraphQL Variables

Variables can be defined and used in queries which helps in query reuse and avoids costly string building in clients at runtime by passing a separate variable map. A variable starts with a $ symbol. For HTTP requests with GraphQL Variables, we must use Content-Type: application/json header and pass data with a JSON object containing query and variables.

curl -H "Content-Type: application/json" localhost:8080/query -XPOST -d $'{
  "query": "query test($a: string) { test(func: eq(name, $a)) { \n uid \n name \n } }",
  "variables": { "$a": "Alice" }
}' | python -m json.tool | less
query test($a: int, $b: int, $name: string) {
  me(func: allofterms([email protected], $name)) {
    [email protected]
    director.film (first: $a, offset: $b) {
      name @en
      genre(first: $a) {
        [email protected]
      }
    }
  }
}
curl -H "Content-Type: application/json" localhost:8080/query -XPOST -d '{
    "query": "blahblah",
    "variables": {"$a": "5", "$b": "10", "$name": "Steven Spielberg"}
}' | python -m json.tool | less
        
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
    
	"github.com/dgraph-io/dgo/v2"
	"github.com/dgraph-io/dgo/v2/protos/api"
    
	"google.golang.org/grpc"
)

var (
	dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph Alpha address")
)

func main() {
	flag.Parse()
	conn, err := grpc.Dial(*dgraph, grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	dg := dgo.NewDgraphClient(api.NewDgraphClient(conn))
    
	resp, err := dg.NewTxn().QueryWithVars(context.Background(), `blahblah`, map[string]string{"$a": "5", "$b": "10", "$name": "Steven Spielberg"})
    
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Response: %s\n", resp.Json)
}
import com.google.common.collect.ImmutableMap;
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphGrpc.DgraphStub;
import io.dgraph.DgraphProto.Response;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.Map;

public class App {

    public static void main(final String[] args) {
        ManagedChannel channel =
            ManagedChannelBuilder.forAddress("localhost", 9080).usePlaintext(true).build();
        DgraphStub stub = DgraphGrpc.newStub(channel);
        DgraphClient dgraphClient = new DgraphClient(stub);

        String query = "blahblah";

    
        Map<String, String> vars = ImmutableMap.of("$a", "5", "$b", "10", "$name", "Steven Spielberg");
        Response res = dgraphClient.newTransaction().queryWithVars(query, vars);
    
        System.out.printf("Response: %s", res.getJson().toStringUtf8());
    }
}

import pydgraph
import json

def main():
    client_stub = pydgraph.DgraphClientStub("localhost:9080")
    client = pydgraph.DgraphClient(client_stub)
    query = """blahblah"""
    variables = {"$a": "5", "$b": "10", "$name": "Steven Spielberg"}
    res = client.txn(read_only=True).query(query, variables=variables)
    print('Response: {}'.format(json.loads(res.json)))

    client_stub.close()


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print('Error: {}'.format(e))

const dgraph = require("dgraph-js");
const grpc = require("grpc");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("localhost:9080", grpc.credentials.createInsecure());
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const vars = {"$a": "5", "$b": "10", "$name": "Steven Spielberg"};
  const response = await dgraphClient.newTxn().queryWithVars(query, vars);
  console.log("Response: ", JSON.stringify(response.getJson()));

  clientStub.close();
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
const dgraph = require("dgraph-js-http");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("http://localhost:8080");
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const vars = {"$a": "5", "$b": "10", "$name": "Steven Spielberg"};
  const response = await dgraphClient.newTxn().queryWithVars(query, vars);
  console.log("Response: ", JSON.stringify(response.data));
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
Response
  • Variables can have default values. In the example below, $a has a default value of 2. Since the value for $a isn’t provided in the variable map, $a takes on the default value.
  • Variables whose type is suffixed with a ! can’t have a default value but must have a value as part of the variables map.
  • The value of the variable must be parsable to the given type, if not, an error is thrown.
  • The variable types that are supported as of now are: int, float, bool and string.
  • Any variable that is being used must be declared in the named query clause in the beginning.
query test($a: int = 2, $b: int!, $name: string) {
  me(func: allofterms([email protected], $name)) {
    director.film (first: $a, offset: $b) {
      genre(first: $a) {
        [email protected]
      }
    }
  }
}
curl -H "Content-Type: application/json" localhost:8080/query -XPOST -d '{
    "query": "blahblah",
    "variables": {"$b": "10", "$name": "Steven Spielberg"}
}' | python -m json.tool | less
        
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
    
	"github.com/dgraph-io/dgo/v2"
	"github.com/dgraph-io/dgo/v2/protos/api"
    
	"google.golang.org/grpc"
)

var (
	dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph Alpha address")
)

func main() {
	flag.Parse()
	conn, err := grpc.Dial(*dgraph, grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	dg := dgo.NewDgraphClient(api.NewDgraphClient(conn))
    
	resp, err := dg.NewTxn().QueryWithVars(context.Background(), `blahblah`, map[string]string{"$b": "10", "$name": "Steven Spielberg"})
    
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Response: %s\n", resp.Json)
}
import com.google.common.collect.ImmutableMap;
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphGrpc.DgraphStub;
import io.dgraph.DgraphProto.Response;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.Map;

public class App {

    public static void main(final String[] args) {
        ManagedChannel channel =
            ManagedChannelBuilder.forAddress("localhost", 9080).usePlaintext(true).build();
        DgraphStub stub = DgraphGrpc.newStub(channel);
        DgraphClient dgraphClient = new DgraphClient(stub);

        String query = "blahblah";

    
        Map<String, String> vars = ImmutableMap.of("$b", "10", "$name", "Steven Spielberg");
        Response res = dgraphClient.newTransaction().queryWithVars(query, vars);
    
        System.out.printf("Response: %s", res.getJson().toStringUtf8());
    }
}

import pydgraph
import json

def main():
    client_stub = pydgraph.DgraphClientStub("localhost:9080")
    client = pydgraph.DgraphClient(client_stub)
    query = """blahblah"""
    variables = {"$b": "10", "$name": "Steven Spielberg"}
    res = client.txn(read_only=True).query(query, variables=variables)
    print('Response: {}'.format(json.loads(res.json)))

    client_stub.close()


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print('Error: {}'.format(e))

const dgraph = require("dgraph-js");
const grpc = require("grpc");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("localhost:9080", grpc.credentials.createInsecure());
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const vars = {"$b": "10", "$name": "Steven Spielberg"};
  const response = await dgraphClient.newTxn().queryWithVars(query, vars);
  console.log("Response: ", JSON.stringify(response.getJson()));

  clientStub.close();
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
const dgraph = require("dgraph-js-http");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("http://localhost:8080");
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const vars = {"$b": "10", "$name": "Steven Spielberg"};
  const response = await dgraphClient.newTxn().queryWithVars(query, vars);
  console.log("Response: ", JSON.stringify(response.data));
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
Response

You can also use array with GraphQL Variables.

query test($a: int = 2, $b: int!, $aName: string, $bName: string) {
  me(func: eq([email protected], [$aName, $bName])) {
    director.film (first: $a, offset: $b) {
      genre(first: $a) {
        [email protected]
      }
    }
  }
}
curl -H "Content-Type: application/json" localhost:8080/query -XPOST -d '{
    "query": "blahblah",
    "variables": {"$b": "10", "$aName": "Steven Spielberg", "$bName": "Quentin Tarantino"}
}' | python -m json.tool | less
        
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
    
	"github.com/dgraph-io/dgo/v2"
	"github.com/dgraph-io/dgo/v2/protos/api"
    
	"google.golang.org/grpc"
)

var (
	dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph Alpha address")
)

func main() {
	flag.Parse()
	conn, err := grpc.Dial(*dgraph, grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	dg := dgo.NewDgraphClient(api.NewDgraphClient(conn))
    
	resp, err := dg.NewTxn().QueryWithVars(context.Background(), `blahblah`, map[string]string{"$b": "10", "$aName": "Steven Spielberg", "$bName": "Quentin Tarantino"})
    
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Response: %s\n", resp.Json)
}
import com.google.common.collect.ImmutableMap;
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphGrpc.DgraphStub;
import io.dgraph.DgraphProto.Response;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.Map;

public class App {

    public static void main(final String[] args) {
        ManagedChannel channel =
            ManagedChannelBuilder.forAddress("localhost", 9080).usePlaintext(true).build();
        DgraphStub stub = DgraphGrpc.newStub(channel);
        DgraphClient dgraphClient = new DgraphClient(stub);

        String query = "blahblah";

    
        Map<String, String> vars = ImmutableMap.of("$b", "10", "$aName", "Steven Spielberg", "$bName", "Quentin Tarantino");
        Response res = dgraphClient.newTransaction().queryWithVars(query, vars);
    
        System.out.printf("Response: %s", res.getJson().toStringUtf8());
    }
}

import pydgraph
import json

def main():
    client_stub = pydgraph.DgraphClientStub("localhost:9080")
    client = pydgraph.DgraphClient(client_stub)
    query = """blahblah"""
    variables = {"$b": "10", "$aName": "Steven Spielberg", "$bName": "Quentin Tarantino"}
    res = client.txn(read_only=True).query(query, variables=variables)
    print('Response: {}'.format(json.loads(res.json)))

    client_stub.close()


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print('Error: {}'.format(e))

const dgraph = require("dgraph-js");
const grpc = require("grpc");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("localhost:9080", grpc.credentials.createInsecure());
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const vars = {"$b": "10", "$aName": "Steven Spielberg", "$bName": "Quentin Tarantino"};
  const response = await dgraphClient.newTxn().queryWithVars(query, vars);
  console.log("Response: ", JSON.stringify(response.getJson()));

  clientStub.close();
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
const dgraph = require("dgraph-js-http");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("http://localhost:8080");
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const vars = {"$b": "10", "$aName": "Steven Spielberg", "$bName": "Quentin Tarantino"};
  const response = await dgraphClient.newTxn().queryWithVars(query, vars);
  console.log("Response: ", JSON.stringify(response.data));
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
Response

We also support variable substituion in facets now.

query test($name: string = "Alice") {
  data(func: eq(name, $name)) {
    friend @facets(eq(close, true)) {
      name
    }
  }
}
curl -H "Content-Type: application/json" localhost:8080/query -XPOST -d '{
    "query": "blahblah",
    "variables": {"$name": "Alice"}
}' | python -m json.tool | less
        
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
    
	"github.com/dgraph-io/dgo/v2"
	"github.com/dgraph-io/dgo/v2/protos/api"
    
	"google.golang.org/grpc"
)

var (
	dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph Alpha address")
)

func main() {
	flag.Parse()
	conn, err := grpc.Dial(*dgraph, grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	dg := dgo.NewDgraphClient(api.NewDgraphClient(conn))
    
	resp, err := dg.NewTxn().QueryWithVars(context.Background(), `blahblah`, map[string]string{"$name": "Alice"})
    
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Response: %s\n", resp.Json)
}
import com.google.common.collect.ImmutableMap;
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphGrpc.DgraphStub;
import io.dgraph.DgraphProto.Response;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.Map;

public class App {

    public static void main(final String[] args) {
        ManagedChannel channel =
            ManagedChannelBuilder.forAddress("localhost", 9080).usePlaintext(true).build();
        DgraphStub stub = DgraphGrpc.newStub(channel);
        DgraphClient dgraphClient = new DgraphClient(stub);

        String query = "blahblah";

    
        Map<String, String> vars = ImmutableMap.of("$name", "Alice");
        Response res = dgraphClient.newTransaction().queryWithVars(query, vars);
    
        System.out.printf("Response: %s", res.getJson().toStringUtf8());
    }
}

import pydgraph
import json

def main():
    client_stub = pydgraph.DgraphClientStub("localhost:9080")
    client = pydgraph.DgraphClient(client_stub)
    query = """blahblah"""
    variables = {"$name": "Alice"}
    res = client.txn(read_only=True).query(query, variables=variables)
    print('Response: {}'.format(json.loads(res.json)))

    client_stub.close()


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print('Error: {}'.format(e))

const dgraph = require("dgraph-js");
const grpc = require("grpc");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("localhost:9080", grpc.credentials.createInsecure());
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const vars = {"$name": "Alice"};
  const response = await dgraphClient.newTxn().queryWithVars(query, vars);
  console.log("Response: ", JSON.stringify(response.getJson()));

  clientStub.close();
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
const dgraph = require("dgraph-js-http");

async function main() {
  const clientStub = new dgraph.DgraphClientStub("http://localhost:8080");
  const dgraphClient = new dgraph.DgraphClient(clientStub);

  const query = `blahblah`;
  const vars = {"$name": "Alice"};
  const response = await dgraphClient.newTxn().queryWithVars(query, vars);
  console.log("Response: ", JSON.stringify(response.data));
}

main().then().catch((e) => {
  console.log("ERROR: ", e);
});
Response

Note If you want to input a list of uids as a GraphQL variable value, you can have the variable as string type and have the value surrounded by square brackets like ["13", "14"].