Gremlin Python

Updated at:

Lindorm Graph Engine is compatible with the Apache TinkerPop Gremlin protocol, allowing you to submit Gremlin statements from Python applications via the gremlinpython client. Learn how to install and configure gremlinpython, bind parameters, control timeouts, and run an end-to-end example covering schema initialization, vertex/edge writes, graph traversal, and vector search.

Prerequisites

  • Lindorm Graph Engine has been activated, and the client IP has been added to the instance's access whitelist.

  • The graph schema has been initialized. If not, refer to Schema definition.

  • Python 3.8 or later is installed locally.

  • You have obtained the connection URL, Gremlin port, database name of the Lindorm Graph Engine, as well as a sub-account with read and write permissions.

Install the gremlinpython client

Run the following command in a Python 3.8 or later environment to install gremlinpython. Version 3.5.x or later is compatible with Lindorm Graph Engine. To verify the installation, run python -c "import gremlin_python; print(gremlin_python.__version__)".

pip install gremlinpython --user

Establish a WebSocket connection

gremlinpython communicates with Lindorm Graph Engine via WebSocket.

  • Syntax:

    from gremlin_python.driver import client
    
    c = client.Client(
        'ws://{host}:{port}/gremlin/{db}',  # WebSocket URL
        'g',
        pool_size=16,
        username="username",
        password="password"
    )
  • Parameter description:

    Parameter

    Description

    host

    Server hostname (for example: localhost)

    port

    Gremlin server port (for example: 16032)

    db

    Database name. Default is default and can be omitted (that is, /gremlin is equivalent to /gremlin/default).

    pool_size

    Connection pool size.

    username

    Database account

    password

    Password for the database account

Parameter binding and timeout control

Use parameter binding to submit Gremlin statements. Passing query conditions as variables prevents injection and improves the server-side statement cache hit rate.

  • Use the G__ prefix for binding parameter names (such as G__label) to avoid conflicts with Gremlin keywords.

  • Set the scriptEvaluationTimeout parameter in RequestMessage to control the timeout of a single query, in milliseconds.

  • After use, call client.close() to close the connection and release WebSocket resources.

from gremlin_python.driver import client
from gremlin_python.driver.request import RequestMessage

c = client.Client(
    'ws://localhost:16032/gremlin/default', 'g',
    username="admin", password="admin"
)

dsl = "g.V(G___id).hasLabel(G___label)"
bindings = {
    "G___id": "marko",
    "G___label": "person"
}

message = RequestMessage('', 'eval', {
    'gremlin': dsl,
    'bindings': bindings,
    'scriptEvaluationTimeout': 30000  # 30 seconds
})
results = c.submit(message).all().result()
for r in results:
    print(r)

c.close()

Code example

The following example demonstrates how to use gremlinpython to complete the full process of schema initialization, adding vertices and edges, graph traversal query, and vector similarity search. Replace the placeholders in the code (such as SERVER_HOST , GREMLIN_PORT , DB_NAME ) with the actual environment values. The vector search functionality in the example is optional and can be removed if your business does not require it.

  • Syntax example:

    """
    Graph database Python client example
    1. Call /schema/mgmt/apply to initialize the schema. Only needs to be called once per graph.
    2. Insert vertices (including 128-dimensional vectors) and edges.
    3. Query vertices, graph traversal, and vector search.
    """
    
    import random
    import requests
    from gremlin_python.driver import client
    from gremlin_python.driver.request import RequestMessage
    
    DEFAULT_TIMEOUT = 30000  # Default timeout is 30 seconds
    
    
    def submit_with_timeout(c, dsl, bindings, timeout=DEFAULT_TIMEOUT):
        """Wrap a Gremlin request with a timeout"""
        message = RequestMessage('', 'eval', {
            'gremlin': dsl,
            'bindings': bindings,
            'scriptEvaluationTimeout': timeout
        })
        return c.submit(message).all().result()
    
    
    def random_vector(dim=128):
        """Generate a random vector"""
        return [round(random.uniform(-1.0, 1.0), 6) for _ in range(dim)]
    
    
    # ========== 1. Initialize Schema ==========
    
    def apply_schema(host, port, db, username, password):
        """Call /schema/mgmt/apply to initialize the graph schema"""
        schema = {
            "vertexLabels": [
                {
                    "label": "person",
                    "properties": [
                        {"name": "name", "dataType": "STRING"},
                        {"name": "age", "dataType": "INT"},
                        {"name": "city", "dataType": "STRING"},
                        {
                            "name": "embedding",
                            "dataType": "VECTOR_FLOAT",
                            "vectorMeta": {
                                "dimension": 128,
                                "distanceMethod": "EUCLIDEAN",
                                "indexType": "HNSW",
                                "indexParams": {
                                    "M": "24",
                                    "EF_CONSTRUCT": "200"
                                }
                            }
                        }
                    ]
                },
                {
                    "label": "software",
                    "properties": [
                        {"name": "name", "dataType": "STRING"},
                        {"name": "lang", "dataType": "STRING"},
                        {"name": "price", "dataType": "INT"}
                    ]
                }
            ],
            "edgeLabels": [
                {
                    "label": "knows",
                    "properties": [
                        {"name": "date", "dataType": "STRING"},
                        {"name": "weight", "dataType": "DOUBLE"}
                    ]
                },
                {
                    "label": "created",
                    "properties": [
                        {"name": "date", "dataType": "STRING"},
                        {"name": "weight", "dataType": "DOUBLE"}
                    ]
                }
            ],
            "connections": [
                {"edgeLabel": "knows", "outVertex": "person", "inVertex": "person"},
                {"edgeLabel": "created", "outVertex": "person", "inVertex": "software"}
            ]
        }
    
        resp = requests.post(
            f"http://{host}:{port}/schema/mgmt/apply?db={db}",
            json=schema,
            auth=(username, password),
            headers={"Content-Type": "application/json"}
        )
        print(f"Schema initialization - status code: {resp.status_code}")
        print(f"Response: {resp.text}")
        return resp
    
    
    # ========== 2. Insert data ==========
    
    def add_persons(c):
        """Batch add person vertices (including 128-dimensional vectors)"""
        persons = [
            {"id": "marko", "name": "marko", "age": 29, "city": "Beijing"},
            {"id": "vadas", "name": "vadas", "age": 27, "city": "Hongkong"},
            {"id": "josh", "name": "josh", "age": 32, "city": "Beijing"},
            {"id": "peter", "name": "peter", "age": 35, "city": "Shanghai"},
        ]
    
        dsl = ("g.addV(G___label).property(id, G___id)"
               ".property('name', G___name)"
               ".property('age', G___age)"
               ".property('city', G___city)"
               ".property('embedding', G___embedding)")
    
        for p in persons:
            bindings = {
                "G___label": "person",
                "G___id": p["id"],
                "G___name": p["name"],
                "G___age": p["age"],
                "G___city": p["city"],
                "G___embedding": random_vector(128)
            }
            result = submit_with_timeout(c, dsl, bindings)
            print(f"Add vertex: {p['id']} -> {result}")
    
    
    def add_softwares(c):
        """Batch add software vertices"""
        softwares = [
            {"id": "lop", "name": "lop", "lang": "java", "price": 328},
            {"id": "ripple", "name": "ripple", "lang": "java", "price": 199},
        ]
    
        dsl = ("g.addV(G___label).property(id, G___id)"
               ".property('name', G___name)"
               ".property('lang', G___lang)"
               ".property('price', G___price)")
    
        for s in softwares:
            bindings = {
                "G___label": "software",
                "G___id": s["id"],
                "G___name": s["name"],
                "G___lang": s["lang"],
                "G___price": s["price"]
            }
            result = submit_with_timeout(c, dsl, bindings)
            print(f"Add vertex: {s['id']} -> {result}")
    
    
    def add_edges(c):
        """Batch add edges"""
        edges = [
            {"from": "marko", "fromLabel": "person", "to": "vadas", "toLabel": "person", "label": "knows", "date": "20160110", "weight": 0.5},
            {"from": "marko", "fromLabel": "person", "to": "josh", "toLabel": "person", "label": "knows", "date": "20130220", "weight": 1.0},
            {"from": "marko", "fromLabel": "person", "to": "lop", "toLabel": "software", "label": "created", "date": "20171210", "weight": 0.4},
            {"from": "josh", "fromLabel": "person", "to": "lop", "toLabel": "software", "label": "created", "date": "20091111", "weight": 0.4},
            {"from": "josh", "fromLabel": "person", "to": "ripple", "toLabel": "software", "label": "created", "date": "20171210", "weight": 1.0},
            {"from": "peter", "fromLabel": "person", "to": "lop", "toLabel": "software", "label": "created", "date": "20170324", "weight": 0.2},
        ]
    
        dsl = ("g.V(G___fromId).hasLabel(G___fromLabel)"
               ".addE(G___edgeLabel)"
               ".to(__.V(G___toId).hasLabel(G___toLabel))"
               ".property('date', G___date)"
               ".property('weight', G___weight)")
    
        for e in edges:
            bindings = {
                "G___fromId": e["from"],
                "G___fromLabel": e["fromLabel"],
                "G___edgeLabel": e["label"],
                "G___toId": e["to"],
                "G___toLabel": e["toLabel"],
                "G___date": e["date"],
                "G___weight": e["weight"]
            }
            result = submit_with_timeout(c, dsl, bindings)
            print(f"Add edge: {e['from']} -[{e['label']}]-> {e['to']} -> {result}")
    
    
    # ========== 3. Query ==========
    
    def query_vertex(c, vertex_id, label):
        """Query a vertex by ID and label"""
        dsl = "g.V(G___id).hasLabel(G___label).valueMap(true)"
        bindings = {
            "G___id": vertex_id,
            "G___label": label
        }
        results = submit_with_timeout(c, dsl, bindings)
        for r in results:
            print(r)
        return results
    
    
    def query_neighbors(c, vertex_id, label, edge_label):
        """Query neighbors of a vertex (traverse out via the specified edge type)"""
        dsl = "g.V(G___id).hasLabel(G___label).out(G___edgeLabel).valueMap(true)"
        bindings = {
            "G___id": vertex_id,
            "G___label": label,
            "G___edgeLabel": edge_label
        }
        results = submit_with_timeout(c, dsl, bindings)
        for r in results:
            print(r)
        return results
    
    
    def query_vector_search(c, label, prop, top_k=3):
        """Vector search: find the vertices most similar to a random target vector"""
        query_vector = random_vector(128)
    
        dsl = "g.V().hasLabel(G___label).hasVector(G___prop, G___vector, G___topK).valueMap(true)"
        bindings = {
            "G___label": label,
            "G___prop": prop,
            "G___vector": query_vector,
            "G___topK": top_k
        }
        results = submit_with_timeout(c, dsl, bindings)
        for r in results:
            print(r)
        return results
    
    
    # ========== main ==========
    
    def main():
        host = "ld-xx-proxy-graph-vpc.lindorm.aliyuncs.com"
        port = 16032
        db = "default" # No multi-graph requirement, use default
        username = "root"
        password = "xxx"
    
        # 1. Initialize Schema
        print("=" * 50)
        print("1. Initialize Schema")
        print("=" * 50)
        #apply_schema(host, port, db, username, password)
    
        # # 2. Create the Gremlin client (passed externally to all functions)
        c = client.Client(
            f'ws://{host}:{port}/gremlin/{db}', 'g',
            pool_size=16,
            username=username, password=password
        )
    
        # 3. Insert data
        print("\n" + "=" * 50)
        print("2. Insert vertices and edges")
        print("=" * 50)
    
        print("\n--- Add person vertices ---")
        add_persons(c)
    
        print("\n--- Add software vertices ---")
        add_softwares(c)
    
        print("\n--- Add edges ---")
        add_edges(c)
    
        # 4. Query
        print("\n" + "=" * 50)
        print("3. Query")
        print("=" * 50)
    
        print("\n--- Query vertex marko ---")
        query_vertex(c, "marko", "person")
    
        print("\n--- People marko knows ---")
        query_neighbors(c, "marko", "person", "knows")
    
        print("\n--- Software created by marko ---")
        query_neighbors(c, "marko", "person", "created")
    
        print("\n--- Vector search top 3 ---")
        query_vector_search(c, "person", "embedding", top_k=3)
    
        # Close the connection
        c.close()
        print("\nDone!")
    
    
    if __name__ == "__main__":
        main()
    
  • Parameter description:

    The example uses vectorMeta to declare vector property index parameters and hasVector to perform nearest-neighbor search in a Gremlin traversal. The signature is hasVector('property name', query vector, topK). Key fields of vectorMeta:

    Parameter

    Example value

    Description

    Property name

    embedding

    The name of the property field that stores the vector on the vertex.

    Query vector

    [0.1f, 0.2f, ...]

    The target vector used for similarity search.

    topK

    6

    Return the top K most similar vertices.