ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Find Direct Connections

Cypher (Neo4j)

Goal -- WPM

Ready
Exercise Algorithm Area
1MATCH (startNode {id: $startNodeId})
2OPTIONAL MATCH (startNode)-[r]->(connectedNode)
3OPTIONAL MATCH (connectedNode)-[r2]->(startNode)
4
5WITH startNode, connectedNode
6WHERE connectedNode IS NOT NULL AND id(connectedNode) <> id(startNode)
7
8RETURN DISTINCT connectedNode
Algorithm description viewbox

Find Direct Connections

Algorithm description:

This query finds all nodes that have at least one direct relationship with a specified starting node, considering both incoming and outgoing relationships. It's useful for exploring immediate neighbors in any graph, such as finding all people directly interacting with a given user in a social network.

Algorithm explanation:

The query starts by matching the `startNode`. It then uses `OPTIONAL MATCH` clauses to find nodes connected via outgoing relationships (`(startNode)-[r]->(connectedNode)`) and incoming relationships (`(connectedNode)-[r2]->(startNode)`). The `WITH` clause passes the `startNode` and `connectedNode` to the next stage. The `WHERE` clause filters out null `connectedNode`s (from the `OPTIONAL MATCH`) and ensures the `connectedNode` is not the `startNode` itself. Finally, `RETURN DISTINCT connectedNode` ensures each unique connected node is listed only once. The time complexity is roughly O(degree(startNode)), making it efficient for finding immediate neighbors. Space complexity is O(degree(startNode)). Edge cases include isolated nodes (no connections) and self-loops (handled by the `id(connectedNode) <> id(startNode)` check).

Pseudocode:

1. Match the starting node.
2. Optionally match nodes connected by outgoing relationships.
3. Optionally match nodes connected by incoming relationships.
4. Combine results and filter out the starting node itself and any null matches.
5. Return distinct connected nodes.