DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

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

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
  1. DZone
  2. Data Engineering
  3. Databases
  4. Neo4j and Cypher: Translating Cypher to Java

Neo4j and Cypher: Translating Cypher to Java

Max De Marzi user avatar by
Max De Marzi
·
Oct. 30, 13 · Interview
Like (0)
Save
Tweet
Share
7.74K Views

Join the DZone community and get the full member experience.

Join For Free

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.


Java (programming language) Neo4j

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

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: