使用 Node.js 連線至 Neptune 資料庫執行個體 - Amazon Neptune

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 Node.js 連線至 Neptune 資料庫執行個體

如果可以的話,請始終使用引擎版本支持的最新版本的 Apache G TinkerPop JavaScript emlin 客戶端 gremlin。較新的版本包含許多錯誤修正,其可以改善用戶端的穩定性、效能和可用性。gremlin要使用的版 TinkerPop 本通常會與 Java Gemlin 客戶端的表格中描述的版本保持一致。

下節引導您逐步執行 Node.js 範例,其會連線至 Amazon Neptune 資料庫執行個體,並執行 Gremlin 周遊。

您必須遵循與 Neptune 資料庫EC2執行個體位於相同虛擬私有雲端 (VPC) 中 Amazon 執行個體的這些指示。

開始之前,請執行以下動作:

  • 確認已安裝 Node.js 8.11 或更高版本。如果沒有,請從 Nodejs.org 網站下載並安裝 Node.js。

使用 Node.js 連線至 Neptune
  1. 輸入以下內容以安裝 gremlin-javascript 套件:

    npm install gremlin
  2. 建立名為 gremlinexample.js 的檔案,並在文字編輯器中開啟。

  3. 將以下內容複製到 gremlinexample.js 檔案。Replace (取代) your-neptune-endpoint 使用您的 Neptune 資料庫執行個體的位址。

    如需尋找 Neptune 資料庫執行個體地址的相關資訊,請參閱 連線至 Amazon Neptune 端點 一節。

    const gremlin = require('gremlin'); const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection; const Graph = gremlin.structure.Graph; dc = new DriverRemoteConnection('wss://your-neptune-endpoint:8182/gremlin',{}); const graph = new Graph(); const g = graph.traversal().withRemote(dc); g.V().limit(1).count().next(). then(data => { console.log(data); dc.close(); }).catch(error => { console.log('ERROR', error); dc.close(); });
  4. 輸入下列命令以執行範例:

    node gremlinexample.js

前面的範例回傳使用 g.V().limit(1).count().next()周遊回傳圖表中的單一頂點計數。若要查詢其他內容,將其換成其他使用其中一個適當之結束方法的 Gremlin 周遊。

注意

Gremlin 查詢最後的部分 next() 用來提交周遊至伺服器,以供進行評估。如果您未包含該方法或其他同等方法,該查詢不會提交到 Neptune 資料庫執行個體。

以下方法會查詢提交至 Neptune 資料庫執行個體:

  • toList()

  • toSet()

  • next()

  • nextTraverser()

  • iterate()

如果您需要序列化並傳回查詢結果,請使用 next(),或者如果不需要,則使用 iterate()

重要

這是一個獨立的 Node.js 範例。如果您打算在 AWS Lambda 函數中執行類似這樣的程式碼,請參閱以Lambda 函數範例取得有關在 Neptune Lambda 函數中 JavaScript 有效使用的詳細資訊。