2012-09-25 86 views
2

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

看起來好像會起作用,儘管在名稱字段上使用索引可能會更快,所以您可以在節點上啓動而無需掃描整個圖形。你能否提供更多的代碼 - 特別是你傳遞參數圖的部分? –

+0

你可能是對的,因爲當我拿出where子句時,我得到的結果包括我正在尋找的關係,並且在我無法指責的where子句中出現錯誤。感謝索引建議,我想在我的基本功能工作後添加它。 – user977505

回答

1

類型參數被列爲{type},但定義爲參數映射"rtype"。它能幫你解決嗎?您可以嘗試不帶參數的查詢(只需將它們硬編碼),以查看它是否有效。

+0

好的。我已經嘗試了很多關於查詢的更改,並最終使用type而不是rtype。還有一些其他的事情我在做錯誤的輸入。你以前的和當前的提示無疑幫助我思考並解決了我的問題。再次感謝您的幫助。 – user977505

相關問題