Hello,

  I've been exploring the capabilities and possibilities of neo4j.py
recently.  It is pretty cool!  Thanks!

  One thing I'm trying to avoid when building my new graph is duplicate
relationships.  Instead of creating the same relationship twice, I'd
like to increment a 'count' property on the existing one.

  While it was pretty straightforward to to this for nodes by using an
Index, I'm struggling to figure out how to do it efficiently for a
relationship.

  I can tell if a relationship between the nodes exists by using a
depth(1) traversal.  Unfortunately this approach seems to be really slow
when I'm adding even just a few thousand nodes and relationships.

  Because the traversal I'm using returns the nodes, I haven't been able
to figure out how to get the existing relationship in a way that lets me
increment the count property.

  Here is what I tried to do:

###########################################################################
neo4j_db = neo4j.GraphDatabase( options.neo4jDB,
                               classpath=[myClassPath],
                               jvm=myJVM,
                               heap_size=128)

myNodeIndex = neo4j_db.index("mynodes", create=True)

## Either create a new node, or increment the count on the existing node:
def create_my_node(nodeName):

    my_node = myNodeIndex[nodeName]

    if not my_node:
        my_node = neo4j_db.node(name=nodeName, count=0)
        myNodeIndex[nodeName] = my_node

    my_node['count'] = my_node['count'].intValue() + 1

    return my_node

## Traversal class used to check if a relationship already exists:
class isFollowedBy(neo4j.Traversal):

    types = [ neo4j.Outgoing.FollowedBy ]
    order = neo4j.DEPTH_FIRST
    stop = neo4j.StopAtDepth(1)

    def isReturnable(self, position):
        return (not position.is_start
                and position.last_relationship.type == 'FollowedBy')

## Either create a new relationship, or increment the count on the
existing one:
# ** (This is really slow, and the increment doesn't work.)**
def create_my_relationship(previousNode, currentNode):

    NodeList = []

    for Node in isFollowedBy(previousNode):

        NodeList.append(Node)

    # If we don't already have a relationship, create one:
    if currentNode not in NodeList:

        previousNode.FollowedBy(currentNode, count=1)

    # Otherwise, increment the count on the relationship:
    else:
        for relationship in previousNode.relationships('OUTGOING'):
            if relationship.getOtherNode(previousNode) == currentNode:
                relationship['count'] = relationship['count'].intValue() + 1




-- 
Rick Otten
rot...@windfish.net
O=='=+


_______________________________________________
Neo4j mailing list
User@lists.neo4j.org
https://lists.neo4j.org/mailman/listinfo/user

Reply via email to