2
votes

I have a neo4j graph database,and I am using java embedded,how can I convert this cypher query to java code(is it possible at all)?

the query:

START n=node(*)
MATCH p=n-[rels:INCLUDE*]->m 
WHERE ALL (rel IN rels 
  WHERE rel.status='on') 
WITH COLLECT(p) AS paths, MAX(length(p)) AS maxLength 
RETURN FILTER(path IN paths 
  WHERE length(path)= maxLength) AS longestPaths

this query is about finding the longest path among nodes which have relationship with STATUS="on" property with each other,and returns the path.

because I read that working with a neo4j database, from java api is faster than running the cypher query from a java application.

so please help me to write the java code which does the same thing this cypher query does.

thanks in advance.

1
You cannot "convert" a "cypher query to java code". You can achieve the same result in a java application, but your question is much too broad. Do you know Java? Have you read the Neo4j tutorials? What have you tried so far?jjaderberg

1 Answers

3
votes

If you are referring to the traversal framework, then this is your best bet: http://docs.neo4j.org/chunked/stable/tutorial-traversal.html

You will probably want to do your own performance testing to determine which is faster.

Forgive me because my java is a bit rusty and I don't readily have a means of actually testing this out for you. However I think this will get what you want.

List<Path> longestPaths = null;
int longestLength = 0;

for ( Path position : Traversal.description()
        .depthFirst()
        .relationships( Rels.INCLUDE )
        .relationships( Rels.LIKES, Direction.OUTGOING )
        .evaluator( new Evaluator {
            public Evaluation evaluate(Path path) {
                Relationship r = path.lastRelationship();
                if(r != null && "on".equals(r.getProperty("status"))) {
                    return Evaluation.INCLUDE_AND_CONTINUE;
                }

                return EXCLUDE_AND_PRUNE;
            }
        } )
        .traverse( node ) )
{
    //Given that node is your start node this would be the (WHERE ALL rels status = on)

    if(longestPaths == null || longestLength < position.length()) {
        longestPaths = new ArrayList<Path>();
        longestPaths.add(position);
        longestLength = position.length();
    }
}

//At this point you should have a collection of the longest paths