Amazon Neptune
User Guide (API Version 2017-11-29)

Using Python to Connect to a Neptune DB Instance

The following section walks you through the running of a Python sample that connects to an Amazon Neptune DB instance and performs a Gremlin traversal.

You must follow these instructions from an Amazon EC2 instance in the same virtual private cloud (VPC) as your Neptune DB instance.

Before you begin, do the following:

To connect to Neptune using Python

  1. Enter the following to install the gremlinpython package:

    pip install gremlinpython ‑‑user
  2. Create a file named gremlinexample.py, and then open it in a text editor.

  3. Copy the following into the gremlinexample.py file. Replace your-neptune-endpoint with the address of your Neptune DB instance.

    For information about finding the address of your Neptune DB instance, see the Amazon Neptune Endpoints section.

    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() g = graph.traversal().withRemote(DriverRemoteConnection('wss://your-neptune-endpoint:8182/gremlin','g')) print(g.V().limit(2).toList())
  4. Enter the following command to run the sample:

    python gremlinexample.py

    The Gremlin query at the end of this example returns the vertices (g.V().limit(2)) in a list. This list is then printed with the standard Python print function.

    Note

    The final part of the Gremlin query, toList(), is required to submit the traversal to the server for evaluation. If you don't include that method or another equivalent method, the query is not submitted to the Neptune DB instance.

    The following methods submit the query to the Neptune DB instance:

    • toList()

    • toSet()

    • next()

    • nextTraverser()

    • iterate()

    The preceding example returns the first two vertices in the graph by using the g.V().limit(2).toList() traversal. To query for something else, replace it with another Gremlin traversal with one of the appropriate ending methods.

    For more information about Amazon Neptune, see Next Steps.