[英]How do I write a sub-query?
I want to retrieve all vertexes and for each one I want to count the number of 'Like' edges pointing at it. 我想检索所有顶点,并想为每个顶点计算指向它的“像”边的数量。
How do I write this kind of query in Gremlin? 如何在Gremlin中编写此类查询?
In SQL it could be something like.... 在SQL中,可能类似于...。
SELECT *, (SELECT Count(*) FROM tbl_like l WHERE l.id = b.id) AS LikeCount
FROM tbl_blah b
Eg use sideEffect
to put the counts in a map ( m
) 例如,使用
sideEffect
将计数放入地图( m
)
m=[:];g.V.sideEffect{m[it]=it.inE.has('label','like').count()}
An alternative which omits vertices with 0 likes: 另一种选择是省略顶点为0的顶点:
m=[:];g.V.inE('like').groupCount(m){it.inV.next()}
EDIT 编辑
Finally the smart solution: 最后是智能解决方案:
m=[:];g.V.groupCount(m){it}{it.a.inE('like').count()}
The first closure of groupCount
determines the key to update in the map and the second closure the value to the key. groupCount
的第一个闭包确定要在映射中更新的键,第二个闭包确定键的值。 Seems like it.a
in the second closure gives the current input value to groupCount
(here a vertex) and it.b
the previous value in the map for the input object. 看起来像
it.a
。第二个闭包中的a将当前输入值提供给groupCount
(这里是一个顶点),而it.b
将映射中输入对象的先前输入值提供给map。 Haven't really found a documentation that explains this, maybe one of the TinkerPop guys can elaborate on the exact usage of the groupCount
closures. 尚未真正找到解释此问题的文档,也许TinkerPop的其中一位可以详细说明
groupCount
闭包的确切用法。
I would consider: 我会考虑:
m = g.E.has('label','like').groupBy{it.inV.next()}{1}{it.sum()}.cap.next()
Iterate all edges and filter by label, group on the inV
of each "like" edge and add a 1
to that Map
of results. 迭代所有边并按标签过滤,在每个“喜欢”边的
inV
上分组, inV
结果Map
添加1
。 That much takes you to the second to last closure of the groupBy
. 那将带您到
groupBy
倒数第二个结束。 At that point you will have a Map
like: 届时您将拥有一个类似于以下内容的
Map
:
[v1:[1,1,1]
v2:[1,1]]
which basically is a vertex with a 1 representing each "like" edge. 它基本上是一个顶点,每个顶点代表1个“相似”边缘。 Going back to the Gremlin above, the final closure to
groupBy
is a reduce operation that occurs on the values in the Map
. 回到上面的Gremlin,对
groupBy
的最后关闭是对Map
的值进行的归约运算。 In this case, we use the Groovy sum
function (though I suppose size
would work here too - but sum
seems easier for readability) to add up the number of edges. 在这种情况下,我们使用Groovy
sum
函数(尽管我想size
也可以在这里工作-但是sum
看起来更容易阅读)来增加边的数量。 Finally, we use cap
to extract the Map
side-effect from the pipeline and next
it out into a var. 最后,我们使用
cap
从管道中提取Map
副作用, next
其提取到var中。
I suppose the downside here is that it doesn't yield a result for vertices with no "like" edges. 我想这里的缺点是,对于没有“相似”边缘的顶点,它不会产生结果。 If you need that, then the solution provided by @Faber is a better way to go.
如果需要,@ Faber提供的解决方案是更好的方法。 You might even pick and choose a bit from both solutions to ultimately get at what you are looking for.
您甚至可以从两种解决方案中进行选择,最终找到您想要的。
不需要副作用...
g.V().transform{[it, it.in('likes').count()]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.