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

