2
votes

I am new to Neo4j and trying to get friends of friends of friends (those who are 3 degrees away) and are also not in a 1 or 2 degree relation through a different path. I am using the below cypher which seems to take a lot of time

MATCH p = (origin:User {ID:51})-[:LINKED*3..3]-(fof:User)

WHERE NOT (origin)-[:LINKED*..2]-(fof)

RETURN fof.Nm

ORDER BY Nm LIMIT 1000

Profiling the query shows that the majority of time is taken by the "WHERE NOT" condition as it cross checks every resultant node against all the 1 and 2 degree nodes.

Am I doing something wrong here or is there a more optimized way of doing this?

Just to add, the property UsrID in label User is indexed.

1

1 Answers

0
votes

There are probably a few ways you could do it. Here's one to try:

MATCH path = (origin:User {ID:51})-[:LINKED*3..3]-(fofof:User)
WHERE NOT(fofof IN (nodes(path)[0..-1]))
RETURN fofof.Nm
ORDER BY fofof.Nm LIMIT 1000

You could also be more explicit:

MATCH path = (origin:User {ID:51})-[:LINKED]-(f:User)-[:LINKED]-(fof:User)-[:LINKED]-(fofof:User)
WHERE fofof <> f AND fofof <> fof
RETURN fofof.Nm
ORDER BY fofof.Nm LIMIT 1000