Getting relations for visualisation

Hi everyone,

I want to draw a graph (nodes and relations). I try to get relations through python lib neo4j, but it doesn't work: I can't give relations (I have it, if I execute the query via Neo4j Browser). How can I get relations? What is better way to draw all graph looks like Neo4j Browser?

My simple code

from neo4j import GraphDatabase, Result, Transaction, Session
from neo4j.graph import Graph


def print_graph(tx: Transaction) -> None:
    result: Result = tx.run("MATCH (a) Return *")
    graph: Graph = result.graph()

    print(f"nodes count is {len(graph.nodes)}")  # It will be 3
    print(f"relationships count is {len(graph.relationships)}")  # It will be 0


if __name__ == "__main__":
    driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j", "changeme"))

    with driver.session() as session:  # type: Session
        session.read_transaction(print_graph)

    driver.close()

the browser makes 2 calls if i'm not mistaken
the first is getting your data and then the second getting all relationships between all the nodes that came back by collecting all the node ids and then using them in the second call.

"[1,2,3]" below is the array of the node ids that came in the first request

match a-[r]-b where id(a) in [1,2...] and id(b) in [1,2,3...] return r

The default setting in Neo4j Browser is to connect the nodes together. If you go to the settings pane (Settings cog on left hand side), then scroll down to Graph Visualization, untick "Connect result nodes" and re-run the result you will just see the nodes without relationships between them.

In order to get a count of the relationships you will also have to return them in the query.

MATCH (start)-[r]->(end)
RETURN start, r, end

However, returning everything from a larger graph may take a long time. Instead you could do something like...

MATCH (n) 
 // Limit the result as Neo4j Browser would do
WITH n LIMIT 25

// Get the neighbouring nodes
MATCH (n)-[r]->(other) 

// Aggregate by relationship type
WITH n, type(r) AS relationship, collect(other) AS nodes. 

// Aggregate by node
RETURN n, collect({ relationship: relationship, nodes: nodes}) AS relationships

This will give you one row for each of those initial 25 nodes, then an array of relationship types and the collected nodes, along the lines of:

[
  { relationship: 'ACTED_IN', nodes: [ ... ]},
  { relationship: 'DIRECTED', nodes: [ ... ]}
]

Limit your results to certain labels and relationship types where possible ;)

Great! Many thanks for the solution!