user2608171
user2608171

Reputation: 39

Unique elements in collections in Neo4j

Is there an easy way to ensure that elements in a collection in Neo4j/Cypher are unique? Something like making the collection into a hashset?

Upvotes: 2

Views: 1630

Answers (3)

LameCoder
LameCoder

Reputation: 1297

Depending on what you are trying to do, you may be able to do this with Cypher.

For example, if you just want to add an item to the property only if it does not exist you can do so in a couple of ways.

This example filters the query and is useful if the collection modification is the only property being modified:

START n=node({id}) WHERE NONE(x IN n.cols WHERE x = {val}) SET n.cols = n.cols + {val} RETURN n;

This next example will end up always modifying the property, but would ensure uniqueness and would be a useful method if some other properties also need to be modified at the same time, however a side effect is that the order of the items will change:

START n=node({id})
WITH n, FILTER(x IN n.cols WHERE x <> {val}) as existingCols 
SET n.cols = existingCols + {val}
RETURN n 

Upvotes: 2

jjaderberg
jjaderberg

Reputation: 9952

In cypher, you can work with collections (1, 2) and you can ensure uniqueness by using the DISTINCT modifier, as in

...
MATCH (fred)-[:LIKES]->(fruit)<-[:LIKES]-(fruit_friend)
WITH fred, COLLECT(DISTINCT(fruit_friend)) as unique_fruit_friends
...

Upvotes: -1

Nicholas
Nicholas

Reputation: 7501

Entity(Node/Relationship) properties do not have a concept of Set, they have key/values, and an allowed value is a primitive/String array.

If you want Set like features, it will be up to your application that is inserting the data to enforce this uniqueness.

Cypher doesn't have any functionality for this either.

Upvotes: 1

Related Questions