2
votes

I'm new to neo4j , so your help is appreciated.

I have a neo4j database with nodes that have a property "Color" and two relationship types, "Previous" and "Next". I have an ArrayList that contains node properties in the order they should be traversed, for example Blue, Red, Yellow.

How do I traverse the graph to find if the exact path Node(Color:Blue) --> Node(Color:Red) --> Node(Color:Yellow) with no nodes in between and all relationships of type "Next", exists in the database?

I'm using neo4j embedded in a java application.

1

1 Answers

4
votes

It's probably enough with a NEXT relationship between each, because an incoming NEXT can be considered as "previous".

And I think you should index your colors and then start traversing from the first node (in this case "Blue") and have a traverser like this:

String[] colors = new String[] { "Blue", "Red", "Yellow" };
Node start = db.index().forNodes( "colors" ).get( "color", colors[0] ).getSingle();
Traversal.description().uniqueness( Uniqueness.RELATIONSHIP_GLOBAL ).breadthFirst().relationships( Types.NEXT, Direction.OUTGOING ).evaluator( new Evaluator()
{
    @Override
    public Evaluation evaluate( Path path )
    {
        String currentColor = (String) path.endNode().getProperty( "color" );
        boolean endOfTheLine = path.length()+1 >= colors.length;
        return currentColor.equals( colors[path.length()] ) ?
                Evaluation.of( endOfTheLine, !endOfTheLine ) : Evaluation.EXCLUDE_AND_PRUNE;
    }
} ).traverse( start )

I hacked up your domain just now and that traverser works out nicely!