Skip to content

Subgraph.__db_create__ doesn't create multiple relationships between the same nodes #953

Description

@alfredo-f

Issue

Description

from py2neo import Graph, Node
graph = Graph(NEO4J_URI, user=NEO4J_USER, password=NEO4J_PASSWORD)
node_a = Node("Node", name="A")
node_b = Node("Node", name="B")

graph_tx = graph.begin()
for node in (node_a, node_b):
    graph_tx.create(node)
graph.commit(graph_tx)

relationship_1 = Relationship(node_a, "REL", node_b, id_overwritten=6)
relationship_2 = Relationship(node_a, "REL", node_b, id_overwritten=7)

graph_tx = graph.begin()
for node in (node_a, node_b):
    graph_tx.create(node)
graph.commit(graph_tx)

graph_tx = graph.begin()
for relationship in (relationship_1, relationship_2):
    graph_tx.create(relationship)
graph.commit(graph_tx)

Expected behavior

Given that relationship_2 has a different id_overwritten, a new relationship should be created.

(A) -[REL {"id_overwritten": 6}]-> (B)
(A) -[REL {"id_overwritten": 7}]-> (B)

Actual behavior

relationship_1 is replaced with relationship_2

(A) -[REL {"id_overwritten": 7}]-> (B)

Cause

This is due to the fact that Subgraph.__db_create__ has no option for CREATEing instead of MERGEing

https://github.com/py2neo-org/py2neo/blob/2e46bbf4d622f53282e796ffc521fc4bc6d0b60d/py2neo/data.py#L209

>>> print(pq[0])

UNWIND $data AS r
MATCH (a) WHERE id(a) = r[0]
MATCH (b) WHERE id(b) = r[2]
MERGE (a)-[_:REL]->(b)
SET _ += r[1]

Workaround

...
pq = unwind_merge_relationships_query(data, r_type)

import re

# Pardon my regex
pq = (
    re.sub(
        (
            r"(.*)?"
            r"(MERGE )(\(a\)-\[_:\w+\]->\(b\))"
            r"(.*)"
        ),
        (
            r"\g<1>"
            r"CREATE "
            r"\g<3>"
            r"\g<4>"
        ),
        pq[0],
    ),
    *pq[1:],
)
...

so that

>>> print(pq[0])

UNWIND $data AS r
MATCH (a) WHERE id(a) = r[0]
MATCH (b) WHERE id(b) = r[2]
CREATE (a)-[_:REL]->(b)
SET _ += r[1]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions