Search code examples
javaneo4jgraph-traversal

Neo4J TraversalDescription Definition


I am trying to create a TraversalDescription that will perform the following search;

  • Return only nodes that have a certain property ("type" == "PERSON")
  • Return a certain fixed number of results (the entire graph is huge, we are only interested in the local graph)
  • Any relationship types can be used

I haven't managed to get very far, I can't seem to figure out how to create an Evaluator for node properties;

TraversalDescription td = Traversal.description().bredthFirst().evaluator(?...);

Solution

  • I fixed this by simply implementing the Evaluator interface, and overwriting the Evaluator.evaluate(Path p) method;

    public final class MyEvaluator implements Evaluator {
    
        private int peopleCount;
        private int maxPeople;
    
        public MyEvaluator(int max) {
            maxPeople = max;
            peopleCount = 0;
        }
    
        public Evaluation evaluate(Path p) {
    
            //prune if we have found the required number already
            if(peopleCount >= maxPeople) return Evaluation.EXCLUDE_AND_PRUNE;
    
            //grab the node of interest
            Node n = p.endNode();
    
            //include if it is a person
            if(n.hasProperty("type") && (n.getProperty("type").equals(NodeTypes.PERSON.name()))) {
                peopleCount++;
                return Evaluation.INCLUDE_AND_CONTINUE;
            }
    
            // otherwise just carry on as normal
            return Evaluation.EXCLUDE_AND_CONTINUE;
        }
    }
    

    And then my TraversalDescription definition ends up looking like:

    TraversalDescription td = Traversal.description().breadthFirst().evaluator(new MyEvaluator(peopleRequired));