Comparing array values in with cypher / neo4j

2019-03-29 06:07发布

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?

标签: neo4j cypher
1条回答
乱世女痞
2楼-- · 2019-03-29 06:49

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

查看更多
登录 后发表回答