Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Wednesday 28 February 2024

How to insert data in Neo4j graph database

Below is an example of how to insert data into a Neo4j database using the official Neo4j Python driver called neo4j. Before running this code, make sure you have Neo4j installed and running on your local machine or a remote server.


from neo4j import GraphDatabase


Define the Neo4j connection URI and credentials

uri = "bolt://localhost:7687"

username = "your_username"

password = "your_password"


Define a function to insert data into Neo4j

def insert_data(tx, name, age):

    tx.run("CREATE (p:Person {name: $name, age: $age})", name=name, age=age)


Main function to connect to Neo4j and insert data

def main():

     Connect to the Neo4j database

    with GraphDatabase.driver(uri, auth=(username, password)) as driver:

         Start a session

        with driver.session() as session:

             Define some sample data

            data = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]

             Insert each data point into Neo4j

            for name, age in data:

                session.write_transaction(insert_data, name, age)

            print("Data inserted successfully!")


Run the main function

if __name__ == "__main__":

    main()


This code snippet does the following:


1. Imports the GraphDatabase class from the neo4j package.

2. Defines the Neo4j connection URI, username, and password.

3. Defines a function insert_data to insert a person node with properties (name, age) into Neo4j.

4. Defines a main function that connects to the Neo4j database, starts a session, defines some sample data, and inserts each data point into Neo4j using a transaction.

5. Runs the main function when the script is executed.


Make sure to replace "bolt://localhost:7687", "your_username", and "your_password" with your actual Neo4j connection details. You can modify the data list to insert different data points into Neo4j.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.