Search code examples
graphneo4jcypherspring-data-neo4j

Find high weighted mutal friend in Neo4J Database


enter image description hereenter image description hereI am new in graph database and I am making a fiends relationship. So, here in the screen shot you can see R<->A, R<->B, R<->C (<-> follow each other), now you can see A->D,E,G,H and B->D,F,G,H and C->H,I now you can see the H is common in all these and D and G node common for A and B. So, its a very high possibility that H should be a friend of R and D and G also friend of R. So, could anyone know to write a cypher query to get the H,D and G node.

@nimrod answer is totally correct and here is the final cypher query

MATCH(u:User{name:"R"})-[:FOLLOWS]->(:User)-[:FOLLOWS]->(unew:User)
WITH COUNT(unew) AS totalNew,unew as finalUsers
WHERE totalNew>=2 AND unew.name<>"R"
Return totalNew,finalUsers 

Solution

  • One option is:

    MATCH (r{name: 'R'})-->()-->(b)
    WITH count(b) as itemsCount, b.name as name
    WHERE itemsCount >= 2
    RETURN name, itemsCount
    

    Which for the example data:

    MERGE (nr:Node {name:"R"})
    MERGE (na:Node {name:"A"})
    MERGE (nb:Node {name:"B"})
    MERGE (nc:Node {name:"C"})
    MERGE (nd:Node {name:"D"})
    MERGE (ne:Node {name:"E"})
    MERGE (nf:Node {name:"F"})
    MERGE (ng:Node {name:"G"})
    MERGE (nh:Node {name:"H"})
    MERGE (ni:Node {name:"I"})
    
    
    MERGE (nr)-[:FOLLOWS]->(na)
    MERGE (nr)-[:FOLLOWS]->(nb)
    MERGE (nr)-[:FOLLOWS]->(nc)
    MERGE (na)-[:FOLLOWS]->(nd)
    MERGE (na)-[:FOLLOWS]->(ne)
    MERGE (na)-[:FOLLOWS]->(ng)
    MERGE (na)-[:FOLLOWS]->(nh)
    MERGE (nb)-[:FOLLOWS]->(nd)
    MERGE (nb)-[:FOLLOWS]->(nf)
    MERGE (nb)-[:FOLLOWS]->(ng)
    MERGE (nb)-[:FOLLOWS]->(nh)
    MERGE (nc)-[:FOLLOWS]->(nh)
    MERGE (nc)-[:FOLLOWS]->(ni)
    

    returns:

    ╒════╤══════════╕
    │name│itemsCount│
    ╞════╪══════════╡
    │"H" │3         │
    ├────┼──────────┤
    │"D" │2         │
    ├────┼──────────┤
    │"G" │2         │
    └────┴──────────┘