Skip to content

Commit f54ba7b

Browse files
authored
examples(latency): Add example to calculate client and server latency. (#50)
This is for CLOUD-260. This adds an example to get the client-side and the server-side latency of a query. The important bit is the following snippet: Client-side latency is calculated using `console.time` and `console.timeEnd` around a query call to capture the client-side latency. Server-side latency is calculated by Dgraph itself. This example prints it out from the query response `res.extensions.server_latency`. --- Example command and output: $ node index-async-await.js --addr https://$MY_DGRAPH_CLOUD_ENDPOINT --api-key $MY_API_KEY --drop-all Created person named "Alice" with uid = 0xbd All created nodes (map from blank node names to uids): blank-0 => 0xbd dg.3043386991.125 => 0xbe dg.3043386991.126 => 0xbf dg.3043386991.127 => 0xc0 Query: query all($a: string) { all(func: eq(name, $a)) { uid name age married loc dob friend { name age } school { name } } } Vars: { '$a': 'Alice' } Query client latency: 39.371ms Query server latency: {"parsing_ns":299313,"processing_ns":1606551,"encoding_ns":361067,"assign_timestamp_ns":1389885,"total_ns":3770262} Number of people named "Alice": 1 { uid: '0xbd', name: 'Alice', age: 26, married: true, loc: { type: 'Point', coordinates: [ 1.1, 2 ] }, dob: '1980-02-02T07:00:00Z', friend: [ { name: 'Bob', age: 24 }, { name: 'Charlie', age: 29 } ], school: [ { name: 'Crown Public School' } ] } DONE! The following flags are available in this example: * --addr: The Dgraph address. Can be a Dgraph Cloud endpoint following the instructions: https://github.com/dgraph-io/dgraph-js-http#create-a-client-for-dgraph-cloud-endpoint. Defaults to http://localhost:8080. * --api-key: The Dgraph Cloud API Key. Required if the --addr is a Dgraph Cloud endpoint. * --drop-all: Call DropAll on Dgraph before loading the data for this example.
1 parent e51a7d0 commit f54ba7b

File tree

2 files changed

+158
-0
lines changed

2 files changed

+158
-0
lines changed

examples/latency/index-async-await.js

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
const dgraph = require("dgraph-js-http");
2+
const minimist = require("minimist");
3+
4+
// Create a client stub.
5+
function newClientStub(addr) {
6+
return new dgraph.DgraphClientStub(addr);
7+
}
8+
9+
// Create a client.
10+
function newClient(clientStub, apiKey) {
11+
c = new dgraph.DgraphClient(clientStub);
12+
if (apiKey != "") {
13+
c.setSlashApiKey(apiKey);
14+
}
15+
return c;
16+
}
17+
18+
// Drop All - discard all data and start from a clean slate.
19+
async function dropAll(dgraphClient) {
20+
await dgraphClient.alter({ dropAll: true });
21+
}
22+
23+
// Set schema.
24+
async function setSchema(dgraphClient) {
25+
const schema = `
26+
name: string @index(exact) .
27+
age: int .
28+
married: bool .
29+
loc: geo .
30+
dob: datetime .
31+
`;
32+
await dgraphClient.alter({ schema: schema });
33+
}
34+
35+
// Create data using JSON.
36+
async function createData(dgraphClient) {
37+
// Create a new transaction.
38+
const txn = dgraphClient.newTxn();
39+
try {
40+
// Create data.
41+
const p = {
42+
uid: "_:blank-0",
43+
name: "Alice",
44+
age: 26,
45+
married: true,
46+
loc: {
47+
type: "Point",
48+
coordinates: [1.1, 2],
49+
},
50+
dob: new Date(1980, 1, 1, 23, 0, 0, 0),
51+
friend: [
52+
{
53+
name: "Bob",
54+
age: 24,
55+
},
56+
{
57+
name: "Charlie",
58+
age: 29,
59+
}
60+
],
61+
school: [
62+
{
63+
name: "Crown Public School",
64+
}
65+
]
66+
};
67+
68+
// Run mutation.
69+
const assigned = await txn.mutate({ setJson: p });
70+
71+
// Commit transaction.
72+
await txn.commit();
73+
74+
// Get uid of the outermost object (person named "Alice").
75+
// Assigned#getUidsMap() returns a map from blank node names to uids.
76+
// For a json mutation, blank node names "blank-0", "blank-1", ... are used
77+
// for all the created nodes.
78+
console.log(`Created person named "Alice" with uid = ${assigned.data.uids["blank-0"]}\n`);
79+
80+
console.log("All created nodes (map from blank node names to uids):");
81+
Object.keys(assigned.data.uids).forEach((key) => console.log(`${key} => ${assigned.data.uids[key]}`));
82+
console.log();
83+
} finally {
84+
// Clean up. Calling this after txn.commit() is a no-op
85+
// and hence safe.
86+
await txn.discard();
87+
}
88+
}
89+
90+
// Query for data.
91+
// This function also logs the client-side and server-side latency for running the query.
92+
async function queryData(dgraphClient) {
93+
// Run query.
94+
const query = `query all($a: string) {
95+
all(func: eq(name, $a)) {
96+
uid
97+
name
98+
age
99+
married
100+
loc
101+
dob
102+
friend {
103+
name
104+
age
105+
}
106+
school {
107+
name
108+
}
109+
}
110+
}`;
111+
const vars = { $a: "Alice" };
112+
113+
console.log("Query:", query.replace(/[\t\n ]+/gm, " "), "Vars:", vars);
114+
console.time('Query client latency');
115+
const res = await dgraphClient.newTxn().queryWithVars(query, vars);
116+
console.timeEnd('Query client latency');
117+
console.log("Query server latency:", JSON.stringify(res.extensions.server_latency));
118+
119+
const ppl = res.data;
120+
121+
// Print results.
122+
console.log(`Number of people named "Alice": ${ppl.all.length}`);
123+
ppl.all.forEach((person) => console.log(person));
124+
return res;
125+
}
126+
127+
async function main() {
128+
const args = minimist(process.argv.slice(2), {
129+
string: 'addr',
130+
string: 'api-key',
131+
boolean: 'drop-all',
132+
default: {
133+
'addr': 'http://localhost:8080'
134+
},
135+
alias: { apiKey: 'api-key', dropAll: 'drop-all' }
136+
});
137+
const dgraphClientStub = newClientStub(args.addr);
138+
const dgraphClient = newClient(dgraphClientStub, args.apiKey);
139+
if (args.dropAll) {
140+
await dropAll(dgraphClient);
141+
}
142+
await setSchema(dgraphClient);
143+
await createData(dgraphClient);
144+
await queryData(dgraphClient);
145+
}
146+
147+
main().then(() => {
148+
console.log("\nDONE!");
149+
}).catch((e) => {
150+
console.log("ERROR: ", e);
151+
});

examples/latency/package.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"name": "latency",
3+
"dependencies": {
4+
"dgraph-js-http": "^21.3.0",
5+
"minimist": "^1.2.5"
6+
}
7+
}

0 commit comments

Comments
 (0)