我是Neo4j的新手,正在使用REST API創建節點和關係。我有兩個節點NA和NB,並且它們與關係RC相連。 'NA - RC - NB'。在創建節點和關係之前,我檢查節點及其之間的關係是否不存在。我弄清楚如何檢查一個節點是否存在,以及如何檢查兩個節點之間是否存在關係。我想到了這個Cypher查詢。Neo4j:REST API 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)"
節點有一個屬性「名稱」。當我執行這個查詢時,我得到空'data:[]'。
有什麼建議嗎?我試圖研究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子句中出現錯誤。感謝索引建議,我想在我的基本功能工作後添加它。 – user977505