Complex queries in neo4j embedded java

101 Views Asked by At

How do I perform

MATCH (p:Person:Actor)-[r:ACTED_IN]->(m:Movies{name:"ABC"}) RETURN p.name;

In neo4j embedded Java . detailed explanation of the code would be of great help. note: I want to do this in native Java api not in cypher. It is supposed to have around 100000 nodes

2

There are 2 best solutions below

4
On

You can execute Cypher queries with:

GraphDatabaseService db = ...;

// from version 2.2.x onwards
db.execute("your cypher statement");

// before version 2.2.x
ExecutionEngine engine = new ExecutionEngine(db)
engine.execute("your cypher statement");

If you're using Neo4j before v2.2, please note that ExecutionEngine is meant to be instantiated as a singleton, so that execution plans will be properly cached.

If you have got strong performance constraints, might want to play with TraversalDescription and customize the many available parameters and define a traversal callback if needed. The key is to ensure you traverse as little node as required.

You should know though that Cypher execution is being more and more performant, last version (2.2) brings lots of improvements.

0
On

You can try something like this:

Label person = DynamicLabel.label("Person");
for(Node p : GlobalGraphOperations.at(gdb).getAllNodesWithLabel(person))
{
    RelationshipType actedIn =  DynamicRelationshipType.withName("ACTED_IN");
    if(p.hasRelationship(actedIn, Direction.OUTGOING))
    {
        Node m = p.getSingleRelationship(actedIn, Direction.OUTGOING).getEndNode();
        Label person = DynamicLabel.label("Movies");
        if(m.hasLabel(movies) && m.getProperty("name", null) == "ABC")
        {
            return p.getProperty("name");
        }
    }
}