I'm using the neo4j Python driver to create and retrieve Person nodes in a Neo4j database. The nodes are successfully created and visible in the Neo4j browser, but my Python script returns zero records when querying these nodes

from neo4j import GraphDatabase

# Connect to the Neo4j database using Bolt protocol
driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("test_user", "test_password"))

def create_person(tx, name):
result = tx.run("CREATE (:Person {name: $name})", name=name)
summary = result.consume()
print(f"Created node: {name}, {summary.counters.nodes_created} nodes created")

def get_persons(tx):
query = """
MATCH (p:Person)
RETURN p.name AS name
"""
result = tx.run(query)
return [record["name"] for record in result]

with driver.session() as session:
session.execute_write(create_person, "Alice")
session.execute_write(create_person, "Bob")
session.execute_write(create_person, "Charlie")

with driver.session() as session:
persons = session.execute_read(get_persons)
if not persons:
print("No Person nodes found.")
else:
print(f"Found {len(persons)} Person nodes:")
for person in persons:
print(person)

driver.close()

output:

Created node: Alice, 1 nodes created
Created node: Bob, 1 nodes created
Created node: Charlie, 1 nodes created
The query MATCH (p:Person) RETURN p.name AS name returned 0 records in 0 ms.

Additional Information:

  • Neo4j Version: 5.22.0 Enterprise edition
  • Python Driver Version: 5.19.0
  • The Person nodes are visible in the Neo4j browser when querying MATCH (n:Person) RETURN n LIMIT 25.

Question:

Why is my Python script returning zero records even though the nodes are successfully created and visible in the Neo4j browser? Are there any permissions or session management issues that I might be overlooking?

Hi :wave:

Are you running against a cluster? In such case, this could be a problem or reading stale writes. You'd need to use bookmarks or a bookmark manager to causally chain your sessions. Have a look at this documentation: Coordinate parallel transactions - Neo4j Python Driver Manual.

For you minimal example you could also just work in the same session.
It should handle the read-your-own-writes scenario.
Of course this is not a solution if the write and read code is separated and you are using multiple sessions. Then you have to either live with the eventual consistency of the cluster or explicitly use the bookmarks, as Rouven suggested.

def create_person(tx, name):
    result = tx.run("CREATE (:Person {name: $name})", name=name)
    summary = result.consume()
    print(f"Created node: {name}, {summary.counters.nodes_created} nodes created")

def get_persons(tx):
    query = """
    MATCH (p:Person)
    RETURN p.name AS name
    """
    result = tx.run(query)
    return [record["name"] for record in result]

with GraphDatabase.driver(
    "neo4j://localhost:7687",
    auth=("test_user", "test_password"),
) as driver:
    with driver.session(
        # specify the database name is possible for better performance
        databse="neo4j",
    ) as session:
        session.execute_write(create_person, "Alice")
        session.execute_write(create_person, "Bob")
        session.execute_write(create_person, "Charlie")
        persons = session.execute_read(get_persons)
        if not persons:
            print("No Person nodes found.")
        else:
            print(f"Found {len(persons)} Person nodes:")
        for person in persons:
            print(person)

Hi Gerrit - I am creating an app using python and flask and look to use neo4j rather than SQL. I am grateful for any help you can give me to get started. This appears to be the first time I have not had a connection error.

I am an absolute newbie at using the python drive to run the simplest possible code that connects with a neo4j database. I used your code (admittedly not the absolute simplest like a Hello World! function in python) along with driver.close() at the end.

Got error:

neo4j.exceptions.ConfigurationError: Unexpected config keys: databse

Traceback:

(.venv) larryeisenberg@Mac Neo4j Learn % python3 start.py
Traceback (most recent call last):
File "/Users/larryeisenberg/PycharmProjects/Neo4j Learn/start.py", line 22, in
with driver.session(
^^^^^^^^^^^^^^^
File "/Users/larryeisenberg/PycharmProjects/Neo4jLearn/.venv/lib/python3.11/site-packages/neo4j/_sync/driver.py", line 577, in session
session_config = self._read_session_config(config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/larryeisenberg/PycharmProjects/Neo4jLearn/.venv/lib/python3.11/site-packages/neo4j/_sync/driver.py", line 585, in _read_session_config
session_config = SessionConfig(self._default_workspace_config,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/larryeisenberg/PycharmProjects/Neo4jLearn/.venv/lib/python3.11/site-packages/neo4j/_conf.py", line 325, in init
self.__update(arg)
File "/Users/larryeisenberg/PycharmProjects/Neo4jLearn/.venv/lib/python3.11/site-packages/neo4j/_conf.py", line 317, in __update
raise ConfigurationError("Unexpected config keys: "
neo4j.exceptions.ConfigurationError: Unexpected config keys: databse
(.venv) larryeisenberg@Mac Neo4j Learn %

@larrykone

not sure where in your python script but looks like a typo. shouldnt databse be database. If you search your python for databse does it find any matches.

Thank you Dana. I corrected the typo, but still have an error: (Unable to retrieve routing information)

Traceback:

(.venv) larryeisenberg@Mac Neo4j Learn % python3 start.py
Unable to retrieve routing information
Transaction failed and will be retried in 0.9282055267891798s (Unable to retrieve routing information)
Unable to retrieve routing information
Transaction failed and will be retried in 2.0540795382718255s (Unable to retrieve routing information)
Unable to retrieve routing information
Transaction failed and will be retried in 3.5454048363608326s (Unable to retrieve routing information)
Unable to retrieve routing information
Transaction failed and will be retried in 8.365545390250297s (Unable to retrieve routing information)
^CTraceback (most recent call last):
File "/Users/larryeisenberg/PycharmProjects/Neo4j Learn/start.py", line 26, in
session.execute_write(create_person, "Alice")
File "/Users/larryeisenberg/PycharmProjects/Neo4jLearn/.venv/lib/python3.11/site-packages/neo4j/_sync/work/session.py", line 757, in execute_write
return self._run_transaction(
^^^^^^^^^^^^^^^^^^^^^^
File "/Users/larryeisenberg/PycharmProjects/Neo4jLearn/.venv/lib/python3.11/site-packages/neo4j/_sync/work/session.py", line 582, in _run_transaction
sleep(delay)
KeyboardInterrupt

@larrykone

'Unable to retrieve routing information' would suggest your Python script can not connect to Neo4j. When connecting via the Neo4j Browser, what is the value for the Connect URL on the authentication page? Is your username/password test_user and test_password as described in @gerrit.meier response and 5 lines above the typo of 'databse`

Thank you for getting back to me Dana. Much appreciated!

I think this part of the code answers your questions:

with GraphDatabase.driver(
"neo4j://localhost:7687",
auth=("test_user", "test_password"),
) as driver:
with driver.session(
# specify the database name is possible for better performance
database="neo4j",

@larrykone

your code snippet of

with GraphDatabase.driver(
"neo4j://localhost:7687",
auth=("test_user", "test_password"),
) as driver:
with driver.session(
# specify the database name is possible for better performance
database="neo4j",

indicates
line 2: connect with a protocal named neo4j:// and to a Neo4j database running on localhost and listening on port 7687. localhost is effectively the same instance/OS where the script is run from

line3: connect with authentication defined as user='test_user' and password='test_password`

line 7: connect to a database which is named neo4j

but how does this compare to the same values as entered when connecting via the Neo4j Browser, which you claim you have success with and

Hi Dana - Maybe I am wasting your time and mine, but before I just go with SQLAlchemy and SQLight, I give it another try and if it does not result in a good connection I won't waste the time anymore of anyone at Neo4j.

I gather you say I have the wrong values. So what are the correct values? I am rather amazed how difficult it is to get started coding with neo4j and python to create a web app. It is amazingly easier to use python, flask and SQL Alchemy. I just don't get it. Neo4j has been around for over a decade and it's this difficult to take the first step? I wonder how many other developers have decided to just use SQL rather than fail over and over again and what should be easy and quick if compared to using SQL with python on a local server. I just don't get it.

I have been using Java driver for a few years and SDN as well. I find it easy to connect and use. I also find cypher a lot more fun and enjoyable than SQL, which have been using for a while. If you need a graph database to efficiently model your data, such as network or hierarchical data, etc, you are not going easily, if at all, do the same in a sql database.

They are both tools that have their place, and they should not be considered interchangeable.

Are you connecting to a local database or remote database in your browser?

Hi Gary,

I am trying to this all locally as I would using Flask, SQLAlchemy and Python. I am open to any guidance or suggestions that you might have. Thanks,

Larry

Can you post the full python code related to neo4j

Hi Gary,

Suggestion: show me code using python and neo4j locally that creates a connection, creates a node and then verifies that the node was created? Perhaps that is easier than you correcting bad code?

Larry

How do I get from this pic to the one where yo want me to check “Connect to Neo4j”?

(Attachment Neo4jBrowser whre from here.pdf is missing)

Here is the log if that helps. I think I have an authorization error.

(Attachment neo4j.log is missing)