tim
tim

Reputation: 1482

How to get a unique list in neo4j cypher?

For example, I have a list [1,1,2],

What I expect result is [1,2].

what I tried

return [distinct x in [1,1,2]]

Distinct does not work , this will throw an error.

something might help

is there any list function I can use in neo4j to achieve this?

Upvotes: 3

Views: 6004

Answers (3)

gooneraki
gooneraki

Reputation: 81

Something with REDUCE?

REDUCE(distinctElements = [], element IN YOUR_ARRAY | CASE WHEN NOT element in distinctElements THEN distinctElements + element ELSE distinctElements END)

Upvotes: 1

Jasper Blues
Jasper Blues

Reputation: 28756

You could use the APOC library's apoc.coll.toSet([list]) function.

These functions are documented here. The same manual includes details on how to install the APOC plugin.

EDIT: Without APOC

Here's one way to return a set from a list in CYPHER - unwind the list and then collect only the distinct values from it:

unwind [1, 1, 2, 3, 3, 4, 5] as nums
with distinct nums return collect(nums);

or

unwind [1, 1, 2, 3, 3, 4, 5] as nums
return collect(distinct nums);

Upvotes: 6

cybersam
cybersam

Reputation: 66989

The COLLECT aggregating function supports the DISTINCT option:

UNWIND [1,1,2] AS list
RETURN COLLECT(DISTINCT list);

Upvotes: 3

Related Questions