Constraints

Unique node property constraints

Unique node property constraints map to @unique directives used in your type definitions, which has the following definition:

"""Informs @neo4j/graphql that there should be a uniqueness constraint in the database for the decorated field."""
directive @unique(
    """The name which should be used for this constraint. By default; type name, followed by an underscore, followed by the field name."""
    constraintName: String
) on FIELD_DEFINITION

Additionally, the usage of the @id directive by default implies that there should be a unique node property constraint in the database for that property.

Using this directive does not automatically ensure the existence of these constraints, and you will need to run a function on server startup. See the section Asserting constraints below for details.

@unique directive usage

@unique directives can only be used in GraphQL object types representing nodes, and will only be applied for the "main" label for the node. You can find some examples below.

In the following example, a unique constraint will be asserted for the label Colour and the property hexadecimal:

type Colour {
    hexadecimal: String! @unique
}

In the next example, a unique constraint with name unique_colour will be asserted for the label Colour and the property hexadecimal:

type Colour {
    hexadecimal: String! @unique(constraintName: "unique_colour")
}

The @node directive is used to change the database label mapping in this next example, so a unique constraint will be asserted for the label Color and the property hexadecimal:

type Colour @node(label: "Color") {
    hexadecimal: String! @unique
}

In the following example, the additionalLabels argument of the @node directive is ignored when it comes to asserting constraints, so the outcome is the same as the example above:

type Colour @node(label: "Color", additionalLabels: ["Hue"]) {
    hexadecimal: String! @unique
}

Asserting constraints

In order to ensure that the specified constraints exist in the database, you will need to run the function assertConstraints, the full details of which can be found in the API reference. A simple example to create the necessary constraints might look like the following, assuming a valid driver instance in the variable driver. This will create two constraints, one for each field decorated with @id or @unique:

const typeDefs = gql`
    type Colour {
        id: ID! @id
        hexadecimal: String! @unique
    }
`;

const neoSchema = new Neo4jGraphQL({ typeDefs, driver });

await neoSchema.assertConstraints({ options: { create: true }});