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

前端 未结 1 642
既然无缘
既然无缘 2021-01-15 14:49

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

1条回答
  •  被撕碎了的回忆
    2021-01-15 15:11

    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.

    
    

    Who has the highest degree?

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

    Of course it's Tom Hanks.

    [u'Tom Hanks']
    

    0 讨论(0)
提交回复
热议问题