Search code examples
pythonneo4jcypherpy2neo

cyclic relationships between nodes in neo4j


i'm working with neo4j and python (with py2neo), i need to put something like this, https://i.sstatic.net/nAzLq.png , in the database. Currently i have this, https://i.sstatic.net/x6skO.png, with this cypher query

grafoNeo4j.cypher.execute("merge (n1:k_mer {name : '"+src.k_1_mer+"'}) 
merge (n2:k_mer {name : '"+dst.k_1_mer+"'}) merge (n1)-[:solapa]-(n2)")

where:

  • grafoNeo4j , is my graph in the db.
  • src.k_1_mer and dst.k_1_mer , are the nodes name

my idea is to get the graph of the first image, wit the corresponding cyclic relationships in the database. Hope that this is clear enough. Thanks for your time.


Solution

  • It is a waste of resources to have identical copies of the same relationship between 2 nodes. You can instead maintain a count property on a single relationship. The optional ON CREATE and ON MATCH subclauses for the MERGE clause make this very easy.

    For example:

    MERGE (n1:k_mer {name : 'a'}) 
    MERGE (n2:k_mer {name : 'b'})
    MERGE (n1)-[r:solapa]-(n2)
    ON CREATE SET r.cnt = 1
    ON MATCH SET r.cnt = r.cnt + 1;