问题描述
如何将Cypher查询的结果加载到python中的igraph
中,同时保留所有的edge和vertex属性?
How would you load the results of a Cypher query into an igraph
in python, keeping all the edge and vertex attributes?
推荐答案
使用py2neo和igraph的Graph.TupleList
方法很容易.
This is easy with py2neo and igraph's Graph.TupleList
method.
您需要同时安装py2neo和igraph.
You'll need both py2neo and igraph installed.
pip install py2neo
pip install python-igraph
这两个软件包都依赖于Graph
类,因此我们在导入时应将它们作为其他别名.
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
首先,使用py2neo的Graph
对象连接到Neo4j.
First, connect to Neo4j with py2neo's Graph
object.
neo4j = pGraph()
然后编写一个Cypher查询以返回边缘列表.假设我们已将示例电影数据集加载到Neo4j中,并且我们希望获得一起表演的演员的边缘列表.
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
方便地,py2neo的Graph.cypher.execute
返回类似于命名元组列表的内容,因此我们可以将其直接传递给igraph的Graph.TupleList
方法以创建igraph对象.
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
现在我们有了一个igraph对象.
And now we have an igraph object.
<igraph.Graph at 0x1083a2908>
谁的学历最高?
best = ig.vs.select(_degree = ig.maxdegree())["name"]
print best
当然是汤姆·汉克斯(Tom Hanks).
Of course it's Tom Hanks.
[u'Tom Hanks']
这篇关于将neo4j查询结果加载到python的`igraph`图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!