I’m new to this whole dgraph thing, I’v gone through large parts of the graphQL+ tutorial, and tried to understand the Dgraph4j sample program, but I can not for the life of me seem to get edges or uid’s to work using the client. Or if the edges are working the following does not show anything:
Below is the mutations and the code I used to read them currently. I have tried several variations of this.
Gson gson = new Gson(); // For JSON encode/decode
Transaction txn = dgraphClient.newTransaction();
Person a = new Person();
a.name = "Dave";
a.age = 25;
a.friends = new ArrayList<Person>();
Person p = new Person();
p.friends = new ArrayList<Person>();
try {
p.name = "Alice";
p.age = 22;
p.friends.add(a);
String json = gson.toJson(p);
Mutation mutation =
Mutation.newBuilder().setSetJson(ByteString.copyFromUtf8(json.toString())).build();
txn.mutate(mutation);
txn.commit();
} finally {
txn.discard();
}
String query = "query all($a:string)" + "{\n all(func: has(age)){\n" + " name\n" +" age\n" + " friends\n" + "}\n" + "}";
//the friends array list will be empty at this point
Response res = dgraphClient.newTransaction().query(query);
String ppl = res.getJson().toStringUtf8();
System.out.println(ppl);
//the person class
static class Person {
// tried to use uids but couldn’t figure them out either
//int uid;
String name;
I found the problem. I need to add fields to the friends attribute to actually see anything in my query. The following worked:
String query = “{\n all(func: has(age)){\n name friends{ name }\n }\n }”;
But now I have a new question. How can I create two nodes that both point to each other? when I try to do it like person1.add(person2) and person2.add(person1) the json created is an infinite loop and the code crashes. I would think I use blank node uids but I can’t seem to figure out how to implement them.
you could create a reverse index and just calling person1.add(person2) is enough.
You could explicitly add just the UID field to both person1 and person2 and use that to create two way connection. This is how json data will look like:
For the second solution, can it be done via JSON serializing a Person object? And if so what type should uid be? Or do I have to manually write the JSON in?
I think if you do person1.add(person2) and person2.add(person1), it will cause problems. Instead, you have to do something like person1.add(person2) and person2.add(person1UID), and define person1UID to only have UID and no other information. This should work. With a bit of bad java syntax, it could look something like this:
person1UID = new Person();
person1UID.UID = "_:person1"
person2.add(person1UID);