Reputation: 14699
I must be doing something incorrectly, or have a misconceptions about constraints and indexing. I have the following:
CREATE CONSTRAINT ON (u:User) ASSERT u.user_id IS UNIQUE
and
CREATE INDEX ON :User(user_id)
I've tried alternating the order, but regardless, I'm getting:
Neo.ClientError.Schema.ConstraintAlreadyExists
or
Neo.ClientError.Schema.IndexAlreadyExists
depending on the ordering.
I don't understand why I wouldn't be able to do this. I want look-ups to be fast for a user_id
, which is why I'm indexing, and I also want to make sure that user_id
is unique, which is why I have a constraint.
What am I misunderstanding? How should I go about doing this?
Upvotes: 9
Views: 2571
Reputation: 5784
As Luanne said, adding a uniqueness constraint on a property will also create an index on it.
To make user_id
unique and indexed, you should use this:
CREATE CONSTRAINT ON (user:User) ASSERT user.user_id IS UNIQUE
>>> Added 1 constraint, returned 0 rows in 107 ms
To verify that the index has been added correctly:
:SCHEMA
>>> Indexes
>>> ON :User(user_id) ONLINE (for uniqueness constraint)
>>>
>>> Constraints
>>> ON (user:User) ASSERT user.user_id IS UNIQUE
Note, if you try to remove the index that has been automatically created by the uniqueness constraint, it will fail:
DROP INDEX ON :User(user_id)
>>> Unable to drop index on :User(user_id): Index belongs to constraint: :User(user_id)
The correct way to remove it is to remove the uniqueness contraint:
DROP CONSTRAINT ON (user:User) ASSERT user.user_id IS UNIQUE
>>> Removed 1 constraint, returned 0 rows in 108 ms
Upvotes: 2
Reputation: 19
Creating a constraint will automatically create an index on that property. You have to create an index manually if you create an index only.
http://docs.neo4j.org/chunked/stable/query-schema-index.html
http://docs.neo4j.org/chunked/stable/query-constraints.html
Upvotes: 0
Reputation: 19373
Adding the unique constraint will also add the index on that property- so the unique constraint is sufficient.
See http://docs.neo4j.org/chunked/stable/query-constraints.html
"Note that adding a uniqueness constraint on a property will also add an index on that property, so you cannot add such an index separately. Cypher will use that index for lookups just like other indexes. If you drop a constraint and still want an index on the property, you will have to create the index."
Upvotes: 13