How py2neo handle an "empty" MATCH

cypher

(Sinuhe David) #1

Hi Community

I'm developing a CLI Terminal app in python 3.6 with:
macOS 10.4
neo4j-community-3.4.4
neo4j-driver==1.6.1
py2neo==4.1.0

I need an empty list or a False response when I do

query="MATCH (n:Node) WHERE n.name = '"+value+"' RETURN n"
return graph.run(query)

But I get Instead any time a different cursor (even with empty value):

<py2neo.database.Cursor object at 0x109f......>

I have in the other hand:

e_list=my_object.find(value)
if(e_list):
	print('Find it')
else:
	print('DONT FIND IT')

So it always get Find it and breaks Python!
I would like to know How to handle an "empty" MATCH RETURN

Thks


(Sinuhe David) #2

ok people after reading this https://py2neo.org/v4/database.html#py2neo.database.Cursor.data
I've found that

if cursor.forward():
    print('Find it')
else:
    print("Didn't find it")

did the trick, never the less with

print(cursor.current["name"])

it breaks python again. Finally to get the values in the cursor I have to make a double graph call, 1 to know if it exist and other to get the values

cursor=my_object.find(value)
if cursor.forward():
    fi_list=my_object.find(value)
    for record in cursor:
        print("Name: "+str(record[0]['name']))
else:
    print ("Didn't find it")

I think it could be optimized. Any help will be appreciated.


(Nigel Small) #3

If you're expecting zero or one record (with one field) then you can use Graph.evaluate:

>>> g.evaluate("UNWIND [] AS x RETURN x")
>>> g.evaluate("UNWIND [1] AS x RETURN x")
1

If you might return multiple records then you probably want to use Cursor.data:

>>> g.run("UNWIND [] AS x RETURN x").data()
[]
>>> g.run("UNWIND [1] AS x RETURN x").data()
[{'x': 1}]
>>> g.run("UNWIND [1, 2] AS x RETURN x").data()
[{'x': 1}, {'x': 2}]

You can then obviously use this conditionally, since empty lists are coerced to False:

>>> print("something" if g.run("UNWIND [] AS x RETURN x").data() else "nothing")
nothing
>>> print("something" if g.run("UNWIND [1] AS x RETURN x").data() else "nothing")
something

(Sinuhe David) #4

Thank you @technige !!
UNWIND solve it like this:

query="MATCH (n:Node) WHERE n.name = '"+value+"' UNWIND [n] AS list_rows RETURN list_rows"
if graph.run(query).data():
    print("Find "+query.current[0]['name']+ " in DB")
else:
    print("Nothing")

Even cursor.current[0]['name'] is working now!
:sunny:

Reference to UNWIND https://neo4j.com/docs/developer-manual/current/cypher/clauses/unwind/