在深入 了解Dgraph 之前,我们先了解下开发环境,毕竟让开发人员真正动起手来才是第一步。
Dgraph 支持很多种语言的开发,包括GO,Python,JS,C#和Java等等。出于项目需要,只了解下JS和Java。
1、NodeJS 开发
首先要说一下,js 有两个库,一个gRPC JS Client,一个HTTP JS Client。这里只以http 为例,http也是我们更熟悉的使用方式。
1.1 、demo 下载
链接:https://pan.baidu.com/s/1GCY-dMkHogsVX6mPv3ioqg
提取码:jzvt
下载该链接的nodejs-http
1.2、 运行demo
首先用vscode 打开,安装 ,直接npm install 实现安装。
npm install
修改Dgraph的地址,这给地址一定要改成自己的服务地址
用node 执行上面的js 代码,在demo里面如下执行
node index-promise.js
看到下面信息,表示执行成功
可以用Ratel UI 去查看,可以看到刚才加入的内容
1.3 、讲解
先看下 package.json, node 安装了一个dgraph-js-http的库,正是因为这个库,我们可以用nodejs开发。这个库是开源的,可以去官方下载。
1.3.1、看下完整的demo代码
const dgraph = require("dgraph-js-http");
// Create a client stub.
function newClientStub() {
return new dgraph.DgraphClientStub("http://10.10.10.215:8080");
}
// Create a client.
function newClient(clientStub) {
return new dgraph.DgraphClient(clientStub);
}
// Drop All - discard all data and start from a clean slate.
function dropAll(dgraphClient) {
return dgraphClient.alter({ dropAll: true });
}
// Set schema.
function setSchema(dgraphClient) {
const schema = `
name: string @index(exact) .
age: int .
married: bool .
loc: geo .
dob: datetime .
`;
return dgraphClient.alter({ schema: schema });
}
// Create data using JSON.
function createData(dgraphClient) {
// Create a new transaction.
const txn = dgraphClient.newTxn();
// Create data.
const p = {
name: "Alice",
age: 26,
married: true,
loc: {
type: "Point",
coordinates: [1.1, 2],
},
dob: new Date(1980, 1, 1, 23, 0, 0, 0),
friend: [
{
name: "Bob",
age: 24,
},
{
name: "Charlie",
age: 29,
}
],
school: [
{
name: "Crown Public School",
}
]
};
let assigned;
let err;
// Run mutation.
return txn.mutate({ setJson: p }).then((res) => {
assigned = res;
// Commit transaction.
return txn.commit();
}).then(() => {
// Get uid of the outermost object (person named "Alice").
// Assigned#getUidsMap() returns a map from blank node names to uids.
// For a json mutation, blank node names "blank-0", "blank-1", ... are used
// for all the created nodes.
console.log(`Created person named "Alice" with uid = ${assigned.data.uids["blank-0"]}\n`);
console.log("All created nodes (map from blank node names to uids):");
for (let key in assigned.data.uids) {
if (Object.hasOwnProperty(assigned.data.uids, key)) {
console.log(`${key}: ${assigned.data.uids[key]}`);
}
}
console.log();
}).catch((e) => {
err = e;
}).then(() => {
return txn.discard();
}).then(() => {
if (err != null) {
throw err;
}
});
}
// Query for data.
function queryData(dgraphClient) {
// Run query.
const query = `query all($a: string) {
all(func: eq(name, $a)) {
uid
name
age
married
loc
dob
friend {
name
age
}
school {
name
}
}
}`;
console.log(query);
const vars = { $a: "Alice" };
return dgraphClient.newTxn().queryWithVars(query, vars).then((res) => {
const ppl = res.data;
// Print results.
console.log(`Number of people named "Alice": ${ppl.all.length}`);
for (let i = 0; i < ppl.all.length; i++) {
console.log(ppl.all[i]);
}
});
}
function main() {
const dgraphClientStub = newClientStub();
const dgraphClient = newClient(dgraphClientStub);
return dropAll(dgraphClient).then(() => {
return setSchema(dgraphClient);
}).then(() => {
return createData(dgraphClient);
}).then(() => {
return queryData(dgraphClient);
});
}
main().then(() => {
console.log("\nDONE!");
}).catch((e) => {
console.log("ERROR: ", e);
});
还有异步代码 ,请查看demo。
1.3.2 、链接服务端
用如下代码
const dgraph = require("dgraph-js-http");
const clientStub = new dgraph.DgraphClientStub(
// addr: optional, default: "http://localhost:8080"
"http://localhost:8080",
// legacyApi: optional, default: false. Set to true when connecting to Dgraph v1.0.x
false,
);
const dgraphClient = new dgraph.DgraphClient(clientStub);
1.3.3 、操作Schema
用下面的代码去更新Schema
const schema = "name: string @index(exact) .";
await dgraphClient.alter({ schema: schema });
比如在demo中
// Set schema.
function setSchema(dgraphClient) {
const schema = `
name: string @index(exact) .
age: int .
married: bool .
loc: geo .
dob: datetime .
`;
return dgraphClient.alter({ schema: schema });
}
1.3.4、操作数据
用mutate 函数操作数据,可以在demo中找到类似代码
// Create data.
const p = {
name: "Alice",
};
// Run mutation.
await txn.mutate({ setJson: p });
1.3.5、查询数据
可以用变量去拼查询语句。比如变量 $a。
query all($a: string) {
all(func: eq(name, $a))
{
name
}
}
其他的方式请查看对应的API
2、Java的开发
2.1、demo的下载
链接:https://pan.baidu.com/s/1GCY-dMkHogsVX6mPv3ioqg
提取码:jzvt
下载该链接的DraphJavaSample
注意我们用的是官方的gPRC框架,这个框架不需要安装Idea软件。如果用Spring boot 和Idea软件,只需要参考App.java的内容即可。
2.2、运行demo
首先要装好java 版本,最好是java 9以上的
用vscode 打开,修改ip和端口号
运行
./gradlew run
出现如下代码表示运行成功
2.3、讲解
2.3.1、链接服务端
下面代码演示了链接方法
ManagedChannel channel1 = ManagedChannelBuilder
.forAddress("localhost", 9080)
.usePlaintext().build();
DgraphStub stub1 = DgraphGrpc.newStub(channel1);
2.3.2 、操作Schema
增加一个name的Shema
String schema = "name: string @index(exact) .";
Operation operation = Operation.newBuilder()
.setSchema(schema)
.setRunInBackground(true)
.build();
dgraphClient.alter(operation);
2.3.3、操作数据
演示了用一个Person的对象去操作数据
String schema = "name: string @index(exact) .";
Operation operation = Operation.newBuilder()
.setSchema(schema)
.setRunInBackground(true)
.build();
dgraphClient.alter(operation);
2.3.4、查询数据
// Query
String query =
"query all($a: string){\n" +
" all(func: eq(name, $a)) {\n" +
" name\n" +
" }\n" +
"}\n";
Map<String, String> vars = Collections.singletonMap("$a", "Alice");
Response response = dgraphClient.newReadOnlyTransaction().queryWithVars(query, vars);
// Deserialize
People ppl = gson.fromJson(response.getJson().toStringUtf8(), People.class);
// Print results
System.out.printf("people found: %d\n", ppl.all.size());
ppl.all.forEach(person -> System.out.println(person.name));
3、总结
本章主要介绍了NodeJS和Java对Dgraph的常用操作逻辑。对Dgraph的操作分同步和异步的,本文以同步为例子,做了加单介绍,对于异步只是Api的调用方式不一样,在此不做详细介绍了。其他语言的调用方式其实大通小异,需要使用的可以去官方看教程。