dgraph的java api简单总结
目录
初始化客户端
public static DgraphClient initializeDgraphClient() {
// 创建连接通道
ManagedChannel channel =
ManagedChannelBuilder.forAddress("ip", 9080).usePlaintext().build();
// 把通道放入dgraphStub
DgraphGrpc.DgraphStub dgraphStub = DgraphGrpc.newStub(channel);
// 为所有请求设置超时时间
// ClientInterceptor clientInterceptor = new ClientInterceptor(){
// @Override
// public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT,
// RespT> method, CallOptions callOptions, Channel next) {
// return next.newCall(method, callOptions.withDeadlineAfter(500,
// TimeUnit.MILLISECONDS));
// }
// };
// dgraphStub.withInterceptors(clientInterceptor);
// 为单个请求设置超时时间
// dgraphClient.newTransaction().query(query, 500, TimeUnit.MILLISECONDS);
// 设置请求头
// Metadata metadata = new Metadata();
// metadata.put(
// Metadata.Key.of("auth-token", Metadata.ASCII_STRING_MARSHALLER),
// "the-auth-token-value");
// dgraphStub = MetadataUtils.attachHeaders(dgraphStub, metadata);
// 把dgraphStub放入客户端
DgraphClient dgraphClient = new DgraphClient(dgraphStub);
// 异步客户端
// DgraphAsyncClient dgraphAsyncClient = new DgraphAsyncClient();
// //关闭单个通道
// channel.shutdown();
// //关闭客户端所有通道
// dgraphClient.shutdown();
// 返回可用的客户端
return dgraphClient;
}
检查版本号
private static void checkVersion(DgraphClient dgraphClient) {
DgraphProto.Version version = dgraphClient.checkVersion();
String tag = version.getTag();
System.out.println(tag);
}
突变新增
/*
* 突变新增 只要uid相同就是修改
* */
private static void mutationInsert(DgraphClient dgraphClient) {
/*
//开启只读事务
Transaction transaction = dgraphClient.newReadOnlyTransaction();
//给只读事务设置尽力而为,尽力而为查询放宽了线性化读取的要求。当运行不需要最新时间戳结果的查询时,这很有用。
transaction.setBestEffort(true);
*
* */
// 开启事务
Transaction tc = dgraphClient.newTransaction();
try {
// 创建Person实体
Person xm = Person.builder().uid("12333").name("小刚").Sex("男").build();
// Person实体序列化
String xmStr = JSON.toJSONString(xm);
// 构造裂变操作
DgraphProto.Mutation build =
DgraphProto.Mutation.newBuilder().setSetJson(ByteString.copyFromUtf8(xmStr)).build();
// 构造请求
DgraphProto.Request request = DgraphProto.Request.newBuilder().addMutations(build).build();
// 事务提交请求
DgraphProto.Response response = tc.doRequest(request);
// 可获得uid
List<String> uidList = new ArrayList<String>(response.getUidsMap().values());
for (String s : uidList) {
System.out.println("uid======" + s);
}
// 提交事务
tc.commit();
} finally {
if (null != tc) {
// 丢弃事务
tc.discard();
}
}
}
查询
private static void query(DgraphClient dgraphClient) {
// 查询
String query =
"query all($name:string){\n"
+ " all(func: eq(name, $name)) {\n"
+ " name\n"
+ " }\n"
+ "}\n";
// 参数
Map<String, String> vars = Collections.singletonMap("$name", "小红");
// 请求
DgraphProto.Response response =
dgraphClient.newReadOnlyTransaction().queryWithVars(query, vars);
// 请求延迟
// DgraphProto.Latency latency = response.getLatency();
// 反序列化
Gson gson = new Gson();
People people = gson.fromJson(response.getJson().toStringUtf8(), People.class);
// 打印
System.out.printf("people found: %d\n", people.all.size());
for (Person person : people.all) {
System.out.println(person.getName());
}
}
使用RDF响应运行查询
/*
使用RDF响应运行查询
* 格式<0x2> <name> "Alice" .
<0x3> <name> "Alice" .
* */
private static void queryWithRDF(DgraphClient dgraphClient) {
// 查询语句
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");
// 发起请求
DgraphProto.Response response =
dgraphClient.newReadOnlyTransaction().queryRDFWithVars(query, vars);
// 打印Rdf
System.out.println(response.getRdf().toStringUtf8());
}
查询突变混合使用
/*
* 查询聚合
* */
private static void queryAndMutation(DgraphClient dgraphClient) {
// 开启事务
Transaction tc = dgraphClient.newTransaction();
// 定义查询语句
String query =
"query {\n" + "user as var(func: eq(email, \"wrong_email@dgraph.io\"))\n" + "}\n";
// 创建突变
DgraphProto.Mutation mu =
DgraphProto.Mutation.newBuilder()
.setSetNquads(
ByteString.copyFromUtf8("uid(user) <email> \"correct_email@dgraph.io\" ."))
.build();
// 构造请求
DgraphProto.Request request =
DgraphProto.Request.newBuilder()
.setQuery(query)
.addMutations(mu)
.setCommitNow(true)
.build();
// 提交请求
tc.doRequest(request);
}
根据条件突变
/*
* 条件突变
* */
private static void conditionalUpsert(DgraphClient dgraphClient) {
// 开启事务
Transaction tc = dgraphClient.newTransaction();
// 定义查询语句
String query =
"query {\n" + "user as var(func: eq(email, \"correct_email@dgraph.io\"))\n" + "}\n";
DgraphProto.Mutation mu =
DgraphProto.Mutation.newBuilder()
.setSetNquads(
ByteString.copyFromUtf8("uid(user) <email> \"wrong_email@dgraph.io\" ."))
// 设置条件
.setCond("@if(gt(len(user), 1))")
.build();
// 构造请求
DgraphProto.Request request =
DgraphProto.Request.newBuilder()
.setQuery(query)
.addMutations(mu)
// 设置立即提交
// .setCommitNow(true)
.build();
// 解析打印
DgraphProto.Response response = tc.doRequest(request);
System.out.println(response.getJson());
// 事务提交
tc.commit();
}
自由删除谓词
/*
* 自由删除谓词
* */
private static void deleteMultipleEdges(DgraphClient dgraphClient) {
// 创建事务
Transaction transaction = dgraphClient.newTransaction();
// 要删除谓词的uid
String uid = "0x271c";
// 创建聚变
DgraphProto.Mutation mu = DgraphProto.Mutation.newBuilder().build();
// 设置要删除的谓词 mu 巨变,uid uid,"age" 要删除的谓词
mu = Helpers.deleteEdges(mu, uid, "age");
// 构造请求
DgraphProto.Request build = DgraphProto.Request.newBuilder().addMutations(mu).build();
// 打印
DgraphProto.Response response = transaction.doRequest(build);
System.out.println(response.toString());
// 提交事务
transaction.commit();
}
按rdf格式创建朋友关系
/*
* 按rdf格式创建朋友关系
* */
public static void createFriendByRdf(DgraphClient dgraphClient) {
// 带\n换行的多行就是批量创建
// uid <friend> uid
String rdf = "<0x2> <friend> <0x3> .\n<0x3> <friend> <0x2711> .";
Transaction transaction = null;
try {
// 事务
transaction = dgraphClient.newTransaction();
// 构造聚变
DgraphProto.Mutation mutation =
DgraphProto.Mutation.newBuilder().setSetNquads(ByteString.copyFromUtf8(rdf)).build();
// 请求
transaction.mutate(mutation);
// 提交
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != transaction) {
// 丢弃事务
transaction.discard();
}
}
}