Susampath
Susampath

Reputation: 716

Neo4j Cypher Queries

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.

Upvotes: 0

Views: 77

Answers (3)

cybersam
cybersam

Reputation: 67044

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).

Upvotes: 0

TheTeacher
TheTeacher

Reputation: 510

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)

Upvotes: 1

Susampath
Susampath

Reputation: 716

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 

Upvotes: 0

Related Questions