本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 Node.js 連線至 Neptune 資料庫執行個體
如果可以的話,請一律使用您的引擎版本所支援的最新版 Apache TinkerPop JavaScript Gremlin 用戶端 (gremlingremlin
版本通常會與 Java Grimlin 用戶端表格中所述的 TinkerPop 版本保持一致。
下節引導您逐步執行 Node.js 範例,其會連線至 Amazon Neptune 資料庫執行個體,並執行 Gremlin 周遊。
您必須從與您的 Neptune 資料庫執行個體位於同一虛擬私有雲端 (VPC) 的 Amazon EC2 執行個體依照以下指示進行。
開始之前,請執行以下動作:
確認已安裝 Node.js 8.11 或更高版本。如果沒有,請從 Nodejs.org 網站
下載並安裝 Node.js。
使用 Node.js 連線至 Neptune
-
輸入以下內容以安裝
gremlin-javascript
套件:npm install gremlin
-
建立名為
gremlinexample.js
的檔案,並在文字編輯器中開啟。 -
將以下內容複製到
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(); }); -
輸入下列命令以執行範例:
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 的詳細資訊。