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

x33g5p2x  于2022-01-28 转载在 其他  
字(14.4k)|赞(0)|评价(0)|浏览(215)

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

Relationship介绍

[英]A relationship between two nodes in the graph. A relationship has a start node, an end node and a RelationshipType. You can attach properties to relationships with the API specified in PropertyContainer.

Relationships are created by invoking the Node#createRelationshipTo(Node,RelationshipType) method on a node as follows:

Relationship rel = node. Node#createRelationshipTo(Node,RelationshipType)( otherNode, MyRels.REL_TYPE );

The fact that the relationship API gives meaning to #getStartNode() and #getEndNode() nodes implicitly means that all relationships have a direction. In the example above, rel would be directed fromnodetootherNode. A relationship's start node and end node and their relation to Direction#OUTGOING and Direction#INCOMING are defined so that the assertions in the following code are true:

Node a = graphDb. 
GraphDatabaseService#createNode()(); 
Node b = graphDb. 
GraphDatabaseService#createNode()(); 
Relationship rel = a. 
Node#createRelationshipTo(Node,RelationshipType)( b,  
RelationshipType ); 
// Now we have: (a) --- REL_TYPE ---> (b) 
assert rel. 
Relationship#getStartNode()().equals( a ); 
assert rel. 
Relationship#getEndNode()().equals( b ); 
assert rel. 
Relationship#getNodes()()[0].equals( a ) && 
rel. 
Relationship#getNodes()()[1].equals( b );

Even though all relationships have a direction they are equally well traversed in both directions so there's no need to create duplicate relationships in the opposite direction (with regard to traversal or performance).

Furthermore, Neo4j guarantees that a relationship is never "hanging freely," i.e. #getStartNode(), #getEndNode(), #getOtherNode(Node) and #getNodes() are guaranteed to always return valid, non-null nodes.

A relationship's id is unique, but note the following: Neo4j reuses its internal ids when nodes and relationships are deleted, which means it's bad practice to refer to them this way. Instead, use application generated ids.
[中]图中两个节点之间的关系。关系有开始节点、结束节点和RelationshipType。可以将属性附加到与PropertyContainer中指定的API的关系。
通过在节点上调用Node#createRelationshipTo(Node,RelationshipType)方法创建关系,如下所示:
Relationship rel = node. Node#createRelationshipTo(Node,RelationshipType)( otherNode, MyRels.REL_TYPE );
关系API为#getStartNode()和#getEndNode()节点赋予了意义,这意味着所有关系都有一个方向。在上面的例子中,rel将从node定向到otherNode。定义关系的开始节点和结束节点及其与方向#传出和方向#传入的关系,以便以下代码中的断言为true

Node a = graphDb. 
GraphDatabaseService#createNode()(); 
Node b = graphDb. 
GraphDatabaseService#createNode()(); 
Relationship rel = a. 
Node#createRelationshipTo(Node,RelationshipType)( b,  
RelationshipType ); 
// Now we have: (a) --- REL_TYPE ---> (b) 
assert rel. 
Relationship#getStartNode()().equals( a ); 
assert rel. 
Relationship#getEndNode()().equals( b ); 
assert rel. 
Relationship#getNodes()()[0].equals( a ) && 
rel. 
Relationship#getNodes()()[1].equals( b );

尽管所有关系都有一个方向,但它们在两个方向上都被同样好地遍历,因此不需要在相反方向上创建重复的关系(关于遍历或性能)。
此外,Neo4j保证关系永远不会“自由挂起”,即#getStartNode()、#getEndNode()、#getOtherNode(节点)和#getNodes()保证始终返回有效的非空节点。
关系的id是唯一的,但请注意以下几点:当节点和关系被删除时,Neo4j重用其内部id,这意味着以这种方式引用它们是不好的做法。相反,使用应用程序生成的ID。

代码示例

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

private void appendRelationship( PrintWriter out, Relationship rel )
{
  out.print( "create (" );
  out.print( identifier( rel.getStartNode() ) );
  out.print( ")-[:" );
  out.print( quote( rel.getType().name() ) );
  formatProperties( out, rel );
  out.print( "]->(" );
  out.print( identifier( rel.getEndNode() ) );
  out.println( ")" );
}

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

private long initWithRel( GraphDatabaseService db )
{
  try ( Transaction tx = db.beginTx() )
  {
    Node node = db.createNode();
    node.setProperty( "a", "prop" );
    Relationship rel = node.createRelationshipTo( db.createNode(), RelationshipType.withName( "T" ) );
    long id = rel.getId();
    tx.success();
    return id;
  }
}

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

public static void cleanupAllRelationshipsAndNodes( GraphDatabaseService db )
  {
    try ( Transaction tx = db.beginTx() )
    {
      for ( Relationship relationship : db.getAllRelationships() )
      {
        relationship.delete();
      }

      for ( Node node : db.getAllNodes() )
      {
        node.delete();
      }
      tx.success();
    }
  }
}

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

private static String relToString( Relationship rel )
{
  return rel.getStartNode() + "--" + rel.getType() + "-->"
      + rel.getEndNode();
}

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

@Override
  public String relationshipRepresentation( Path path,
                       Node from, Relationship relationship )
  {
    String prefix = "-";
    String suffix = "-";
    if ( from.equals( relationship.getEndNode() ) )
    {
      prefix = "<-";
    }
    else
    {
      suffix = "->";
    }
    return prefix + "[" + relationship.getType().name() + "," +
        relationship.getId() + "]" + suffix;
  }
}

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

public void add( Relationship rel )
{
  final long id = rel.getId();
  if ( !relationships.containsKey( id ) )
  {
    addRel( id, rel );
    add( rel.getStartNode() );
    add( rel.getEndNode() );
  }
}

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

@Test
public void mustBeAbleToConsistencyCheckRelationshipIndexWithOneRelationshipTypeAndOneProperty() throws Exception
{
  GraphDatabaseService db = createDatabase();
  RelationshipType relationshipType = RelationshipType.withName( "R1" );
  try ( Transaction tx = db.beginTx() )
  {
    db.execute( format( RELATIONSHIP_CREATE, "rels", array( "R1" ), array( "p1" ) ) ).close();
    tx.success();
  }
  try ( Transaction tx = db.beginTx() )
  {
    db.schema().awaitIndexesOnline( 1, TimeUnit.MINUTES );
    Node node = db.createNode();
    node.createRelationshipTo( node, relationshipType ).setProperty( "p1", "value" );
    node.createRelationshipTo( node, relationshipType ).setProperty( "p1", "value" ); // This relationship will have a different id value than the node.
    tx.success();
  }
  db.shutdown();
  assertIsConsistent( checkConsistency() );
}

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

@Test
public void shouldDeleteRelationship() throws Exception
{
  long n1, r;
  try ( org.neo4j.graphdb.Transaction tx = graphDb.beginTx() )
  {
    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    n1 = node1.getId();
    r = node1.createRelationshipTo( node2, RelationshipType.withName( "R" ) ).getId();
    tx.success();
  }
  try ( Transaction tx = beginTransaction() )
  {
    assertTrue( "should delete relationship", tx.dataWrite().relationshipDelete( r ) );
    tx.success();
  }
  try ( org.neo4j.graphdb.Transaction ignore = graphDb.beginTx() )
  {
    assertEquals( 0, graphDb.getNodeById( n1 ).getDegree() );
  }
}

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

private void createData( GraphDatabaseService database, int numberOfNodes )
{
  for ( int i = 0; i < numberOfNodes; i++ )
  {
    try ( Transaction transaction = database.beginTx() )
    {
      Node node = database.createNode( Label.label( FOOD_LABEL ), Label.label( CLOTHES_LABEL ),
          Label.label( WEATHER_LABEL ) );
      node.setProperty( PROPERTY_NAME, "Node" + i );
      Relationship relationship = node.createRelationshipTo( node, RelationshipType.withName( FOOD_LABEL ) );
      relationship.setProperty( PROPERTY_NAME, "Relationship" + i );
      transaction.success();
    }
  }
}

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

@Test
public void queryShouldFindDataAddedInLaterTransactions()
{
  db = createDatabase();
  db.execute( format( NODE_CREATE, "node", array( "Label1", "Label2" ), array( "prop1", "prop2" ) ) ).close();
  db.execute( format( RELATIONSHIP_CREATE, "rel", array( "Reltype1", "Reltype2" ), array( "prop1", "prop2" ) ) ).close();
  awaitIndexesOnline();
  long horseId;
  long horseRelId;
  try ( Transaction tx = db.beginTx() )
  {
    Node zebra = db.createNode();
    zebra.setProperty( "prop1", "zebra" );
    Node horse = db.createNode( Label.label( "Label1" ) );
    horse.setProperty( "prop2", "horse" );
    horse.setProperty( "prop3", "zebra" );
    Relationship horseRel = zebra.createRelationshipTo( horse, RelationshipType.withName( "Reltype1" ) );
    horseRel.setProperty( "prop1", "horse" );
    Relationship loop = horse.createRelationshipTo( horse, RelationshipType.withName( "loop" ) );
    loop.setProperty( "prop2", "zebra" );
    horseId = horse.getId();
    horseRelId = horseRel.getId();
    tx.success();
  }
  assertQueryFindsIds( db, true, "node", "horse", newSetWith( horseId ) );
  assertQueryFindsIds( db, true, "node", "horse zebra", newSetWith( horseId ) );
  assertQueryFindsIds( db, false, "rel", "horse", newSetWith( horseRelId ) );
  assertQueryFindsIds( db, false, "rel", "horse zebra", newSetWith( horseRelId ) );
}

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

@PluginTarget( Node.class )
public Path pathToReference( @Source Node me )
{
  PathFinder<Path> finder = GraphAlgoFactory.shortestPath( PathExpanders.allTypesAndDirections(), 6 );
  try ( Transaction tx = me.getGraphDatabase().beginTx() )
  {
    Node other;
    if ( me.hasRelationship( RelationshipType.withName( "friend" ) ) )
    {
      ResourceIterable<Relationship> relationships =
          (ResourceIterable<Relationship>) me.getRelationships( RelationshipType.withName( "friend" ) );
      try ( ResourceIterator<Relationship> resourceIterator = relationships.iterator() )
      {
        other = resourceIterator.next().getOtherNode( me );
      }
    }
    else
    {
      other = me.getGraphDatabase().createNode();
    }
    Path path = finder.findSinglePath( other, me );
    tx.success();
    return path;
  }
}

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

@Test
public void testSameTxWithArray()
{
  commit();
  newTransaction();
  Node nodeA = getGraphDb().createNode();
  Node nodeB = getGraphDb().createNode();
  Relationship relA = nodeA.createRelationshipTo( nodeB, MyRelTypes.TEST );
  nodeA.setProperty( arrayKey, array );
  relA.setProperty( arrayKey, array );
  assertNotNull( nodeA.getProperty( arrayKey ) );
  assertNotNull( relA.getProperty( arrayKey ) );
  relA.delete();
  nodeA.delete();
  nodeB.delete();
}

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

@Name( GET_CONNECTED_NODES )
@PluginTarget( Node.class )
public Iterable<Node> getAllConnectedNodes( @Source Node start )
{
  ArrayList<Node> nodes = new ArrayList<>();
  try ( Transaction tx = start.getGraphDatabase().beginTx() )
  {
    for ( Relationship rel : start.getRelationships() )
    {
      nodes.add( rel.getOtherNode( start ) );
    }
    tx.success();
  }
  return nodes;
}

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

@Test
public void shouldAccountForDeletedRelationships()
{
  // given
  GraphDatabaseService graphDb = db.getGraphDatabaseAPI();
  Relationship rel;
  try ( Transaction tx = graphDb.beginTx() )
  {
    Node node = graphDb.createNode();
    node.createRelationshipTo( graphDb.createNode(), withName( "KNOWS" ) );
    rel = node.createRelationshipTo( graphDb.createNode(), withName( "KNOWS" ) );
    node.createRelationshipTo( graphDb.createNode(), withName( "KNOWS" ) );
    tx.success();
  }
  long before = numberOfRelationships();
  long during;
  try ( Transaction tx = graphDb.beginTx() )
  {
    rel.delete();
    during = countsForRelationship( null, null, null );
    tx.success();
  }
  // when
  long after = numberOfRelationships();
  // then
  assertEquals( 3, before );
  assertEquals( 2, during );
  assertEquals( 2, after );
}

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

@Graph( value = { "I know you" }, nodes = { @NODE( name = "I", properties = { @PROP( key = "name", value = "me" ) } ) } )
private void verifyIKnowYou( String type, String myName )
{
  try ( Transaction ignored = graphdb.beginTx() )
  {
    Map<String, Node> graph = data.get();
    assertEquals( "Wrong graph size.", 2, graph.size() );
    Node iNode = graph.get( "I" );
    assertNotNull( "The node 'I' was not defined", iNode );
    Node you = graph.get( "you" );
    assertNotNull( "The node 'you' was not defined", you );
    assertEquals( "'I' has wrong 'name'.", myName, iNode.getProperty( "name" ) );
    assertEquals( "'you' has wrong 'name'.", "you",
        you.getProperty( "name" ) );
    Iterator<Relationship> rels = iNode.getRelationships().iterator();
    assertTrue( "'I' has too few relationships", rels.hasNext() );
    Relationship rel = rels.next();
    assertEquals( "'I' is not related to 'you'", you, rel.getOtherNode( iNode ) );
    assertEquals( "Wrong relationship type.", type, rel.getType().name() );
    assertFalse( "'I' has too many relationships", rels.hasNext() );
    rels = you.getRelationships().iterator();
    assertTrue( "'you' has too few relationships", rels.hasNext() );
    rel = rels.next();
    assertEquals( "'you' is not related to 'i'", iNode, rel.getOtherNode( you ) );
    assertEquals( "Wrong relationship type.", type, rel.getType().name() );
    assertFalse( "'you' has too many relationships", rels.hasNext() );
    assertEquals( "wrong direction", iNode, rel.getStartNode() );
  }
}

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

@Before
public void setup()
{
  db = (GraphDatabaseFacade) new TestGraphDatabaseFactory().newImpermanentDatabase();
  try ( Transaction tx = db.beginTx() )
  {
    Node node = db.createNode();
    node.createRelationshipTo( db.createNode(), withName( "a" ) );
    node.createRelationshipTo( db.createNode(), withName( "b" ) );
    relId = node.createRelationshipTo( db.createNode(), withName( "c" ) ).getId();
    tx.success();
  }
}

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

@Test
public void shouldTellIfRelExists()
{
  // Given
  long node = createLabeledNode( db, map() ).getId();
  long created;
  long createdAndRemoved;
  long neverExisted;
  try ( Transaction tx = db.beginTx() )
  {
    created = db.createNode().createRelationshipTo( db.createNode(), withName( "Banana" ) ).getId();
    createdAndRemoved = db.createNode().createRelationshipTo( db.createNode(), withName( "Banana" ) ).getId();
    tx.success();
  }
  try ( Transaction tx = db.beginTx() )
  {
    db.getRelationshipById( createdAndRemoved ).delete();
    tx.success();
  }
  neverExisted = created + 99;
  // When & then
  assertTrue(  relationshipExists( node ));
  assertFalse( relationshipExists( createdAndRemoved ) );
  assertFalse( relationshipExists( neverExisted ) );
}

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

private void createAlistairAndStefanNodes()
{
  try ( Transaction tx = graphDb.beginTx() )
  {
    alistair = graphDb.createNode( label );
    alistair.setProperty( "name", "Alistair" );
    alistair.setProperty( "country", "UK" );
    stefan = graphDb.createNode( label );
    stefan.setProperty( "name", "Stefan" );
    stefan.setProperty( "country", "Deutschland" );
    aKnowsS = alistair.createRelationshipTo( stefan, relationshipType );
    aKnowsS.setProperty( "duration", "long" );
    aKnowsS.setProperty( "irrelevant", "prop" );
    sKnowsA = stefan.createRelationshipTo( alistair, relationshipType );
    sKnowsA.setProperty( "duration", "lengthy" );
    sKnowsA.setProperty( "irrelevant", "prop" );
    tx.success();
  }
}

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

private void createRelationshipsOnNode( GraphDatabaseService db, Node root, int numberOfRelationships )
{
  for ( int i = 0; i < numberOfRelationships; i++ )
  {
    root.createRelationshipTo( db.createNode(), RelationshipType.withName( "Type" + (i % 4) ) )
        .setProperty( "" + i, i );
  }
}

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

@Test
public void testRollbackDeleteRelationship()
{
  Node node1 = getGraphDb().createNode();
  Node node2 = getGraphDb().createNode();
  Relationship rel1 = node1.createRelationshipTo( node2, TEST );
  newTransaction();
  node1.delete();
  rel1.delete();
  getTransaction().failure();
  getTransaction().close();
  setTransaction( getGraphDb().beginTx() );
  node1.delete();
  node2.delete();
  rel1.delete();
}

相关文章