Search code examples
memgraphdb

Dealing with subqueries and merge Statements in Memgraph: trouble with empty node


I'm encountering difficulties while trying to run the following query:

MERGE (town:Town {name: "Paris", external_id: "paris1"})
CALL {
MATCH (nation:Nation {iso_code: "FR"})
RETURN nation, assert(count(nation) = 1, '[NATION_NOT_FOUND] The specified nation code does not exist') AS nation_check_failed
}
MERGE (town)-[:LOCATED_IN]->(nation)
RETURN town, nation

I'm unsure if this is an issue with my understanding of Cypher or with Memgraph, but in my view, this should execute properly. The problem arises when merging (or even creating) a relationship where the Nation node is an empty node (no label, no properties). The query runs successfully without the merge statement (as can be seen in the second screenshot). The issue persists even without the assert statement.

Although the subquery might not be needed in this case, I came across this unusual behavior in more complex queries. In those, the fetched node worked fine when creating relationships, but then it became "empty", and a relationship was created with this empty node.

Moreover, this query works perfectly:

MERGE (town:Town {name: "Paris", external_id: "paris1"})
WITH town
MATCH (nation:Nation {iso_code: "FR"})
MERGE (town)-[:LOCATED_IN]->(nation)
RETURN town, nation

But, I need to use subqueries. What am I doing wrong here? Any guidance or thoughts would be appreciated.


Solution

  • Here's a potential workaround to your problem. However, please make sure that you've already created the necessary nodes:

    CREATE (town:Town {name: "Paris", external_id: "paris1"});
    CREATE (nation:Nation {name: "France", iso_code: "FR"});
    

    When you have nodes you can do the following:

    MATCH (town:Town {name: "Paris", external_id: "paris1"})
    CALL {
    MATCH (nation:Nation {iso_code: "FR"})
    RETURN nation, assert(count(nation) = 1, '[NATION_NOT_FOUND] There is no nation with the provided iso_code') AS nation_check_failed
    }
    WITH town, nation
    MERGE (town)-[rel:LOCATED_IN]->(nation)
    RETURN town, rel, nation;
    

    However, it's important to note that using count(state) in the assert function will always return 1 for the matched State node. If you are aiming to guarantee the uniqueness of the iso_code, you may need to adjust your method. You might want to consider setting a uniqueness constraint on the iso_code property of the State nodes if your use case permits. This would ensure that no two State nodes can have the same iso_code.