Stefan
Stefan

Reputation: 1553

Python & Neo4j: Check for empty statementresult

I am using a python script to do a cypher statement that should return 0..n results. I use a foreach loop to get all values:

for column1 in results['col1']:
    # do some stuff

If the Statementresult is empty, the loop will not be executed - of course. I want to check the Statementresult before. If there is no result the python script shall do something different, e. g. printing a message.

I tried to compare the statementresult with None (but its an object, even if its empty), or use the first index. I looked for a solution in the documentation and online but could not find anything. How can I check if its empty or not? Is it also possible to get e. g. the 3rd result if it exists?

Thanks! Stefan

Upvotes: 2

Views: 1487

Answers (2)

Albert S
Albert S

Reputation: 2602

if (results.peek() is None):
   # empty object

Upvotes: 2

gonzaedu61
gonzaedu61

Reputation: 91

I found a way using the internal method peek() of class StatementResult. If you call this method it will raise an error in case there no records in the result object. I wrapped this code within a function which can be used passing the Result object to it.

def isResultRecord(results):
    try:
        results.peek()
    except ResultError:
        return False
    else:
        return True

Upvotes: 2

Related Questions