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

基于Apache TinkerPop Gremlin实现同类别网站查询的问题求助

基于Apache TinkerPop Gremlin查询同类顶点的正确写法

问题根源

你写的查询之所以返回所有网站,主要是两个问题:

  1. has()的动态参数用法错误:has("category", select('k').values("category")) 里,has()的第二个参数不能直接传递遍历器(select('k')属于遍历器),需要用where()来实现动态属性匹配逻辑。
  2. 未排除目标顶点:原查询没过滤掉输入的"W-ABC"本身,所以结果里会包含它。

正确查询示例

写法一:用where()做属性匹配+排除自身

g.V()
 .hasLabel('website')
 .has('name', 'W-ABC')
 .as('target')
 .V()
 .hasLabel('website')
 .where(neq('target')) // 去掉输入的网站本身
 .where(values('category').eq(select('target').values('category'))) // 匹配同类别
 .values('name')

写法二:先提取类别再过滤(更简洁)

先拿到目标网站的分类,再用这个分类筛选其他网站,同时排除自身:

g.V()
 .hasLabel('website')
 .has('name', 'W-ABC')
 .values('category')
 .as('targetCat')
 .V()
 .hasLabel('website')
 .has('category', select('targetCat'))
 .has('name', neq('W-ABC'))
 .values('name')

写法三:用match()结构化查询

如果逻辑复杂,match()能让遍历逻辑更清晰:

g.match(
  __.as('target').hasLabel('website').has('name', 'W-ABC'),
  __.as('similarSite').hasLabel('website').where(neq('target')),
  __.as('target').values('category').as('cat'),
  __.as('similarSite').values('category').as('cat')
).select('similarSite').values('name')

执行结果

不管用哪种写法,都会得到预期结果:

==>W-DEF
==>W-JKL

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:50:25