如何在项目中遍历 'by' 步骤在 gremlin 中所需的次数?

How to traverse in project followed by 'by' step for required number of times in gremlin?

我有一个顶点(比如省份)。我正在使用来自该顶点的 属性 调用代码来遍历中间边。

gremlin> :> g.V().hasLabel('Province').has('code','IN').inE('partOf').outV().hasLabel('Province').has('type','state').project('state','city').by(values('code')).by(coalesce(inE('partOf').outV().hasLabel('Province').has('type','city').project('cityId','cityName'),constant('NONE')))

==>{state=DD, city=NONE}
==>{state=HR, city={cityId=e2d437ca-0150-47fd-bbbe-2a04d697db9a, cityName=Gurugram}}
==>{state=JK, city=NONE}
==>{state=CH, city=NONE}
==>{state=MZ, city=NONE}
==>{state=OR, city=NONE}
==>{state=TR, city=NONE}
==>{state=UP, city={cityId=5b871eed-2bfd-4959-81b1-81151d238ed4, cityName=Lucknow}}
==>{state=ML, city=NONE}
==>{state=AR, city=NONE}
==>{state=AS, city=NONE}
==>{state=GA, city=NONE}
==>{state=JH, city=NONE}
==>{state=PY, city=NONE}
==>{state=RJ, city=NONE}
==>{state=WB, city=NONE}
==>{state=AN, city=NONE}
==>{state=AP, city=NONE}
==>{state=GJ, city=NONE}
==>{state=HP, city=NONE}
==>{state=MN, city=NONE}
==>{state=PB, city=NONE}
==>{state=UT, city=NONE}
==>{state=BR, city=NONE}
==>{state=CT, city=NONE}
==>{state=DN, city=NONE}
==>{state=DL, city={cityId=f715b5d9-96b5-4907-a4b4-91eb2fdd0022, cityName=New Delhi}}
=>{state=KA, city={cityId=5f37f9e9-bed0-4a9f-9bec-bb296672e579, cityName=Bengaluru}}
==>{state=KL, city=NONE}
==>{state=LD, city=NONE}
==>{state=MP, city=NONE}
==>{state=MH, city={cityId=256c974a-c4f7-4145-bc26-43566cfa9009, cityName=Mumbai}}
==>{state=NL, city=NONE}

在我试过的输出中,只有一个城市的属性。 在某些州,我们拥有的不仅仅是一座城市。但我没有得到两个城市的数据。我该如何处理它?

您需要 fold()by():

g.V().hasLabel('Province').has('code','IN').
  inE('partOf').outV().hasLabel('Province').has('type','state').
  project('state','city').
    by(values('code')).
    by(coalesce(inE('partOf').outV().hasLabel('Province').
                has('type','city').
                project('cityId','cityName').
                  by('cityId').by('cityName').
                fold(),
       constant('NONE')))

请注意,您可以稍微简化为:

g.V().hasLabel('Province').has('code','IN').
  in('partOf').hasLabel('Province').has('type','state').
  project('state','city').
    by('code').
    by(coalesce(__.in('partOf').hasLabel('Province').
                has('type','city').
                valueMap('cityId','cityName').
                  by(unfold()).
                fold(),
       constant('NONE')))

by() 只会 next() 作为参数提供给它的匿名子遍历,因此如果您有多个预期结果,您需要提供自己的归约操作(例如 fold(), count(), 等等)