You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

加权图中文章节点间路径权重求和的Gremlin查询优化

问题描述

我有一个双向加权图,边带有weight属性。**文章(article)节点间的紧密性(closeness)**定义为两个article节点间所有路径的weight总和。

目前我能获取article间的路径,但仅能得到单条路径的weight值,需要对起始article通过repeat(outE().inV().simplePath()).until(hasLabel('article'))返回的所有路径的weight进行聚合求和。

当前尝试的查询语句

g.V('8630')
    .repeat(outE().inV().simplePath())
    .until(hasLabel('article')).as('foundArticle')
    .path()
    .map(unfold().coalesce(values('weight'), constant(0)).sum()).as('pathWeight')
    .group().by(select('foundArticle').id()).as('grouping')

当前输出结果

[
  {
    "8634": [0.1, 0.5, 0.8]
  },
  {
    "8640": [0.1, 0.8]
  },
  {
    "8642": [0.1]
  }
]

期望输出结果

[
  {
    "8634": 1.4
  },
  {
    "8640": 0.9
  },
  {
    "8642": 0.1
  }
]

示例图创建语句

g.addV('article').as('1').
  addV('brand').as('2').
  addV('article').as('3').
  addV('category').as('4').
  addV('zone').as('5').
  addV('article').as('6').
  addV('article').as('7').
  addE('zone').from('1').to('5').  property('weight', 0.1).
  addE('category').from('1').to('4').property('weight', 0.5).
  addE('brand').from('1').to('2').property('weight', 0.8).
  addE('article').from('2').to('6').
  addE('article').from('2').to('1').
  addE('article').from('2').to('3').  
  addE('zone').from('3').to('5').property('weight', 0.1).  
  addE('category').from('3').to('4').property('weight', 0.3).
  addE('brand').from('3').to('2').property('weight', 0.4).
  addE('article').from('4').to('1').
  addE('article').from('4').to('3').
  addE('article').from('5').to('6').
  addE('article').from('5').to('7').
  addE('article').from('5').to('1').
  addE('article').from('5').to('3').
  addE('zone').from('6').to('5').property('weight', 0.1).
  addE('brand').from('6').to('2').property('weight', 0.6).
  addE('zone').from('7').to('5').property('weight', 0.1)   
解决方案

只需要在group()操作中指定聚合函数为sum(),就能将每个目标article对应的所有路径weight求和,而不是收集成列表。修改后的查询语句如下:

g.V('8630')
    .repeat(outE().inV().simplePath())
    .until(hasLabel('article')).as('foundArticle')
    .path()
    .map(unfold().coalesce(values('weight'), constant(0)).sum())
    .group().by(select('foundArticle').id()).by(sum(local))

解释

  • group().by(select('foundArticle').id()).by(sum(local)):第一个by指定分组依据为目标article的ID,第二个by指定对每个分组内的路径weight值执行求和操作,最终得到每个article对应的总紧密性值。

内容的提问来源于stack exchange,提问作者PaulG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 05:54:39