Gremlin 是图数据领域最流行的查询语言之一,就好比关系型数据库里的 SQL 一样。接下来,我们将通过一些例子来说明 Gremlin 是如何执行图查询的。
# Install graphscope package if you are NOT in the Playground
!pip3 install graphscope
# Import the graphscope module and load the modern graph
import graphscope
from graphscope.dataset import load_modern_graph
graphscope.set_option(show_log=False) # enable logging
modern_graph = load_modern_graph()
# Greate GIE engine with Gremlin
interactive = graphscope.gremlin(modern_graph)
两点之间的遍历是图数据领域十分常见的查询场景。例如,为了搞清楚v1和v2/v3之间的关系,我们可以这样写一条 gremlin 语句:
q1 = interactive.execute(
'g.V().has("id", 1).as("u").out().has("id", eq(2).or(eq(3))).as("v").select("u", "v").by("id")'
).all().result()
for p in q1:
print(p)
接下来展示一条在社交网络场景中常用的查询,例如如何找到两个不同用户之间的共同特点,用户1昵称为"marko",另一个为"peter"。
q2 = interactive.execute(
'g.V().has("name", "marko").out().where(__.in().has("name", "peter")).valueMap()'
).all().result()
for p in q2:
print(p)
度的中心性是衡量每个顶点邻接边数量的指标,在处理大数据时有重要意义,这里有一些示例:
q3 = interactive.execute("g.V().group().by().by(bothE().count())").all()
for p in q3:
print(p)
q4 = interactive.execute("g.V().group().by().by(inE().count())").all()
for p in q4:
print(p)
环的检测是图查询在商业领域中的另一重要应用,环通常被认为是欺诈行为的发生。这里有一个示例展示 gremlin 如何被用于发现图上的环。
q5 = interactive.execute(
'g.V().as("u").repeat(out().simplePath()).times(2).where(out().where(eq("u"))).count()'
)
print(q5.one())