Search code examples
python-3.xneo4jpy2neo

Creating nodes and Realtionships in Neo4j Dynamically


I have a Directory structure like below

C:\Users\Shiva\Desktop\Internship\shiva.txt

I want to Create nodes as each folder and I want a relationship between them.

Example Graph will be like this

C <-contains-> Users <-contains-> Shiva <-contains-> desktop <-contains-> 

Internship <-contains-> shiva.txt

I am going to pass the path in a dynamic way.


Solution

  • I imagine a solution could be to use Python's os.walk()

    This function can be used as this:

    from os import walk
    
    def add_node(root, elem):
        query = 'MATCH (r: Directory {{name: "{0}"}})\
                    CREATE (e: Directory {{name: "{1}")\
                    CREATE (r)-[l: CONTAINS]->(e)\
                    RETURN id(e), id(l)'.format(root, elem)
        # Run the query with your driver instance here
    
    # Add the node for root here
    
    for root, dirs, files in os.walk(your_dynamic_path, topdown = False):
        for dir in dirs:
            add_node(root, dir)
        for file in files:
            add_node(root, file)
    

    With add_node(root, elem) being a function adding/merging the node elem to your Neo4J graph and adding the relation you want.