user1919
user1919

Reputation: 3938

How to get the response of a cypher query in neo4j using python Rest api

I am using Python to access neo4j and create nodes. Before I create the node I want to check if it exists. I run this query:

          "query" : "match (PPnode:Node) return PPnode"

And using the method of requests library:

           r.text

I get a string, with the response of my POST request. My question is if there is a more "elegant" way to check if there are existing nodes with a specific name using python and rest api.

This is my code:

   import requests
   import json
   import csv

  headers = {'content-type': 'application/json'}
  url = "http://localhost:7474/db/data/cypher"


  fparts = open('FOC.csv')
  csv_pseudo = csv.reader(fparts)


  for row in csv_pseudo:

   # query to check if node exists
   checkNode = {"query" : "match (PPnode:Node) return PPnode"}
   mkr =requests.post(url, data=json.dumps(checkNode), headers=headers)

Thanks Dimitris

Upvotes: 4

Views: 2986

Answers (1)

FrobberOfBits
FrobberOfBits

Reputation: 18002

I think you might be working harder here than you need to. There's a library called py2neo which will do what you want to do much more simply. If you were using it, you could get actual objects back instead of raw JSON, which might be easier to deal with:

From the documentation on how to run Cypher queries:

from py2neo import Graph
graph = Graph("http://nifty-site:1138/db/data/")
results = graph.cypher.execute("match (PPnode:Node) return PPnode")

for r in results:
    # get the node you return in your query
    ppNode = r[0]
    # get the properties of your node
    props = ppNode.get_properties()
    # Do nifty stuff with properties, not JSON.

Upvotes: 5

Related Questions