org.neo4j.graphdb.Path类的使用及代码示例

x33g5p2x  于2022-01-26 转载在 其他  
字(13.1k)|赞(0)|评价(0)|浏览(126)

本文整理了Java中org.neo4j.graphdb.Path类的一些代码示例,展示了Path类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Path类的具体详情如下:
包路径:org.neo4j.graphdb.Path
类名称:Path

Path介绍

[英]Represents a path in the graph. A path starts with a node followed by pairs of Relationship and Node objects. The shortest path is of length 0. Such a path contains only one node and no relationships. During a traversal Path instances are emitted where the current position of the traverser is represented by each such path. The current node in such a traversal is reached via Path#endNode().
[中]表示图形中的路径。路径以一个节点开始,后跟一对关系和节点对象。最短路径的长度为0。这样的路径只包含一个节点,没有关系。在遍历路径期间,会发出遍历器的当前位置由每个这样的路径表示的实例。这种遍历中的当前节点是通过路径#endNode()到达的。

代码示例

代码示例来源:origin: neo4j/neo4j

@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 );
  }
}

代码示例来源:origin: neo4j/neo4j

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) )

代码示例来源:origin: neo4j/neo4j

@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 );
}

代码示例来源:origin: neo4j/neo4j

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;
  }
};

代码示例来源:origin: neo4j/neo4j

@Override
public NodeValue[] nodes()
{
  int length = path.length() + 1;
  NodeValue[] values = new NodeValue[length];
  int i = 0;
  for ( Node node : path.nodes() )
  {
    values[i++] = ValueUtils.fromNodeProxy( node );
  }
  return values;
}

代码示例来源:origin: neo4j/neo4j

@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;
}

代码示例来源:origin: neo4j/neo4j

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;
}

代码示例来源:origin: Graphify/graphify

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;
}

代码示例来源:origin: neo4j/neo4j

@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() );
  }
}

代码示例来源:origin: neo4j/neo4j

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 );
      } )

代码示例来源:origin: SciGraph/SciGraph

@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;
}

代码示例来源:origin: neo4j-contrib/neo4j-apoc-procedures

@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"));
      });
}

代码示例来源:origin: neo4j/neo4j

@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 );
}

代码示例来源:origin: Graphify/graphify

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;
}

代码示例来源:origin: neo4j/neo4j

@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 ) );
}

代码示例来源:origin: neo4j/neo4j

@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() );
}

代码示例来源:origin: org.neo4j.examples/neo4j-examples

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();
}

代码示例来源:origin: neo4j/neo4j

@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" ) );
}

代码示例来源:origin: neo4j/neo4j

@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;
  }
}

代码示例来源:origin: neo4j-contrib/neo4j-apoc-procedures

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);

相关文章