Joel Stevick
Joel Stevick

Reputation: 2028

Gremlin: need an efficient query to check whether two vertices are connected?

Our app needs to check whether two vertices are connected via any path.

The app does not care about the segments in a path, or the shortest path.

The app only needs to know if two vertices share a common sub-graph.

My question: given two vertices with id(s) A and B, respectively, what gremlin query works well to answer the question "are A and B connected, somehow?"

Upvotes: 0

Views: 1213

Answers (1)

Daniel Kuppitz
Daniel Kuppitz

Reputation: 10904

This one should do the trick:

g.V(A).
  repeat(both().dedup()).
    until(hasId(B)).
  hasNext()

Start at A, then start visiting neighbors, don't visit any vertex twice, and stop if B is reached. Obviously, this can run into timeouts (or memory issues) if you are dealing with huge subgraphs.

Upvotes: 1

Related Questions