[12屆 鐵人賽] [Day26] 打打看 Neo4j Http Api 吧 === ###### tags: `iT鐵人賽` `Neo4j` ## 前情提要 26 篇了,距離結束的 30 篇,剩 5 篇 扣掉最後一篇尾聲打算講一些心路歷程什麼的 還有 4 篇未定主題的文章  現在這篇的主題還是剛剛翻書才臨時起意的 所以說等等會寫出什麼我也不知道 ## Neo4j Http Api Neo4j Server 有包含 Http Api 功能,可以做為下 Cypher 指令的一種方法 在最一開始,就先來講講 Neo4j API 所需要的一些 `Header` * `Accept` = "`application/json;charset=UTF-8`" * 訊息格式,很基本應該不用多講 * `X-Stream` = `true` * 官方表示,為了提升效能建議加上這行 * `Authorization` = "`Basic bmVvNGo6MTIzNDU2`" * 後面那串是 `UserName:Password` 的 Base64 編碼 * 或是如果你用的是 Postman,直接用 Basic Auth 就行了  ## 確認連線 這篇的 Demo 將會全部使用 Postman 來進行 首先確認你的 Server 可以連線是最基本的 GET: ``` http://localhost:7474/ ```  如你發現伺服器沒有回應,請去把 **neo4j.conf** 裡的這行設為 `true` ```javascript dbms.connector.http.enabled=true ``` ## 來下 Cypher 指令吧 剛剛確認連線中,`Response` 的回應中有這一行 ```javascript "transaction": "http://localhost:7474/db/{databaseName}/tx" ``` 這個我們等等會用到 裡面寫的 `databaseName` 顧名思義就是資料庫的名稱,通常預設是 **Neo4j** ### 開始傳送 POST: ``` http://localhost:7474/db/neo4j/tx ```  你的 Body ```javascript { "statements":[{ "statement":"CREATE (n:Test1) RETURN n" //你要執行的指令 }] } ``` Service Response ```javascript { "results": [... ], "errors": [], "commit": "http://localhost:7474/db/neo4j/tx/1/commit", "transaction": { "expires": "Sat, 10 Oct 2020 13:28:04 GMT" } } ``` 這裡要注意這一行 ```javascript "commit": "http://localhost:7474/db/neo4j/tx/1/commit" ``` API 的執行概念跟之前在[第 20 篇](https://ithelp.ithome.com.tw/articles/10249120)那邊提過的 `BeginTransactionAsync()` 一樣 你必須先 `Commit` 這次的請求才會被寫入資料庫 而這邊 `tx/1/commit` 中間的這個 1 則是指你現在在使用的 Channel Neo4j 會依照這個 Channel 去儲存所有進來的資料 那要怎麼再對同一個 Channel 下指令呢 只要在剛剛下指令的網址後加上 Channel 的 Id 就行了 POST: ``` http://localhost:7474/db/neo4j/tx/1 ``` 這裡要注意一件事情,如果同一個 Channel 太久沒有使用 那 Neo4j 會自動釋放該 Channel 的所有資料 > 預設是 60 秒 如過你不想讓 Channel 消失,你可以一樣打 上面的 URL `statement` 欄位代 `""`,就可以維持住該 Channel ### 傳送失敗 如果你讓該 Channel 釋放後再使用該 Channel 你會收到這樣的 `404 response` ```javascript { "results": [], "errors": [ { "code": "Neo.ClientError.Transaction.TransactionNotFound", "message": "Unrecognized transaction id. Transaction may have timed out and been rolled back." } ] } ``` ### 資料 Commit POST: ``` http://localhost:7474/db/neo4j/tx/1/commit ```  這樣一來,所有資料就會寫入資料庫了 --- 原本想說應該可以快速完成,阿不就 API 接果看文件跟測試花了一堆時間 很好又完成了一篇,倒數 3 篇尾聲 下篇 **Neo4j 綜合應用 & 來讀個 CSV 吧** 究竟鐵人賽能不能完賽呢,讓我們繼續看下去 --- ## 參考資料 [Neo4j HTTP API](https://neo4j.com/docs/http-api/current/) ## 紀錄 撰寫日期:2020/10/10 耗時: 2 小左右 WTF
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up