Search code examples
memgraphdb

Is it possible to create a constrain with a union of two properties in Memgraph?


Is it possible to create a constrain with a union of two properties. I have address and chainId. My constrain must assert that is possible to have only 1 node with an specific address and chainId?


Solution

  • Not sure if this is what you're looking for, but you can specify multiple properties when creating uniqueness constraints: CREATE CONSTRAINT ON (n:label) ASSERT n.property1, n.property2, ..., IS UNIQUE; Source: https://memgraph.com/docs/fundamentals/constraints#uniqueness-constraint

    For example, let's say I did:

    CREATE CONSTRAINT ON (n:Company) ASSERT n.address, n.chainId IS UNIQUE;
    

    And then I went on and create companies:

    CREATE (:Company {address: "Address 1", chainId: 1})
    
    CREATE (:Company {address: "Address 1", chainId: 2})
    
    CREATE (:Company {address: "Address 2", chainId: 1})
    
    CREATE (:Company {address: "Address 2", chainId: 2})
    

    This is okay because none of the pairs of (address, chainId) is not exactly the same. But, if I try running the following query:

    CREATE (:Company {address: "Address 1", chainId: 1})
    

    I get

    Unable to commit due to unique constraint violation on :Company(address, chainId)
    

    as expected, because that pair of (address, chainId) already exists in the database.