Gremlin 查询查找两个标签之间的最短和最长路径连接

问题描述 投票:0回答:1

我正在寻找连接两个标签的最短和最长路径。我正在尝试以下 Gremlin Python 代码。

from gremlin_python.driver import client
from gremlin_python.process.traversal import __, T, P, Vertex

# Initialize the Gremlin client
client = client.Client('ws://localhost:8182/gremlin', 'g')

try:
    # Query to find paths from "City" to "Person"
    paths = client.submitAsync(
        g.V()
        .hasLabel("City")
        .repeat(__.bothE().otherV().simplePath())
        .until(__.hasLabel("Person"))
        .limit(100)
        .path()
        .toList()
    ).result()

    for path in paths:
        relation_types = [v.label for v in path.objects if isinstance(v, Vertex)]
        print(relation_types)
        data.append(len(relation_types))

    if data: 
        print(f"Shortest Path length = {min(data) - 1}")
        print(f"Longest Path length = {max(data) - 1}")
    else: 
        print(f"Shortest Path length = 0")
        print(f"Longest Path length = 0")


except Exception as e:
    print(f"An error occurred: {e}")

finally:
    client.close()

我们目前观察到,当限制为 100 时,最短路径长度为 2,最长路径长度为 3。当我们将限制增加到 1000 时,最长路径长度将增加到 5。但是,如果我们完全删除限制,它会导致连接崩溃并导致“评估超时”错误。

TinkerPop 中是否有一个我可能会忽略的查找最短和最长路径的特定函数?或者,是否有一种算法可以用来实现这一目标?

gremlin tinkerpop gremlinpython
1个回答
0
投票

查找最短和最长路径需要对图进行全面搜索。根据图表的大小,这可能会花费大量时间,请参阅here了解连接组件相关问题的可扩展性示例。 如果您的 Tinkerpop 服务器支持,您还可以尝试 OLAP

shortest_path
步骤,它的扩展性比代码中的 OLTP 遍历稍好。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.