2

我是 Neo4j 的新手,正在使用 REST API 创建节点和关系。我有两个节点 NA 和 NB,它们通过关系 RC 连接。'NA - RC - NB'。在创建节点和关系之前,我会检查节点和它们之间的关系是否不存在。我想出了如何检查一个节点是否存在并且正在努力如何检查两个节点之间的关系是否存在。我想出了这个 Cypher 查询。

"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)"

节点具有属性“名称”。执行此查询时,我得到空的“数据:[]”。

有什么建议么?我尝试查看 Neo4j 文档和一些教程,但不太明白这一点。

TIA

这是java代码:

/** 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;
}
4

2 回答 2

1

类型参数被列为{type},但"rtype"在参数映射中定义。这能为你解决吗?您可以尝试不带参数的查询(只需将它们硬编码),看看它是否有效。

于 2012-09-25T04:15:52.283 回答
0

也许您可以使用 RELATE 命令使其有所不同:http: //docs.neo4j.org/chunked/1.8.M03/query-relate.html

这样就不需要检查关系是否已经存在。简单地说,如果没有,那么它会创建一个。

于 2012-09-27T08:29:09.807 回答