【问题标题】:Neo4j: REST API Cypher Query to find relationship between two nodesNeo4j:REST API Cypher 查询以查找两个节点之间的关系
【发布时间】:2012-09-16 12:54:40
【问题描述】:

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

【问题讨论】:

  • 看起来它会起作用,尽管在名称字段上使用索引可能会更快,因此您可以从节点开始而不必扫描整个图。能否提供更多代码——尤其是传递参数映射的部分?
  • 你可能是对的,因为当我取出 where 子句时,我得到的结果包括我正在寻找的关系,并且 where 子句有问题,我无法把我的手指放在上面。也感谢您的索引建议,我想在我的基本功能工作后添加它。

标签: neo4j graph-databases cypher spring-data-neo4j


【解决方案1】:

也许你可以用 RELATE 命令让它变得不同: http://docs.neo4j.org/chunked/1.8.M03/query-relate.html

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 好收获。我围绕查询尝试了很多更改,最终使用 type 而不是 rtype。我在输入方面做错了其他几件事。您以前和当前的提示确实帮助我思考和解决了我的问题。再次感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多