如何用Gremlin将多顶点数据返回为单个嵌套对象
问题:用Gremlin生成嵌套结构的整合对象
我正尝试使用Gremlin返回一个整合了多个顶点数据的单个嵌套对象,目标是获取指定referenceSignal和system对应的externalReferences列表。目前已经通过.select()拿到了所需顶点,但不知道怎么把这些数据处理成单个嵌套对象。
数据模型
顶点与边关系如下:
system顶点,被component顶点通过partOf边关联component顶点,被signal顶点通过partOf边关联signal顶点,通过instanceOf边关联referenceSignal顶点,同时被externalReference顶点通过describes边关联referenceSignal顶点externalReference顶点
当前查询
g.V().has('id', 'SYSTEM_ID').hasLabel('system').as("system") .in("partOf").hasLabel('component').as("component") .in("partOf").hasLabel('signal').as("signal") .where(out("instanceOf").hasLabel('referenceSignal').has("name", "REF_SIGNAL_NAME")).in("describes").hasLabel('externalReference').as("externalReference") .select('system', 'component', 'signal', 'externalReference')
现有输出
[{system=v[2776], component=v[2780], signal=v[2797], externalReference=v[2843]}, {system=v[2776], component=v[2785], signal=v[2802], externalReference=v[2848]}]
期望输出格式
{ "system_id": "{system_id from the system vertex}", "system_name": "{system_name from the system vertex}", "components": [ { "component_id": "{component_id from the component vertex}", "component_name": "{component_name from the component vertex}", "signals": [ { "signal_id": "{signal_id from the signal vertex}", "signal_name": "{signal_name from the signal vertex}", "external_reference_id": "{external_reference_id from the external reference vertex adjacent to the signal}" } ] } ] }
解决方案
可以通过Gremlin的project、group、by等步骤构建嵌套结构,修改后的查询如下:
g.V().has('id', 'SYSTEM_ID').hasLabel('system') .project('system_id', 'system_name', 'components') .by('id') .by('name') .by( __.in('partOf').hasLabel('component') .where( __.in('partOf').hasLabel('signal') .where(out('instanceOf').hasLabel('referenceSignal').has('name', 'REF_SIGNAL_NAME')) ) .group() .by(__.project('component_id', 'component_name').by('id').by('name')) .by( __.in('partOf').hasLabel('signal') .where(out('instanceOf').hasLabel('referenceSignal').has('name', 'REF_SIGNAL_NAME')) .group() .by(__.project('signal_id', 'signal_name').by('id').by('name')) .by(__.in('describes').hasLabel('externalReference').values('id').fold()) .unfold() .map(__.project('signal_id', 'signal_name', 'external_reference_id') .by(select(keys).select('signal_id')) .by(select(keys).select('signal_name')) .by(select(values).unfold()) ) .fold() ) .unfold() .map(__.project('component_id', 'component_name', 'signals') .by(select(keys).select('component_id')) .by(select(keys).select('component_name')) .by(select(values)) ) .fold() )
步骤说明
- 先定位目标
system顶点,用project初始化顶层结构,提取system的id和name。 - 在
components字段的处理中,先筛选关联的component顶点(需满足该component下有符合条件的signal)。 - 对每个
component,再次筛选符合条件的signal(关联指定name的referenceSignal),并关联对应的externalReference。 - 通过
group和map层级嵌套,把顶点属性映射成期望的嵌套对象结构,最后用fold()把同层级的元素整理成数组。
内容的提问来源于stack exchange,提问作者dominicst
相关产品推荐
相关产品推荐

