@Override public Iterable<Relationship> expand( Path path, BranchState<STATE> state ) { if ( path.length() == 0 ) { return path.endNode().getRelationships( types ); } else { Direction direction = getDirectionOfLastRelationship( path ); return path.endNode().getRelationships( direction, types ); } }
Iterator<Node> nodeIterator = path.nodes().iterator(); Iterator<Relationship> relationshipIterator = path.relationships().iterator(); startNode = endNode; endNode = nodeIterator.next(); if ( rel.getStartNode().equals(startNode) && rel.getEndNode().equals(endNode) )
@Override public boolean equals( Object obj ) { if ( obj == this ) { return true; } if ( !(obj instanceof Path) ) { return false; } Path other = (Path) obj; return relationships().equals( other.relationships() ) && other.startNode().equals( cachedStartNode ); }
private Direction getDirectionOfLastRelationship( Path path ) { assert path.length() > 0; Direction direction = Direction.INCOMING; if ( path.endNode().equals( path.lastRelationship().getEndNode() ) ) { direction = Direction.OUTGOING; } return direction; } };
@Override public RelationshipValue[] relationships() { int length = path.length(); RelationshipValue[] values = new RelationshipValue[length]; int i = 0; for ( Relationship relationship : path.relationships() ) { values[i++] = ValueUtils.fromRelationshipProxy( relationship ); } return values; }
public static Path path( Node node, Link... links ) { List<Node> nodes = new ArrayList<>( links.length + 1 ); List<Relationship> relationships = new ArrayList<>( links.length ); List<PropertyContainer> mixed = new ArrayList<>( links.length * 2 + 1 ); nodes.add( node ); mixed.add( node ); Path path = mock( Path.class ); when( path.startNode() ).thenReturn( node ); Relationship last = null; for ( Link link : links ) { last = link.relationship; relationships.add( last ); mixed.add( last ); node = link.checkNode( node ); nodes.add( node ); mixed.add( node ); } when( path.endNode() ).thenReturn( node ); when( path.iterator() ).thenAnswer( withIteratorOf( mixed ) ); when( path.nodes() ).thenReturn( nodes ); when( path.relationships() ).thenReturn( relationships ); when( path.lastRelationship() ).thenReturn( last ); when( path.length() ).thenReturn( links.length ); when( path.reverseNodes() ).thenReturn( reverse( nodes ) ); when( path.reverseRelationships() ).thenReturn( reverse( relationships ) ); return path; }
public static Map<Long, Integer> getTermFrequencyMapForDocument(GraphDatabaseService db, Long classId) { Map<Long, Integer> termDocumentMatrix; String cacheKey = "TERM_DOCUMENT_FREQUENCY_" + classId; if(vectorSpaceModelCache.getIfPresent(cacheKey) == null) { Node classNode = db.getNodeById(classId); termDocumentMatrix = new HashMap<>(); IteratorUtil.asCollection(db.traversalDescription() .depthFirst() .relationships(withName("HAS_CLASS"), Direction.INCOMING) .evaluator(Evaluators.fromDepth(1)) .evaluator(Evaluators.toDepth(1)) .traverse(classNode)).stream() .forEach(p -> { int matches = (Integer) p.lastRelationship().getProperty("matches"); termDocumentMatrix.put(p.endNode().getId(), matches); }); vectorSpaceModelCache.put(cacheKey, termDocumentMatrix); } else { termDocumentMatrix = (Map<Long, Integer>)vectorSpaceModelCache.getIfPresent(cacheKey); } return termDocumentMatrix; }
@Test public void testMaxDepthAndCustomPruneEvaluatorCombined() { Evaluator lessThanThreeRels = path -> count( path.endNode().getRelationships( Direction.OUTGOING ).iterator() ) < 3 ? Evaluation.INCLUDE_AND_PRUNE : Evaluation.INCLUDE_AND_CONTINUE; TraversalDescription description = getGraphDb().traversalDescription().evaluator( Evaluators.all() ) .evaluator( toDepth( 1 ) ).evaluator( lessThanThreeRels ); Set<String> expectedNodes = new HashSet<>( asList( "a", "b", "c", "d", "e" ) ); try ( Transaction tx = beginTx() ) { for ( Path position : description.traverse( node( "a" ) ) ) { String name = (String) position.endNode().getProperty( "name" ); assertTrue( name + " shouldn't have been returned", expectedNodes.remove( name ) ); } tx.success(); } assertTrue( expectedNodes.isEmpty() ); } }
try ( Transaction tx = beginTx() ) getNodeWithName( "2" ).setProperty( "timestamp", 1L ); getNodeWithName( "3" ).setProperty( "timestamp", 2L ); tx.success(); Iterator<Node> nodes = getGraphDb().traversalDescription() .depthFirst() .relationships( type, Direction.OUTGOING ) .evaluator( path -> Relationship rel = path.lastRelationship(); boolean relIsOfType = rel != null && rel.isType( type ); boolean prune = relIsOfType && (Long) path.endNode().getProperty( "timestamp" ) >= timestamp; return Evaluation.of( relIsOfType, !prune ); } )
@Override public Map<String, Set<Long>> call() throws Exception { logger.info("Processsing " + category); Map<String, Set<Long>> map = new HashMap<String, Set<Long>>(); Set<Long> nodeSet = new HashSet<Long>(); Transaction tx = graphDb.beginTx(); try { for (Path position : graphDb.traversalDescription().uniqueness(Uniqueness.NODE_GLOBAL).depthFirst() .relationships(OwlRelationships.RDFS_SUBCLASS_OF, Direction.INCOMING).relationships(OwlRelationships.RDF_TYPE, Direction.INCOMING) .relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH).relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH) .traverse(root)) { Node end = position.endNode(); nodeSet.add(end.getId()); } logger.info("Discovered " + nodeSet.size() + " nodes for " + category); map.put(category, nodeSet); } catch (Exception e) { logger.warning("IRI not found for category: " + category); } finally { tx.success(); tx.close(); } return map; }
@Test public void testTerminationFilterBeforeWhitelist() { db.execute("MATCH (c:Person) WHERE c.name in ['Clint Eastwood', 'Gene Hackman', 'Christian Bale'] SET c:Western"); TestUtil.testResult(db, "MATCH (k:Person {name:'Keanu Reeves'}) " + "CALL apoc.path.expandConfig(k, {relationshipFilter:'ACTED_IN|PRODUCED|DIRECTED', labelFilter:'/Western|+Movie', uniqueness: 'NODE_GLOBAL', filterStartNode:false}) yield path " + "return path", result -> { List<Map<String, Object>> maps = Iterators.asList(result); assertEquals(1, maps.size()); Path path = (Path) maps.get(0).get("path"); assertEquals("Gene Hackman", path.endNode().getProperty("name")); }); }
@Override public Iterable<Relationship> expand( Path path, BranchState<Double> state ) { double newState = state.getState(); if ( path.length() > 0 ) { newState += (Double) path.lastRelationship().getProperty( "length" ); state.setState( newState ); } seenBranchStates.put( path.endNode(), newState ); return path.endNode().getRelationships( OUTGOING ); }
private static List<LinkedHashMap<String, Object>> getFeaturesForClass(GraphDatabaseService db, Node classNode) { List<LinkedHashMap<String, Object>> patternIds = new ArrayList<>(); for (Path p : db.traversalDescription() .depthFirst() .relationships(withName("HAS_CLASS"), Direction.INCOMING) .evaluator(Evaluators.fromDepth(1)) .evaluator(Evaluators.toDepth(1)) .traverse(classNode)) { if(getFeatureMatchDistribution(db, p.endNode().getId()) > CONFIDENCE_INTERVAL) { LinkedHashMap<String, Object> featureMap = new LinkedHashMap<>(); if (p.relationships().iterator().hasNext()) { featureMap.put("frequency", p.relationships().iterator().next().getProperty("matches")); } else { featureMap.put("frequency", 0); } featureMap.put("feature", ((Long) p.endNode().getId()).intValue()); patternIds.add(featureMap); } } return patternIds; }
@Test public void shouldHandlePaths() { // Given NodeValue n1 = nodeValue( 42L, stringArray( "L" ), EMPTY_MAP ); NodeValue n2 = nodeValue( 43L, stringArray( "L" ), EMPTY_MAP ); PathValue p = path( new NodeValue[]{n1, n2}, new RelationshipValue[]{relationshipValue( 1L, n1, n2, stringValue( "T" ), EMPTY_MAP )} ); // When p.writeTo( converter ); // Then Object value = converter.value(); assertThat( value, instanceOf( Path.class ) ); Path path = (Path) value; assertThat( path.length(), equalTo( 1 ) ); assertThat( path.startNode().getId(), equalTo( 42L ) ); assertThat( path.endNode().getId(), equalTo( 43L ) ); assertThat( path.relationships().iterator().next().getId(), equalTo( 1L ) ); }
@Test public void ensureCorrectPathEntitiesInShortPath() { /* * (a)-->(b) */ createGraph( "a TO b" ); Node a = getNodeWithName( "a" ); Node b = getNodeWithName( "b" ); Relationship r = a.getSingleRelationship( to, OUTGOING ); Path path = Iterables.single( getGraphDb().bidirectionalTraversalDescription() .mirroredSides( getGraphDb().traversalDescription().relationships( to, OUTGOING ).uniqueness( NODE_PATH ) ) .collisionEvaluator( Evaluators.atDepth( 1 ) ) .sideSelector( SideSelectorPolicies.LEVEL, 1 ) .traverse( a, b ) ); assertContainsInOrder( path.nodes(), a, b ); assertContainsInOrder( path.reverseNodes(), b, a ); assertContainsInOrder( path.relationships(), r ); assertContainsInOrder( path.reverseRelationships(), r ); assertContainsInOrder( path, a, r, b ); assertEquals( a, path.startNode() ); assertEquals( b, path.endNode() ); assertEquals( r, path.lastRelationship() ); }
private Node getPersonNode() { TraversalDescription traversalDescription = underlyingNode.getGraphDatabase() .traversalDescription() .depthFirst() .relationships( NEXT, Direction.INCOMING ) .relationships( STATUS, Direction.INCOMING ) .evaluator( Evaluators.includeWhereLastRelationshipTypeIs( STATUS ) ); Traverser traverser = traversalDescription.traverse( getUnderlyingNode() ); return singleOrNull( traverser.iterator() ).endNode(); }
@Test public void testPostorderDepthFirstReturnsDeeperNodesFirst() { Traverser traverser = getGraphDb().traversalDescription().order( POSTORDER_DEPTH_FIRST ).traverse( node( "1" ) ); int i = 0; List<String> encounteredNodes = new ArrayList<>(); try ( Transaction tx = beginTx() ) { for ( Path pos : traverser ) { encounteredNodes.add( (String) pos.endNode().getProperty( "name" ) ); assertEquals( expectedDepth( 12 - i++ ), pos.length() ); } tx.success(); } assertEquals( 13, i ); assertTrue( encounteredNodes.indexOf( "5" ) < encounteredNodes.indexOf( "2" ) ); assertTrue( encounteredNodes.indexOf( "6" ) < encounteredNodes.indexOf( "2" ) ); assertTrue( encounteredNodes.indexOf( "7" ) < encounteredNodes.indexOf( "2" ) ); assertTrue( encounteredNodes.indexOf( "8" ) < encounteredNodes.indexOf( "3" ) ); assertTrue( encounteredNodes.indexOf( "9" ) < encounteredNodes.indexOf( "3" ) ); assertTrue( encounteredNodes.indexOf( "A" ) < encounteredNodes.indexOf( "3" ) ); assertTrue( encounteredNodes.indexOf( "B" ) < encounteredNodes.indexOf( "4" ) ); assertTrue( encounteredNodes.indexOf( "C" ) < encounteredNodes.indexOf( "4" ) ); assertTrue( encounteredNodes.indexOf( "D" ) < encounteredNodes.indexOf( "4" ) ); assertTrue( encounteredNodes.indexOf( "2" ) < encounteredNodes.indexOf( "1" ) ); assertTrue( encounteredNodes.indexOf( "3" ) < encounteredNodes.indexOf( "1" ) ); assertTrue( encounteredNodes.indexOf( "4" ) < encounteredNodes.indexOf( "1" ) ); }
@Override public boolean test( Path item ) { ResourceIterable<Relationship> relationships = (ResourceIterable<Relationship>) item.endNode() .getRelationships( Direction.OUTGOING ); try ( ResourceIterator<Relationship> iterator = relationships.iterator() ) { while ( iterator.hasNext() ) { Relationship rel = iterator.next(); if ( rel.getEndNode().equals( node ) ) { return true; } } return false; } }
Iterator<PropertyContainer> it = path.iterator(); while (it.hasNext()) { Node n = (Node) it.next(); Map<String, Object> nMap = maps.computeIfAbsent(n.getId(), (id) -> toMap(n)); if (it.hasNext()) { Relationship r = (Relationship) it.next(); Node m = r.getOtherNode(n); Map<String, Object> mMap = maps.computeIfAbsent(m.getId(), (id) -> toMap(m)); String typeName = r.getType().name(); if (lowerCaseRels) typeName = typeName.toLowerCase(); mMap = addRelProperties(mMap, typeName, r); .map(Path::startNode) .distinct() .map(n -> maps.remove(n.getId())) .map(m -> m == null ? Collections.<String,Object>emptyMap() : m) .map(MapResult::new);