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

JanusGraph Scala实现:高效检查并获取两顶点间指定有向边

Got it, I totally get where you're coming from—when working with JanusGraph in Scala, some Gremlin steps don't translate exactly the way you'd expect, especially when it comes to otherV(). Let's break down how to check for and retrieve that directed edge between v1 and v2 with specific properties.

Checking if the Edge Exists

Since we're dealing with a directed edge from v1 to v2, we can skip the ambiguity of otherV() and use inV() directly to target the destination vertex. This makes the query more explicit and plays nicely with Scala's Gremlin integration.

Basic existence check (no property filter)

val edgeExists: Boolean = g.V(v1).outE().inV().is(v2).hasNext()

Existence check with specific property

If you need to filter by a property (e.g., an edge labeled relationType with value friend), just add a has() step before checking the target vertex:

val edgeExistsWithProp: Boolean = 
  g.V(v1)
    .outE()
    .has("relationType", "friend") // Add your property filter here
    .inV()
    .is(v2)
    .hasNext()

Retrieving the Edge

Once you confirm the edge exists (or wrap the call safely to handle missing edges), you can fetch it directly. Using Option is a good practice here to avoid NoSuchElementException if the edge doesn't exist.

Retrieve edge without property filter

val edgeOption: Option[Edge] = Option(g.V(v1).outE().inV().is(v2).next())

Retrieve edge with specific property

val edgeWithPropOption: Option[Edge] = 
  Option(
    g.V(v1)
      .outE()
      .has("relationType", "friend")
      .inV()
      .is(v2)
      .next()
  )

Alternative: Iterate Directly Over Vertex Edges

If you prefer a more imperative approach (great for small edge sets), you can iterate over v1's outgoing edges directly and filter for the target vertex and properties:

import scala.jdk.CollectionConverters._

val targetEdge: Option[Edge] = 
  v1.outE().iterator().asScala.find { edge =>
    edge.inVertex().equals(v2) && 
    edge.property("relationType").value().equals("friend")
  }

A quick note on otherV(): technically you can use it in Scala, but since we're dealing with a directed edge from v1 to v2, inV() is more precise and avoids any confusion about which vertex is the "other" one. It's cleaner and aligns better with the directed nature of your query.

内容的提问来源于stack exchange,提问作者J.Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:13:45