Search code examples
cyphermemgraphdbopencypher

How to make sure that created node will exist and will be unique in Memgraph?


If I get it correctly, this only enforces an existence constraint, not a uniqueness:

CREATE CONSTRAINT ON (c:City)
ASSERT exists (c.name);

To make it unique, I would use a unique property constraint using the following syntax:

CREATE CONSTRAINT ON (c:City)
ASSERT c.name IS UNIQUE

Can I somehow make it unique and enforce existence at the same time?

If I run:

CREATE CONSTRAINT ON (c:City)
ASSERT exists (c.name) IS UNIQUE;

I get an error:

Query failed: line 2:24 mismatched input 'IS' expecting {<EOF>, ';'}

Solution

  • I can't comment due to my low karma, but @cybersam is correct. If you want to make it clear that you're enforcing both existence and uniqueness, you can use a combination of ASSERT EXISTS and ASSERT c.property IS UNIQUE. This syntax is not supported by Cypher in a single statement.

    To achieve both constraints, you will need to create two separate queries. One for existence and one for uniqueness.

    Frist query:

    CREATE CONSTRAINT ON (c:City)
    ASSERT EXISTS (c.name);
    

    Second query:

    CREATE CONSTRAINT ON (c:City)
    ASSERT c.name IS UNIQUE;