简体   繁体   中英

Neo4j: REST API Cypher Query to find relationship between two nodes

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;
}

The type parameter is listed as {type} , but defined as "rtype" in the parameter map. Does that fix it for you? You might try the query without the parameters (just hard code them in), to see if it works.

maybe you could make it different with the RELATE command: http://docs.neo4j.org/chunked/1.8.M03/query-relate.html

this way there is no need to check whether or not the relation already exists. simply, if it doesn't then it creates one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM