I'm new to Neo4j and am using REST API's to create nodes and relationships. I've two nodes NA and NB and they are connected w/ a relationship RC. 'NA - RC - NB'. Before I create the nodes and the relationship, I check to see if the nodes and the relationship between them do not exist. I figure out how to check if a node exists and am struggling w/ how to check if a relationship between the two nodes exist. I came up w/ this Cypher query.
"start x = node(*), n = node(*)
match x-[r]->n
where (x.name? = {from} and type(r) = {rtype} and n.name? = {to})
return ID(r), TYPE(r)"
The nodes have a property 'name'. I'm getting empty 'data: []' when I execute this query.
Any suggestions? I tried looking into the Neo4j documentation and some tutorial but not quite able to figure this out.
TIA
Here is the java code:
/** Check if a relationship exists between two nodes */
public boolean relationshipExists(String from /** node name */
, String to /** node name */
, String type) {
boolean exists = false;
/** check if relationship exists */
String url = "http://localhost:7474/db/data/cypher";
JSONObject jobject = new JSONObject();
try {
Map<String, String> params = new HashMap<String, String>();
params.put("from", from);
params.put("rtype", type);
params.put("to", to);
String query = "start x = node(*), n = node(*) match x-[r]->n where (x.name? = {from} and type(r) = {rtype} and n.name? = {to}) return ID(r), TYPE(r)";
jobject.put("query", query);
jobject.put("params", params);
} catch (JSONException e) {
logger.error("Error", e);
}
String response = sendQuery(url, jobject.toString());
try {
jobject = new JSONObject(response);
JSONArray data = (JSONArray) jobject.get("data");
JSONArray next = null;
for (int index = 0; index < data.length(); index++) {
next = data.getJSONArray(index);
if (!next.isNull(1) && next.getString(1).equalsIgnoreCase(type)) {
exists = (next.getInt(0) > -1) ? true : false;
}
}
} catch (JSONException e) {
logger.error("Error", e);
}
return exists;
}