Neo4j and Cypher: Translating Cypher to Java
Join the DZone community and get the full member experience.
Join For Freethe 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.
Published at DZone with permission of Max De Marzi, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
DZone's Article Submission Guidelines
-
Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
-
Auditing Tools for Kubernetes
-
Effortlessly Streamlining Test-Driven Development and CI Testing for Kafka Developers
Comments