从neo4j-driver cypher查询创建iGraph

时间:2017-01-23 22:08:34

标签: python neo4j igraph

我正在尝试做类似于this的操作,但是使用neo4j-driver而不是py2neo。当我运行以下代码时,我得到了查询返回的所有节点的列表,但是我的图形不会创建任何节点。

from igraph import Graph
from neo4j.v1 import GraphDatabase, basic_auth

driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "pass123"))
session = driver.session()

result = session.run("MATCH (a:author)-[r:PUBLISHED]->(p:paper) RETURN a,r,p")

for record in result:
  print(record)

g = Graph.TupleList(result)
print(g)
session.close()

控制台结果:

<Record a=<Node id=946 labels=set([u'author']) properties={u'name': u'a9', u'id': u'9'}> r=<Relationship id=950 start=946 end=955 type=u'PUBLISHED' properties={}> p=<Node id=955 labels=set([u'paper']) properties={u'year': 2009, u'id': u'9', u'name': u'p9'}>>
<Record a=<Node id=946 labels=set([u'author']) properties={u'name': u'a9', u'id': u'9'}> r=<Relationship id=949 start=946 end=953 type=u'PUBLISHED' properties={}> p=<Node id=953 labels=set([u'paper']) properties={u'year': 2007, u'id': u'7', u'name': u'p7'}>>
IGRAPH UN-- 0 0 --
+ attr: name (v)

有人可以告诉我为什么这不起作用吗?

1 个答案:

答案 0 :(得分:2)

Py2neo的cypher.execute方法返回一个对象,该对象本质上是一个dicts(或命名元组)列表。 neo4j驱动程序没有。相反,您需要遍历session.run返回的游标对象,并构造一个元组列表以传递给igraph构造函数。这里的示例是使用来自BuzzFeed Trumpworld graph的数据,这恰好就是我目前在Neo4j中所拥有的数据,因此请根据您的需求调整查询:

from igraph import Graph
from neo4j.v1 import GraphDatabase, basic_auth

driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "pass123"))
session = driver.session()

result = session.run("MATCH (p1:Person)-[r]->(p2:Person) RETURN p1.name AS name1, p2.name AS name2")
nodelist = []
for record in result:
    nodelist.append((record["name1"], record["name2"]))

nodelist是一个元组列表,如下所示:

>>> print(nodelist)

[('RUDY GIULIANI', 'WILBUR ROSS'),
('GARY COHN', 'DONALD J. TRUMP'),
('DAN COATS', 'DONALD J. TRUMP'),
('MICHAEL POMPEO', 'DONALD J. TRUMP'),
('OMAROSÉ ONEE MANIGAULT', 'DONALD J. TRUMP'),
('MICK MULVANEY', 'DONALD J. TRUMP'),
('ALEX SHNAIDER', 'DONALD J. TRUMP'),
('MEHMET ALI YALCINDAG', 'DONALD J. TRUMP'),
('MANGAL PRABHAT LODHA', 'DONALD J. TRUMP'),
('ROGER KHAFIF', 'DONALD J. TRUMP')...

然后实例化igraph对象:

g = Graph.TupleList(nodelist)

我们可以在此图表上运行PageRank,并查看哪个节点具有最高的PageRank作为完整性检查:

pg = g.pagerank()
max_pg = max(pg)
[g.vs[idx]["name"] for idx, pg in enumerate(pg) if pg == max_pg]

结果是:

['DONALD J. TRUMP']