【发布时间】: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