Translating Cypher to Java

cypher-translate-600x293

The expressive power of Cypher is already awesome and getting better with the Neo4j 2.0 release. Let’s take a step back from the bleeding edge and see Cypher in 1.9.4 and how it can be translated into Java. First a simple example where we look up a User node by an index and return a list of usernames belonging to the people who are that user’s friends:

START me = node:Users(username='maxdemarzi')
MATCH me -[:FRIENDS]-> people
RETURN people.username

The Cypher statement expresses what I want even better than my botched explanation in English. So how would we do this in the Neo4j Java API?

    ObjectMapper objectMapper = new ObjectMapper();
    private static final RelationshipType FRIENDS = DynamicRelationshipType.withName("FRIENDS");

    @GET
    @Path("/friends/{username}")
    public Response getFriends(@PathParam("username") String username, @Context GraphDatabaseService db) throws IOException {
        List<String> results = new ArrayList<String>();
        IndexHits<Node> users = db.index().forNodes("Users").get("username", username);
        Node user = users.getSingle();

        for ( Relationship relationship : user.getRelationships(FRIENDS, Direction.OUTGOING) ){
            Node friend = relationship.getEndNode();
            results.add((String)friend.getProperty("username"));
        }

        return Response.ok().entity(objectMapper.writeValueAsString(results)).build();
    }

That’s a little verbose, but not terrible. We are looking up the username in an index and then traversing the Outgoing FRIENDS relationships to the friend nodes and grabbing their username properties. How about we try something a little harder:

START me = node:Users(username='maxdemarzi')
MATCH me -[:FRIENDS]- people -[:FRIENDS]- fof
WHERE NOT(me -[:FRIENDS]- fof)
RETURN fof, COUNT(people) AS friend_count
ORDER BY friend_count DESC
LIMIT 10

In the query above, we are getting the friends of friends who are not direct friends, and returning the top 10 ordered by the number of mutual friends in descending order. We’re going to extract pieces of this query out into their own methods to make our life easier, so for now let’s just cheat and pretend this will work:

    @GET
    @Path("/fofs/{username}")
    public Response getFofs(@PathParam("username") String username, @Context GraphDatabaseService db) throws IOException {
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();

        HashMap<Node, AtomicInteger> fofs = new HashMap<Node, AtomicInteger>();

        IndexHits<Node> users = db.index().forNodes("Users").get("username", username);
        Node user = users.getSingle();

        findFofs(fofs, user);
        List<Entry<Node, AtomicInteger>> fofList = orderFofs(fofs);
        returnFofs(results, fofList.subList(0, Math.min(fofList.size(), 10)));

        return Response.ok().entity(objectMapper.writeValueAsString(results)).build();
    }

We’re calling a “findFofs” method to get the friends of friends and their counts. First, we’ll find the user’s friends and put them on a list. Second, we’ll find the friends of those friends and as long as they are not the user we started with, or already friends of the user, we add them to a HashMap as they key and increment every time we see them again.

    private void findFofs(HashMap<Node, AtomicInteger> fofs, Node user) {
        List<Node> friends = new ArrayList<Node>();

        if (user != null){
            for ( Relationship relationship : user.getRelationships(FRIENDS, Direction.BOTH) ){
                Node friend = relationship.getOtherNode(user);
                friends.add(friend);
            }

            for ( Node friend : friends ){
                for (Relationship otherRelationship : friend.getRelationships(FRIENDS, Direction.BOTH) ){
                    Node fof = otherRelationship.getOtherNode(friend);
                    if (!user.equals(fof) && !friends.contains(fof)) {
                        AtomicInteger atomicInteger = fofs.get(fof);
                        if (atomicInteger == null) {
                            fofs.put(fof, new AtomicInteger(1));
                        } else {
                            atomicInteger.incrementAndGet();
                        }
                    }
                }
            }
        }
    }

Next, we’ll need to order our list of Friends of Friends in Descending order with this method:

    private List<Entry<Node, AtomicInteger>> orderFofs(HashMap<Node, AtomicInteger> fofs) {
        List<Entry<Node, AtomicInteger>> fofList = new ArrayList<Entry<Node, AtomicInteger>>(fofs.entrySet());
        Collections.sort(fofList, new Comparator<Entry<Node, AtomicInteger>>() {
            @Override
            public int compare(Entry<Node, AtomicInteger> a,
                               Entry<Node, AtomicInteger> b) {
                return ( b.getValue().get() - a.getValue().get() );

            }
        });
        return fofList;
    }

Finally we’ll get all the properties of the friend of friend nodes as well as the friend_count and put them in our results.

    private void returnFofs(List<Map<String, Object>> results, List<Entry<Node, AtomicInteger>> fofList) {
        Map<String, Object> resultsEntry;
        Map<String, Object> fofEntry;
        Node fof;
        for (Entry<Node, AtomicInteger> entry : fofList) {
            resultsEntry = new HashMap<String, Object>();
            fofEntry = new HashMap<String, Object>();
            fof = entry.getKey();

            for (String prop : fof.getPropertyKeys()) {
                fofEntry.put(prop, fof.getProperty(prop));
            }

            resultsEntry.put("fof", fofEntry);
            resultsEntry.put("friend_count", entry.getValue());
            results.add(resultsEntry);
        }
    }

Notice when we called this method, we only passed in the just the top 10 friends of friends already ordered by friend_count.

returnFofs(results, fofList.subList(0, Math.min(fofList.size(), 10)));

Our 6 lines of Cypher quickly ballooned into 70 lines of Java. See the complete unmanaged extension with tests on github.

I think these kinds of posts are fun and they truly show the power of Cypher in terms of expressiveness, readability and agility. I’ll do a few more soon. E-mail me if you have any particular cypher queries you’d like to see translated.

Tagged , , , , ,

2 thoughts on “Translating Cypher to Java

  1. […] 6 months ago we looked at how to translate a few lines of Cypher in to way too much Java code in version 1.9.x. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,579 other followers

%d bloggers like this: