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

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

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

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

注意

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

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

您必须在 Amazon EC2 实例和 Neptune 数据库实例相同的 Virtual Private Cloud (VPC) 中按照这些说明操作。

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

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

    pip install gremlinpython ‑‑user
  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 遍历。