View a markdown version of this page

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

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

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

重要

選擇正確的 Apache TinkerPop Gremlin 驅動程式版本對於與您的 Neptune 引擎版本相容至關重要。使用不相容的版本可能會導致連線失敗或非預期的行為。如需詳細的版本相容性資訊,請參閱 使用 Gremlin 存取 Neptune 圖形

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

您必須從與您的 Neptune 資料庫執行個體位於同一虛擬私有雲端 (VPC) 的 Amazon EC2 執行個體依照以下指示進行。

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

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

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

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

  3. 將以下內容複製到 gremlinexample.js 檔案。將 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 的詳細資訊。

IAM 身分驗證

Neptune 支援 IAM 身分驗證,以控制對資料庫叢集的存取。如果您已啟用 IAM 身分驗證,則需要使用 Signature 第 4 版簽署來驗證您的請求。如需從 JavaScript 用戶端連線的詳細說明和程式碼範例,請參閱 使用 IAM 身分驗證搭配 Gremlin JavaScript 連線至 Amazon Neptune 資料庫