Java 中的 Dgraph。如何运行原始字符串突变查询?

Dgraph in Java. How to run raw string mutation query?

我需要能够在不使用 newBuilder() 的情况下 运行 原始字符串突变查询:

Gson gson = new Gson();
String json = gson.toJson(newEmployer);
Transaction newTransaction = this.dgraphClient.newTransaction();
Mutation mu = Mutation.newBuilder().setSetJson(ByteString.copyFromUtf8(json.toString())).build();
newTransaction.mutate(mu);

我想运行:

String email = "ba@a.aa";
String userType = "JOB_SEEKER";
Transaction newTransaction = this.dgraphClient.newTransaction();
String query = 
        "{\n" +
        "    set { \n" +
        "       _:user <label> \"USER\" . \n" +
        "      _:user <userType> \"" + email + "\" . \n" +
        "      _:user <email> \"" + userType + "\" . \n" +
        "    }\n" +
        "}";
Mutation mu = Mutation.parseFrom(ByteString.copyFromUtf8(query));
newTransaction.mutate(mu);

但我在 运行 时收到错误消息:"While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either that the input has been truncated or that an embedded message misreported its own length."

在 gRPC 客户端(例如 dgraph4j)中为突变设置 N-Quad 三元组时,您只需指定 newline-separated 三元组本身并将它们传递给 Mutation#setSetNquads。他们没有被 set 包围。换句话说,而不是这个:

{
  set {
    _:user <label> "USER" .
    _:user <userType> "USER_TYPE" .
    _:user <email> "ba@a.aa" .
  }
}

你只需要三元组:

_:user <label> "USER" .
_:user <userType> "USER_TYPE" .
_:user <email> "ba@a.aa" .

这是您的 Java 代码中的样子:

String email = "ba@a.aa";
String userType = "JOB_SEEKER";
Transaction newTransaction = this.dgraphClient.newTransaction();
String triples = 
        "_:user <label> \"USER\" .\n" +
        "_:user <userType> \"" + email + "\" .\n" +
        "_:user <email> \"" + userType + "\" .";
Mutation mu =
    Mutation.newBuilder()
        .setSetNquads(ByteString.copyFromUtf8(triples))
        .build();
Assigned assigned = newTransaction.mutate(mu);

{ set { ... } } 的第一个变异格式用于 HTTP 客户端,其中包括 Dgraph Ratel 内的变异或 curl

有关 Dgraph 突变的更多信息可在突变文档中找到:https://docs.dgraph.io/mutations/

我找到了一些解决方案,它不是字符串,但它有效。

JSONObject query = new JSONObject();
query.put("label", "USER");
query.put("userType", userType);
query.put("email", email);
Mutation mu = Mutation.newBuilder().setSetJson(ByteString.copyFromUtf8(query.toJSONString())).build();