简体   繁体   中英

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

I need do be able to run raw string mutation queries without using of 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);

I want to run:

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);

But I get the error on run-time: "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."

When setting N-Quad Triples for mutations in gRPC clients such as dgraph4j, you only need to specify the newline-separated triples themselves and pass them to Mutation#setSetNquads . They are not surrounded by set . In other words, instead of this:

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

You only need the triples:

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

Here's how it would look like in your Java code:

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);

The first mutation format with { set { ... } } is for HTTP clients, which includes mutations within Dgraph Ratel or with curl .

More information about Dgraph mutations is available in the mutation docs: https://docs.dgraph.io/mutations/

I've found some solution, it is not string but it works.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM