本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
如果可以的話,請一律使用您的引擎版本所支援的最新版 Apache TinkerPop Python Gremlin 用戶端 (gremlinpythongremlinpython
版本通常會與 Java Grimlin 用戶端表格中所述的 TinkerPop 版本保持一致。
注意
gremlinpython
3.5.x 版與 TinkerPop 3.4.x 版相容,只要您在撰寫的 Gremlin 查詢中僅使用 3.4.x 功能即可。
下節引導您逐步執行 Python 範例,其會連線至 Amazon Neptune 資料庫執行個體,並執行 Gremlin 周遊。
您必須從與您的 Neptune 資料庫執行個體位於同一虛擬私有雲端 (VPC) 的 Amazon EC2 執行個體依照以下指示進行。
開始之前,請執行以下動作:
從 Python.org 網站
下載並安裝 Python 3.6 或更新版本。 確認已安裝 pip。如果您沒有 pip 或不確定,請參閱 pip 文件中的我是否需要安裝 pip?
。 如果 Python 安裝未提供 pip,請如下下載
futures
:pip install futures
使用 Python 連線至 Neptune
-
輸入以下內容以安裝
gremlinpython
套件:pip install --user gremlinpython
-
建立名為
gremlinexample.py
的檔案,並在文字編輯器中開啟。 -
將以下內容複製到
gremlinexample.py
檔案。將your-neptune-endpoint
取代為 Neptune 資料庫叢集的地址,將your-neptune-port
取代為 Neptune 資料庫叢集的連接埠 (預設值:8182)。如需尋找 Neptune 資料庫執行個體地址的相關資訊,請參閱 連線至 Amazon Neptune 端點 一節。
在下列範例中,您可以透過設定名為 的環境變數,在啟用 IAM 的資料庫上啟用 使用
USE_IAM
。這將使用 AWS 標準化的登入資料提供者鏈和boto3
SDK,以適當的 SigV4 登入資料簽署您的請求。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" if "USE_IAM" in os.environ and bool(os.environ["USE_IAM"]): creds = boto3.Session().get_credentials().get_frozen_credentials() request = AWSRequest(method="GET", url=database_url, data=None) SigV4Auth(creds, "neptune-db", boto3.Session().region_name).add_auth(request) remoteConn = DriverRemoteConnection(database_url, "g", headers=request.headers.items()) else: remoteConn = DriverRemoteConnection(database_url, "g") g = traversal().withRemote(remoteConn) print(g.inject(1).toList()) remoteConn.close() -
輸入下列命令以執行範例:
python gremlinexample.py
本範例結尾的 Gremlin 查詢將以清單傳回頂點 (
g.V().limit(2)
)。接著此清單將以標準 Pythonprint
函數列印。注意
Gremlin 查詢最後的部分
toList()
用來提交周遊至伺服器,以供進行評估。如果您未包含該方法或其他同等方法,該查詢不會提交到 Neptune 資料庫執行個體。以下方法會查詢提交至 Neptune 資料庫執行個體:
toList()
toSet()
next()
nextTraverser()
iterate()
上述範例使用
g.V().limit(2).toList()
周遊傳回圖形中的前兩個頂點。若要查詢其他內容,將其換成其他使用其中一個適當之結束方法的 Gremlin 周遊。