0
votes

I am new to neo4j and I have a following relationship like this

A is a friend of B
A is a friend of E
B is a friend of C
C is a friend of D
C is a friend of F
E is a friend of G
G is a friend of H

I want a result of A's friends' friends where A is not currently a friend by ordering the numbers of friends by DESC.The expecting result is

C ---> 2
D ---> 1
F ---> 1
G ---> 1
H ---> 1

A,B,C,D,E,F,G,H are nodes and they are connected with a relationship of [:friends]. It would be much grateful if anyone can give a solution for this.

3
What query have you tried so far?Luanne
Can you provide the algorithm for getting 2 for C and 1 for the other people?cybersam
@Luanne I found a solution.I posted it.Susampath
@cybersam according to the example c has 2 friends and others has one friendSusampath

3 Answers

1
votes
MATCH (a)-[:friends]-(f)-[:friends]-(fof) WHERE a.name = 'A' AND NOT (a)-[:friends]-(fof)
WITH DISTINCT fof
MATCH ( fof)-[:friends]-(l) 
RETURN fof.name , COUNT (DISTINCT l)
0
votes

I found a solution when referring to Neo4j documentation.

match (a:users {userId:'1234'})-[e:friends]-(b:users)
with collect(b) as excluded
match (b:users)-[r:friends]-(fof:users)
with collect(fof) as fofCollect,excluded,fof,count(r) as relationCount
where none (fof in fofCollect where fof in excluded)
return fof.FIRST_NAME,fof.userId,relationCount
order by relationCount desc 
0
votes

This query returns your expected counts:

// Get a collection of all friends of 'A'
MATCH (a)-[:friends]-(f)
WHERE a.name = 'A'
WITH a, COLLECT(f) AS fs

// Get all friends of friends (fof) who are not already known to 'A'
UNWIND fs AS f
MATCH (f)-[:friends*]-(fof)
WHERE NOT fof IN fs+a

// Count how many of each fof's friends are not already known to 'A'
WITH DISTINCT a, fs, fof
MATCH (fof)-[:friends]-(l)
WHERE NOT l IN fs+a
RETURN fof.name, COUNT(l)

Note: For large DBs, you will want to impose a reasonable upper bound on the variable-length relationship pattern (f)-[:friends*]-(fof) to avoid the query taking a very long time or running out of memory. E.g., (f)-[:friends*..7]-(fof).