About the demo of use Dgraph as graph database

I would like to build a graph for keeping user phone and phone graph. The node is defined as a phone number, and the Edge could be defined as from_phone call to_phone with earliest call time. The constraint is every phone node should be unique, and every edge should also be unique.

For each edge to be inserted into DGraph, first check and persist the phone node, and then insert the edge.

But the problem is I could not find the way to retrieve edges from the UID of given phone node. Can anyone help me out? Thanks.

The demo could can be simply as below:

import com.google.gson.Gson;
import com.google.protobuf.ByteString;
import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphProto;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GraphDemo {

    public static String getUidForPhone(String phone, DgraphClient dgraphClient) {
        DgraphClient.Transaction txn = dgraphClient.newTransaction();
        String query =
                "\n"
                        + "  {\n"
                        + "   get(func: eq(phone_number, \"%s\")) {\n"
                        + "    uid\n"
                        + "   }\n"
                        + "  }\n";
        query = String.format(query, phone);
        String uid = "";
        try {
            DgraphProto.Response resp = txn.query(query);
            Gson gson = new Gson();
            Demo.Decode1 decode1 = gson.fromJson(resp.getJson().toStringUtf8(), Demo.Decode1.class);
            // assertTrue(decode1.get.size() <= 1);
            if (decode1.get.size() == 1) {
                uid = decode1.get.get(0).uid;
            } else {
                String nqs =
                        "\n"
                                + "   _:phone <phone_number> \"%s\" .\n";
                nqs = String.format(nqs, phone);
                DgraphProto.Mutation mu = DgraphProto.Mutation.newBuilder().setSetNquads(ByteString.copyFromUtf8(nqs)).build();
                DgraphProto.Assigned assigned = txn.mutate(mu);
                uid = assigned.getUidsOrThrow("phone");
            }
            System.out.println("phone=" + phone + "  uid=" + uid);
            txn.commit();
        } finally {
            txn.discard();
        }

        return  uid;
    }

    public static void main(String[] args) throws Exception {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9080).usePlaintext(true).build();
        DgraphGrpc.DgraphBlockingStub blockingStub = DgraphGrpc.newBlockingStub(channel);
        DgraphClient dgraphClient = new DgraphClient(Collections.singletonList(blockingStub));

        System.out.println(dgraphClient);

        String schema =
                "   phone_number:  string   @index(exact) .\n"
                        + "   is_black:    int      @index(int)  .\n";

        DgraphProto.Operation op = DgraphProto.Operation.newBuilder().setSchema(schema).build();
        dgraphClient.alter(op);


        List<String> phoneList = new ArrayList<>();
        phoneList.add("13675878111");
        phoneList.add("13312345678");
        phoneList.add("13876541234");

        //persisteThePhoneNodes(phoneList, dgraphClient);

        List<String> edgeList = new ArrayList<>();
        edgeList.add("13675878111,13312345678,called,2017-10-12T12:12:20");
        edgeList.add("13675878111,13876541234,contact,2017-08-21T15:21:02");

        for (String edge : edgeList) {
            String[] t = edge.split(",");
            String fromPhone = t[0].trim();
            String toPhone = t[1].trim();
            String edgeType = t[2];
            String createTime = t[3];

            String fromUid = getUidForPhone(fromPhone, dgraphClient);
            String toUid = getUidForPhone(toPhone, dgraphClient);

            DgraphClient.Transaction txn = dgraphClient.newTransaction();
            String query = "{\n" +
                    "\tget (func: eq(phone_number, \"" + fromPhone +  "\")) {\n" +
                     "_predicate_" +
                    "\t}\n" +
                    "}";

            DgraphProto.Response resp = txn.query(query);
            System.out.println(resp);

            // _:x <friend> _:y .
            String nqs = " <" + fromUid + ">  <" + edgeType + ">  <" + toUid + "> (createTime=" + createTime + ")  .";
            System.out.println("nqs=" + nqs);
            DgraphProto.Mutation mu = DgraphProto.Mutation.newBuilder().setSetNquads(ByteString.copyFromUtf8(nqs)).build();
            DgraphProto.Assigned assigned = txn.mutate(mu);
            txn.commit();
        }


    }

    static class Decode1 {
        ArrayList<Uids> get;

        static class Uids {
            String uid;
        }
    }

    static class Decode2 {
        List<Entry> all;

        static class Entry {
            String first;
            String last;
            int age;
        }
    }
}

It’s hard to debug without a full reproducible example. Also, I see that you are not checking errors from txn.mutate(mu) and txn.commit() so maybe data is not getting written properly.

I have pasted the whole code.

one of the response is:

json: "{\"get\":[{\"_predicate_\":[\"called\",\"phone_number\",\"contact\"]}]}"
txn {
  start_ts: 27761
  lin_read {
    ids {
      key: 1
      value: 57128
    }
  }
}
latency {
  parsing_ns: 6219
  processing_ns: 101027
  encoding_ns: 364723
}

Blockquote

That means the predicates are there. Have you tried retrieving them by specifying them within the query like?

{
  get(func: eq(phone_number, "number")) {
    uid
    called
    contact
  }
}

You can also use expand(_all_) https://docs.dgraph.io/query-language/#expand-predicates

If turn to query like this

            String query = "{\n" +
                    "\tdirector (func: eq(phone_number, \"" + fromPhone +  "\")) {\n" +
                     "    expand(_all_) {\n" +
                    "      expand(_all_) {\n" +
                    "        expand(_all_) { expand(_all_)} \n" +
                    "      }\n" +
                    "    }" +
                    "\t}\n" +
                    "}";

the response is

json: "{\"director\":[{\"called\":[{\"phone_number\":\"13312345678\"}],\"phone_number\":\"13675878111\",\"contact\":[{\"phone_number\":\"13876541234\"}]}]}"

The problem of query out the edge with create_time still failed. Because I would like to query out the create time for each edge, if edge existed, the most earliest timestamp will be kept on the Edge.

I see that you have added create_time as a facet and unfortunately expand(_all_) doesn’t expand facets automatically as of now. Could you please file an issue on Github so that we can support it?

As a work around you can request predicates directly, like

{
  director(func: eq(phone_number, "fromPhone")) {
    called @facets {
      phone_number
    }
    phone_number
    contact @facets {
      phone_number
    }
  }
}

Great!
I could query out the facet now.
Thanks very much.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.