0

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."

Alex Kumundzhiev
  • 245
  • 3
  • 10

2 Answers2

2

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/

Daniel Mai
  • 341
  • 1
  • 7
0

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();
Alex Kumundzhiev
  • 245
  • 3
  • 10
  • I imagine it from Node.js driver examples. I came from JavaScript world and this is more explicit for me, than Dgraph documentation have. – Alex Kumundzhiev Jun 14 '19 at 01:30