Search code examples
pythonneo4jneo4j-python-driver

session.run() doesn't run properly when called from a self made library using python


I have made a library of various functions in python which when called maps relationships between nodes. I have been facing issues as and when I call those function from the library they tend to work occasionally. When I run the same code in the main file it executes perfectly. My question being, is it not recommended to run queries for neo4j from a SELF MADE library.

I have a function that creates a relation between node A to node B. It is in a loop that runs for 5 times. But surprisingly it creates just one or two relation between the respective nodes. The same code when I run in the main file run perfectly.

Can someone guide me through this as when I searched online I couldn't get any answers.

[EDIT 1]

import pymongo
from neo4j.v1 import GraphDatabase, basic_auth

class basics:
    def OEE(shift_length, break_time, stop_time, ideal_cycle_time, total_count, rejected_count, machine_name):
        driver = GraphDatabase.driver("bolt://172.104.44.80:7687", auth=basic_auth("neo4j", "root")) #Connects to tthe neo4j server
        session = driver.session() #Creates a session

        #avb = availability(shift_length, break_time, stop_time)
        planned_production_time = float(shift_length) - float(break_time)
        run_time = float(planned_production_time) - float(stop_time)
        avb = float(run_time) / float(planned_production_time)

        #perf = performance(ideal_cycle_time, total_count, shift_length, break_time, stop_time)
        perf = (float(ideal_cycle_time) * float(total_count)) / float(run_time)

        #qual = quality(rejected_count, total_count)
        good_count = float(total_count) - float(rejected_count)
        qual = float(good_count) / float(total_count)

        oee = float(avb) * float(perf) * float(qual)

        session.run("MATCH (n:Machine), (a:OEE) WHERE n.machine = {machine} AND a.name = 'OEE' CREATE (n)-[r:abc]->(a) RETURN r",
                    {"machine": machine_name})
        return oee 

The above mentioned code is the function. It is in a library called basics and i call it in the main python code as:

import basics
basics.OEE(*all the parameters*)

(I have removed the for loop over here for some reason but this code too maps occasionally.)


Solution

  • Your code has one issue, and one improvement :

    • a session opened must be closed somewhere. You opened one at the begin, but I don't see its closure.
    • driver instance must be shared across all your Neo4j actions.A driver has a pool of connections to the database, so you can reuse them. In your code, you create each time a new connection to the database.

    Cheers.