Sorting
Syntax Examples:
q(func: ..., orderasc: predicate)
q(func: ..., orderdesc: val(varName))
predicate (orderdesc: predicate) { ... }
predicate @filter(...) (orderasc: N) { ... }
q(func: ..., orderasc: predicate1, orderdesc: predicate2)
Sortable Types: int
, float
, String
, dateTime
, default
Results can be sorted in ascending order (orderasc
) or descending order (orderdesc
) by a predicate or variable.
For sorting on predicates with sortable indices, Dgraph sorts on the values and with the index in parallel and returns whichever result is computed first.
null
values at the end of the results, irrespective of their sort. This behavior is consistent across indexed and non-indexed sorts.
Query Example: French director Jean-Pierre Jeunet’s movies sorted by release date.
{
me(func: allofterms(name@en, "Jean-Pierre Jeunet")) {
name@fr
director.film(orderasc: initial_release_date) {
name@fr
name@en
initial_release_date
}
}
}
curl -H "Content-Type: application/dql" localhost:8080/query -XPOST -d '
blahblah' | 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().Query(context.Background(), `blahblah`)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Response: %s\n", resp.Json)
}
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";
Response res = dgraphClient.newTransaction().query(query);
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"""
res = client.txn(read_only=True).query(query)
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 response = await dgraphClient.newTxn().query(query);
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 response = await dgraphClient.newTxn().query(query);
console.log("Response: ", JSON.stringify(response.data));
}
main().then().catch((e) => {
console.log("ERROR: ", e);
});
Sorting can be performed at root and on value variables.
Query Example: All genres sorted alphabetically and the five movies in each genre with the most genres.
{
genres as var(func: has(~genre)) {
~genre {
numGenres as count(genre)
}
}
genres(func: uid(genres), orderasc: name@en) {
name@en
~genre (orderdesc: val(numGenres), first: 5) {
name@en
genres : val(numGenres)
}
}
}
curl -H "Content-Type: application/dql" localhost:8080/query -XPOST -d '
blahblah' | 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().Query(context.Background(), `blahblah`)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Response: %s\n", resp.Json)
}
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";
Response res = dgraphClient.newTransaction().query(query);
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"""
res = client.txn(read_only=True).query(query)
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 response = await dgraphClient.newTxn().query(query);
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 response = await dgraphClient.newTxn().query(query);
console.log("Response: ", JSON.stringify(response.data));
}
main().then().catch((e) => {
console.log("ERROR: ", e);
});
Sorting can also be performed by multiple predicates as shown below. If the values are equal for the first predicate, then they are sorted by the second predicate and so on.
Query Example: Find all nodes which have type Person, sort them by their first_name and among those that have the same first_name sort them by last_name in descending order.
{
me(func: type("Person"), orderasc: first_name, orderdesc: last_name) {
first_name
last_name
}
}