Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j Bolt StatementResult to Pandas DataFrame

Based on example from Neo4j

from neo4j.v1 import GraphDatabase, basic_auth

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

  session.run("CREATE (a:Person {name:'Arthur', title:'King'})")

  result = session.run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title")
  for record in result:
      print("%s %s" % (record["title"], record["name"]))

  session.close()

Here result is of datatype neo4j.v1.session.StatementResult. How to access this data in pandas dataframe without explicitly iterating?

pd.DataFrame.from_records(result) doesn't seem to help.

This is what I have using list comprehension

resultlist = [[record['title'], record['name']] for record in result]
pd.DataFrame.from_records(resultlist, columns=['title', 'name'])
like image 215
Joel Avatar asked Dec 05 '22 17:12

Joel


2 Answers

The best I can come up with is a list comprehension similar to yours, but less verbose:

df = pd.DataFrame([r.values() for r in result], columns=result.keys())

The py2neo package seems to be more suitable for DataFrames, as it's fairly straightforward to return a list of dictionaries. Here's the equivalent code using py2neo:

import py2neo

# Some of these keyword arguments are unnecessary, as they are the default values.
graph = py2neo.Graph(bolt=True, host='localhost', user='neo4j', password='neo4j')

graph.run("CREATE (a:Person {name:'Arthur', title:'King'})")

query = "MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title"
df = pd.DataFrame(graph.data(query))
like image 110
root Avatar answered Dec 22 '22 05:12

root


Casting result records into dictionaries does the trick:

df = pd.DataFrame([dict(record) for record in result])
like image 29
user1461617 Avatar answered Dec 22 '22 03:12

user1461617