Search code examples
neo4jcyphergraph-databasesspring-data-neo4j

Neo4J query for related users


I have the following example in Neo4J where users are interested in each other. There are two connections as each user can individually set a weight factor and some users may not be mutually interested in each other.

enter image description here

I want to write a Cypher query that retrieves related users for a user but also tells me which users are connected.

For example for user Fred, return Tom, Jane and also return that Jane is interested in Tom. Bob and Sarah should not be returned.

Here is what I have so far:

MATCH (u:User)-[r1:INTERESTED_IN]->(u2:User)
WHERE u.emailAddress ='[email protected]'
OPTIONAL MATCH (u)-[r2:INTERESTED_IN]->(u3:User)
OPTIONAL MATCH (u2)-[r3:INTERESTED_IN]->(u3)
RETURN u, r1, u2, r2, u3, r3

Is that along the right lines? I want to map this to a Spring Neo4J repository method but want to make sure that the query is correct and I'll be able to navigate the object graph to bring out the information above.

Any help would be appreciated.


Solution

  • This may do what you want:

    MATCH (u:User)-[:INTERESTED_IN]->(u2:User)
    WHERE u.emailAddress = '[email protected]'
    OPTIONAL MATCH (u)-[:INTERESTED_IN]->(u3:User)<-[:INTERESTED_IN]-(u2)
    RETURN u, u2, COLLECT(u3) AS mutualInterests
    

    It returns in each result row an interest of u (i.e., u2), along with their mutual interests.