跳至内容

从Python连接

Gremlin遍历可以通过Gremlin-Python构建,就像在 Gremlin-Java或Gremlin-Groovy中一样。有关Gremlin的介绍和进一步资源的指引,请参考Gremlin查询语言

重要

一些Gremlin步骤和谓词名称在Python中是保留字。 这些名称在Gremlin-Python中会简单地加上_后缀,例如, in()变为in_()not()变为not_(),依此类推。其他 受此影响的名称有:allandasfromglobalislistorset

JanusGraph与Gremlin-Python入门指南

开始使用 Gremlin-Python:

  1. 安装 Gremlin-Python:
    pip install gremlinpython==3.7.3
    
  2. 创建一个文本文件 gremlinexample.py 并添加以下导入语句:

    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. 创建一个 GraphTraversalSource,这是所有Gremlin遍历的基础:

    from gremlin_python.process.anonymous_traversal import traversal
    
    connection = DriverRemoteConnection('ws://localhost:8182/gremlin', 'g')
    # 连接应在关闭时通过connection.close()关闭打开的连接
    g = traversal().withRemote(connection)
    # 在整个应用程序中复用'g'
    

  4. 执行一个简单的遍历:

    hercules_age = g.V().has('name', 'hercules').values('age').next()
    print(f'Hercules is {hercules_age} years old.')
    
    next() 是一个终端步骤,它将遍历提交到Gremlin服务器并返回单个结果。

JanusGraph 特定类型和谓词

JanusGraph包含一些不属于Apache TinkerPop的类型和predicates, 因此也不被Gremlin-Python支持。