使用 Python 连接到 Neptune 数据库实例 - Amazon Neptune
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 Python 连接到 Neptune 数据库实例

如果可以的话,请始终使用你的引擎版本支持的最新版本的 Apac TinkerPop he Python Gremlin 客户端 gremlinpython。更新的版本包含大量错误修复,可以提升客户端的稳定性、性能和可用性。要使用的gremlinpython版本通常与 Java Gremlin 客户端表中描述的 TinkerPop版本保持一致。

注意

只要你在编写的 gremlinpython Gremlin 查询中只使用 TinkerPop 3.4.x 功能,3.5.x 版本就与 3.4.x 版本兼容。

以下部分将指导您完成 Python 示例的运行,该示例连接到 Amazon Neptune 数据库实例并执行 Gremlin 遍历。

必须从与您的 Neptune 数据库实例位于同一虚拟私有云 (VPC) 中的 Amazon EC2 实例中按照这些说明操作。

开始之前,请执行以下操作:

  • Python.org 网站下载并安装 Python 3.6 或更高版本。

  • 验证您是否安装了 pip。如果您没有 pip 或不确定是否有,请参阅 pip 文档中的是否需要安装 pip?

  • 如果您的 Python 安装尚未具有该命令,请按如下方式下载 futurespip install futures

使用 Python 连接到 Neptune
  1. 输入以下命令以安装 gremlinpython 程序包:

    pip install --user gremlinpython
  2. 创建名为 gremlinexample.py 的文件,然后在文本编辑器中打开它。

  3. 将以下内容复制到 gremlinexample.py 文件中。将 your-neptune-endpoint 替换为 Neptune 数据库实例的地址。

    有关查找 Neptune 数据库实例的地址的信息,请参阅连接到 Amazon Neptune 端点部分。

    from __future__ import print_function # Python 2/3 compatibility from gremlin_python import statics from gremlin_python.structure.graph import Graph from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection graph = Graph() remoteConn = DriverRemoteConnection('wss://your-neptune-endpoint:8182/gremlin','g') g = graph.traversal().withRemote(remoteConn) print(g.V().limit(2).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 遍历。