Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing array values in with cypher / neo4j

Tags:

neo4j

cypher

I have a graph of members and the items that they've looked at.

This data is going to be used to recommend items based on items that similar members have looked at. I'd like to sort the items based on how similar the colors of the items are. The colors are stored on the items in an array (["red", "blue", "green"]). Is there any way in cypher to compare arrays to see how many elements they have in common?

like image 242
blim8183 Avatar asked Dec 09 '13 23:12

blim8183


2 Answers

Given two nodes, n and m, that look something like:

CREATE ({id: 1, color: ["red", "blue", "green", "yellow"]})
CREATE ({id: 2, color: ["red", "blue", "green", "white"]})

You can do something like this:

MATCH n, m
WHERE n.id = 1 AND m.id = 2
RETURN length(FILTER(x in n.color WHERE x in m.color))

The FILTER function iterates through the n.color array, binding the current value to x(arbitrarily chosen by me, could be different). The predicate (x in m.color) is checked for each x value, and if it evaluates to true, that element is pushed into the new array that FILTER returns. You can leave it at that to see the intersection of the two arrays (red, blue, and green in this case), or wrap it in the length function to see the number of colors shared between the two nodes (3 in this case).

Check out the full FILTER docs here: http://docs.neo4j.org/chunked/milestone/query-functions-collection.html#functions-filter

like image 174
freethejazz Avatar answered Sep 25 '22 03:09

freethejazz


The solution given above is good. But in the new version(4.0), they have made some changes. The Filter() method is deprecated and list() is

Restricted to only work on paths

in Version 4.0

They replaced the filter with List comprehension so instead of using the above code

MATCH n, m
WHERE n.id = 1 AND m.id = 2
RETURN length(FILTER(x in n.color WHERE x in m.color))

I recommend you to use this one.

MATCH n, m
WHERE n.id = 1 AND m.id = 2
RETURN size([x in n.color WHERE x in m.color])
like image 36
Dev Gaud Avatar answered Sep 25 '22 03:09

Dev Gaud