Boris Gorelik
Boris Gorelik

Reputation: 31767

Loading neo4j query result into python's `igraph` graph

How would you load the results of a Cypher query into an igraph in python, keeping all the edge and vertex attributes?

Upvotes: 2

Views: 2481

Answers (1)

Nicole White
Nicole White

Reputation: 7790

This is easy with py2neo and igraph's Graph.TupleList method.

You'll need both py2neo and igraph installed.

pip install py2neo
pip install python-igraph

Both of these packages rely on a Graph class so we should alias them as something else on import.

from py2neo import Graph as pGraph
from igraph import Graph as iGraph

First, connect to Neo4j with py2neo's Graph object.

neo4j = pGraph()

Then write a Cypher query to return an edgelist. Let's say we have the example movie dataset loaded into Neo4j and we want an edgelist of actors who have acted together.

query = """
MATCH (p1:Person)-[:ACTED_IN]->(:Movie)<-[:ACTED_IN]-(p2:Person)
RETURN p1.name, p2.name
"""

data = neo4j.cypher.execute(query)
print data[0]

This gives us an edgelist of actors who have acted together.

p1.name      | p2.name    
--------------+-------------
Hugo Weaving | Emil Eifrem

Conveniently, py2neo's Graph.cypher.execute returns something like a list of named tuples, so we can pass this directly to igraph's Graph.TupleList method to create an igraph object.

ig = iGraph.TupleList(data)
print ig

And now we have an igraph object.

<igraph.Graph at 0x1083a2908>

Who has the highest degree?

best = ig.vs.select(_degree = ig.maxdegree())["name"]
print best

Of course it's Tom Hanks.

[u'Tom Hanks']

Upvotes: 6

Related Questions