如何为以下模式编写Gremlin查询?

时间:2015-07-29 04:17:01

标签: graph gremlin tinkerpop tinkerpop-blueprint

我有一些微型Gremlin有向图,其中每个顶点都有两个属性“type”和“text”。 “text”属性的值只是英文文本,而“type”属性可以是从该集合中选择的值:

NP, PP, VP, ADVP, ADJP, SBAR, PRT, INTJ, O

这些图中的所有边都有相同的标签:“next”。

我希望能够选择具有以下节点模式的图形:

1) [text=","] --> type="VP" --> type="ADVP" --> type="NP"
2) type="NP" --> [text="," Upto 3 nodes with any text and type text=","] --> type="VP" --> [text=":" OR "that"]

括号中的pattern元素表示它是可选的。

因此,对于第一个模式,我需要选择具有带文本“,”的节点的图形,可选地后跟一个类型为“VP”的节点,然后是“ADVP”,然后是“NP”。

对于第二种模式,我需要选择节点类型为“NP”的图形,然后是一个可选的节点序列,以带有文本“,”的节点开始,然后是3个带有任何文本和类型的节点,然后是带有文本“,”的节点。然后,此可选序列后跟一个类型为“VP”的节点,最后是一个带有文本“:”或“that”的节点。

两个与第一个模式匹配的示例图表是:

Pattern 1

以下是与第二种模式匹配的示例图: enter image description here

我理解基本的Gremlin遍历,但我不确定如何处理上述模式的可选元素。

有没有办法在Gremlin中为这些模式编写查询?如果没有,您能否建议使用基于非Gremlin的方法来创建此类图表并查询它们?

1 个答案:

答案 0 :(得分:1)

你可以在TinkerPop 3.0中使用Gremlin进行模式匹配。您可以使用Match Step来完成任务。我已经写过Gremlin作为你的第一个要求的例子。也许这会激励你为第二个要求开发遍历。

我生成了一些数据如下:

gremlin> graph = TinkerGraph.open()
==>tinkergraph[vertices:0 edges:0]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> v1=g.addV(id, 1, "type", "o", "text", ",").next()
==>v[1]
gremlin> v2=g.withSideEffect('x',v1).addV(id, 2, "type", "vp", "text", "a").addInE('next','x').inV().next()
==>v[2]
gremlin> v3=g.withSideEffect('x',v2).addV(id, 3, "type", "advp", "text", "b").addInE('next','x').inV().next()
==>v[3]
gremlin> g.withSideEffect('x',v3).addV(id, 4, "type", "np", "text", "c").addInE('next','x').inV().next()
==>v[4]
gremlin> 
gremlin> v5=g.addV(id, 5, "type", "vp", "text", "a").next()
==>v[5]
gremlin> v6=g.withSideEffect('x',v5).addV(id, 6, "type", "advp", "text", "b").addInE('next','x').inV().next()
==>v[6]
gremlin> g.withSideEffect('x',v6).addV(id, 7, "type", "np", "text", "c").addInE('next','x').inV().next()
==>v[7]
gremlin> 
gremlin> v8=g.addV(id, 8, "type", "vp", "text", "a").next()
==>v[8]
gremlin> v9=g.withSideEffect('x',v8).addV(id, 9, "type", "o", "text", ",").addInE('next','x').inV().next()
==>v[9]
gremlin> g.withSideEffect('x',v9).addV(id, 10, "type", "np", "text", "c").addInE('next','x').inV().next()
==>v[10]

然后进行匹配遍历:

gremlin> g.V().has('type','vp').match(__.as('vp').coalesce(__().in().has('text',','),constant("optional")).as('o'),
gremlin>                              __.as('vp').out().has('type','advp').as('advp'),
gremlin>                              __.as('advp').out().has('type','np').as('np')).select('o','vp','advp','np')
==>[o:v[1], vp:v[2], advp:v[3], np:v[4]]
==>[o:optional, vp:v[5], advp:v[6], np:v[7]]
相关问题