Hi Taylor,

It is possible to make sure only one relationship of a specific type
gets created between two nodes. The easiest way to achieve this is to
make sure a write lock is grabbed on the node (or nodes if the
relationship could start from either n1 or n2). Grabbing a write lock
can be done using the internal lock manager of Neo4j but even easier
is to just perform a write operation on the node then check for
existing relationship. Here is some sample code how to make sure node1
only has one relationship of a specific type to node2:

       // grab write lock on nodes by setting a dummy property
       node1.setProperty( "dummy", true );
       node2.setProperty( "dummy", true );

       boolean relationshipAlreadyExist = false;
       for ( Relationship rel : node1.getRelationships( type, Direction.BOTH ) )
       {
           if ( rel.getOtherNode( node1 ).equals( node2 ) )
           {
               relationshipAlreadyExist = true;
               break;
           }
       }
       if ( !relationshipAlreadyExist )
       {
           node1.createRelationshipTo( node2, type );
       }

       // remove dummy property
       node1.removeProperty( "dummy" );
       node2.removeProperty( "dummy" );

Once the transaction is committed all other threads that are blocked
on the node.setProperty (that grabs the write lock) will see the
relationship created and not create a duplicate one.

It is possible to do this a bit more efficient using the internal lock
manager (see this thread:
http://www.mail-archive.com/[email protected]/msg01870.html on how
to do that).

Regards,
-Johan


On Wed, Dec 2, 2009 at 8:28 PM, Taylor Cowan <[email protected]> wrote:
> I'm struggling with choosing the best pattern to keep relationships singular 
> regarding a particular target/object, (neo allows many relations of the same 
> type between n(1) and n(2)
>
> Within a transaction, a relationship can be checked as missing, and added, 
> and simultaneously another thread ads the relationship.  I'm now considering 
> just allowing duplicates and periodically walking the graph offline to remove 
> duplicate relationships between the same two nodes.
>
> Are there any best practices, patterns, tips that might be helpful regarding 
> pruning or preventing redundant relationships?
>
> Taylor
_______________________________________________
Neo mailing list
[email protected]
https://lists.neo4j.org/mailman/listinfo/user

Reply via email to