在“使用addAll,list和sack”这一节中我们介绍了哪些sack步骤可以操作列表。现在我们会更多了解map步骤,以及小精灵如何利用闭包, 我们可以探索一些额外的使用sack的方式。
In the "Using addAll and lists with a sack" section we introduced ways in which sack steps could
operate on lists. Now that we know a bit more about the map step and how Gremlin can take
advantage of Groovy closures (lambda functions) we can explore some additional ways of working
with sacks.
举个例子,以前我们查看sack步骤和列表我们会用到下面的查询。
When we looked at sack steps and lists earlier we used the query below as one of the examples.

现在我们查看map步骤,可以用另一种方式来编写查询,不必是最佳途径,但是它说明了map的使用,如下所示。

Now that we have looked at map steps, another way we could write the query, not necessarily the
best way, but it does illustrate use of a map, is shown below.

 

出于完整性,这是如果我们运行相同的查询会发生的,没有使用克隆。

Just for completeness, here is what would happen if we ran the same query, without the clone (or
split) being used.

 

我们可以写这个查询的一种不同的方式。在本书中有一些我们还没有解释的东西,它就是在sack步骤内直接使用闭包。

A different way we could write the query, and this is something that we have not yet examined in
this book, is to use a closure directly with the sack step itself.

 

我们可以用一个空表map来初始化一个sack,而不是用一个列表或者一个lambda函数来操作它,如下所示。

We could also initialize the sack with a map "[:]" instead of a list and use a lambda function to
manipulate it as shown below.

 

只是为了说明发生了什么,这是移除了clone步骤的同一个查询。

Just to show what happens, here is the same query with the clone step removed.

 

如果我们想得到一个单独的键值对的列表,就像上面的输出中的最后一行。我们可以这么写查询。方法之一是我们可以用一个map而不使用sack步骤,如下所示。

If all we wanted back was a single list of key value pairs, such as the one in the last line of the
output above, we can write a query to do that. One way we could do it is to use a map and not use a
sack step at all as shown below.

 

然而,在笔者看来,使用一个sack感觉得清晰,像下面这样。注意这个例子中返回的是一个java linkedHashMap数据结果,而前边的一个查询生成的是一个 LinkedHashMap.Entry对象的数组列表ArrayList. 值得注意的是:我们已经得到我们想要的结果,在这个例子中是在sack步骤中增加了一个fold步骤。

However, doing it using a sack feels cleaner in my view, as shown below. Note that in this case what
is returned is a Java LinkedHashMap data structure whereas the previous query generated an
ArrayList of LinkedHashMap.Entry objects. Also, it is worth noting that all we had to do to get the
result that we wanted in this case was to add a fold step between the sack steps.

 

另一种方式您可能会选择这样编审查询,没有使用闭包,但是希望这些例子说明了闭包的一些有趣的用法,它可以和sack步骤一起使用。

There are other ways that you might choose to write queries like these, that avoid the use of
closures altogether, but hopefully these examples show some interesting ways that closures can be
combined with sack steps.
posted on 2022-04-25 11:26  bokeyuannicheng0000  阅读(35)  评论(0)    收藏  举报