Chapter 19. Connecting from Python

JanusGraph can be queried from a Python application with Apache TinkerPop’s Gremlin-Python.

Gremlin traversals can be constructed with Gremlin-Python just like in Gremlin-Java or Gremiln-Groovy. Refer to Chapter 6, Gremlin Query Language for an introduction to Gremlin and pointers to further resources.

[Important]Important

Some Gremlin step and predicate names are reserved words in Python. Those names are simply postfixed with _ in Gremlin-Python, e.g., in() becomes in_(), not() becomes not_(), and so on. The other names affected by this are: all, and, as, from, global, is, list, or, and set.

19.1. Getting Started with JanusGraph and Gremlin-Python

To get started with Gremlin-Python:

  1. Install Gremlin-Python:

    pip install gremlinpython==3.3.3
  2. Create a text file gremlinexample.py and add the following imports to it:

    from gremlin_python import statics
    from gremlin_python.structure.graph import Graph
    from gremlin_python.process.graph_traversal import __
    from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
  3. Create a GraphTraversalSource which is the basis for all Gremlin traversals:

    graph = Graph()
    connection = DriverRemoteConnection('ws://localhost:8182/gremlin', 'g')
    // The connection should be closed on shut down to close open connections with connection.close()
    g = graph.traversal().withRemote(connection)
    // Reuse 'g' across the application
  4. Execute a simple traversal:

    herculesAge = g.V().has('name', 'hercules').values('age').next()
    print('Hercules is {} years old.'.format(herculesAge))

    next() is a terminal step that submits the traversal to the Gremlin Server and returns a single result. Other terminal steps can be found in TinkerPop’s reference documentation.

19.2. JanusGraph Specific Types and Predicates

JanusGraph contains some types and predicates that are not part of Apache TinkerPop and are therefore also not supported by Gremlin-Python.