javadgraph

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


Solution

  • 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/