Prev |  | Next

## 5.8. Find people based on mutual friends and groups

Figure 5.6. Graph

In this scenario, the problem is to determine mutual friends and groups, if any, between persons. If no mutual groups or friends are found, there should be a `0` returned.

Query.

    MATCH (me { name: 'Joe' }),(other)
    WHERE other.name IN ['Jill', 'Bob']
    OPTIONAL MATCH pGroups=(me)-[:member_of_group]->(mg)<-[:member_of_group]-(other)
    OPTIONAL MATCH pMutualFriends=(me)-[:knows]->(mf)<-[:knows]-(other)
    RETURN other.name AS name, count(DISTINCT pGroups) AS mutualGroups,
      count(DISTINCT pMutualFriends) AS mutualFriends
    ORDER BY mutualFriends DESC

The question we are asking is — how many unique paths are there between me and Jill, the paths being common group memberships, and common friends. If the paths are mandatory, no results will be returned if me and Bob lack any common friends, and we don’t want that. To make a path optional, you have to make at least one of it’s relationships optional. That makes the whole path optional.

Result

name | mutualGroups | mutualFriends
--- | --- | ---
2 rows
`"Jill"` | `1` | `1`
`"Bob"` | `1` | `0`

Copyright © 2014 Neo Technology

Prev | Up | Next
| Home |