Search code examples
neo4jpy2neo

how do I create unique constraints on two properties in neo4j?


I'm using nodes as intermediate path elements, but I want to make sure the start/end are unique. How do I create a constraint that requires TWO values to be checked?

I can set individual ones but can't see syntax for a two-part constraint.

        neolib.run_query(
            """CREATE CONSTRAINT
                uSource
                if not exists
                ON (m:route) ASSERT m.source IS UNIQUE""")
        neolib.run_query(
            """CREATE CONSTRAINT
            uTarget
            if not exists
            ON (m:route) ASSERT m.target IS UNIQUE""")

Solution

  • It has this documentation:

    https://neo4j.com/docs/cypher-manual/current/administration/constraints/#query-constraint-node-key

    CREATE CONSTRAINT [constraint_name] [IF NOT EXISTS]
    ON (n:LabelName)
    ASSERT (n.propertyName_1,
    n.propertyName_2,
    …
    n.propertyName_n)
    IS NODE KEY
    [OPTIONS "{" option: value[, ...] "}"]
    
    FOR EXAMPLE:
        CREATE CONSTRAINT uSourceTarget IF NOT EXISTS ON (m:route) ASSERT (m.source, m. target) IS NODE KEY
    

    NB: Only applicable for Enterprise Edition (NOT community edition)