Neo4j create nodes and relationships from pandas dataframe with py2neo

后端 未结 2 748
萌比男神i
萌比男神i 2021-02-04 15:43

Getting results on a pandas dataframe from a cypher query on a Neo4j database with py2neo is really straightforward, as:

>>> from pandas import DataFram         


        
2条回答
  •  执念已碎
    2021-02-04 16:37

    You can use DataFrame.iterrows() to iterate through the DataFrame and execute a query for each row, passing in the values from the row as parameters.

    for index, row in df.iterrows():
        graph.run('''
          MATCH (a:Label1 {property:$label1})
          MERGE (a)-[r:R_TYPE]->(b:Label2 {property:$label2})
        ''', parameters = {'label1': row['label1'], 'label2': row['label2']})
    

    That will execute one transaction per row. We can batch multiple queries into one transaction for better performance.

    tx = graph.begin()
    for index, row in df.iterrows():
        tx.evaluate('''
          MATCH (a:Label1 {property:$label1})
          MERGE (a)-[r:R_TYPE]->(b:Label2 {property:$label2})
        ''', parameters = {'label1': row['label1'], 'label2': row['label2']})
    tx.commit()
    

    Typically we can batch ~20k database operations in a single transaction.

提交回复
热议问题