floatingpurr
floatingpurr

Reputation: 8559

py2neo (1.6) how to get an existing node by node property without CypherQuery

I'm using py2neo (version 1.6). I want to get an existing node by its property from the graph and then use it to create a relationship.

My solution:

graph = neo4j.GraphDatabaseService("http://...")

query = neo4j.CypherQuery(graph,"MATCH (n:NodeType) where n.property = 'property' return n")
r = query.execute()
if len(r.data)==0:
    raise Exception("node does not exist")                
node = r.data[0]['n']

newNode = batch.create(node(name="APropertyOfNewNode"))
batch.add_labels(newNode, "LableOfNewNode")
relation  = rel(node, "relationshipName", newNode)
batch.create(relation)

batch.submit()
batch.clear()

Is there an high level way to get an existing node by its property without using CypherQuery and writing plain cypher?

Upvotes: 1

Views: 953

Answers (1)

Nicole White
Nicole White

Reputation: 7790

You can use GraphDatabaseService.find:

from py2neo import neo4j
graph = neo4j.GraphDatabaseService('http://localhost:7474/db/data/')

movies = graph.find('Movie', 'title', 'The Matrix')

But graph.find returns a generator object.

movies
# <generator object find at 0x10b64acd0>

So you can only iterate through it once.

for movie in movies:
    print type(movie)
    print movie['tagline']

# <class 'py2neo.neo4j.Node'>
# Welcome to the Real World

Upvotes: 3

Related Questions