View a markdown version of this page

使用 Python 連線至 Neptune 資料庫執行個體 - Amazon Neptune

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

使用 Python 連線至 Neptune 資料庫執行個體

重要

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

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

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

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

  • Python.org 網站下載並安裝 Python 3.6 或更新版本。

  • 確認已安裝 pip。如果您沒有 pip 或不確定,請參閱 pip 文件中的我是否需要安裝 pip?

  • 如果 Python 安裝未提供 pip,請如下下載 futurespip install futures

使用 Python 連線至 Neptune
  1. 輸入以下內容以安裝 gremlinpython 套件:

    pip install --user gremlinpython
  2. 建立名為 gremlinexample.py 的檔案,並在文字編輯器中開啟。

  3. 將以下內容複製到 gremlinexample.py 檔案。將 your-neptune-endpoint 取代為 Neptune 資料庫叢集的地址,將 your-neptune-port 取代為 Neptune 資料庫叢集的連接埠 (預設值:8182)。

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

    以下範例示範如何與 Gremlin Python 連線。

    import boto3 import os from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.process.anonymous_traversal import traversal database_url = "wss://your-neptune-endpoint:your-neptune-port/gremlin" remoteConn = DriverRemoteConnection(database_url, "g") g = traversal().withRemote(remoteConn) print(g.inject(1).toList()) remoteConn.close()
  4. 輸入下列命令以執行範例:

    python gremlinexample.py

    本範例結尾的 Gremlin 查詢將以清單傳回頂點 (g.V().limit(2))。接著此清單將以標準 Python print 函數列印。

    注意

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

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

    • toList()

    • toSet()

    • next()

    • nextTraverser()

    • iterate()

    上述範例使用 g.V().limit(2).toList() 周遊傳回圖形中的前兩個頂點。若要查詢其他內容,將其換成其他使用其中一個適當之結束方法的 Gremlin 周遊。

IAM 身分驗證

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