2

I am using neo4j.rb in my rails application.

I already have two nodes n1 and n2 retrieved from the database.

Now i need to check if they have a path between them, i was thinking of using cypher queries using Neo4j::Session.query

But since i already have the two nodes i do not want to retrieve them again inside the query,(does it affect performance?) is there a way to do it?

I know i can use query1 = n1.query_as(:node1) and use it as the node identifier but how can i introduce n2 within the same query object so that i can check connectivity between them.

I want something equivalent to the query

RETURN 
  CASE 
    WHEN node1-[*..6]-node2  
    THEN 'Connected within 6 nodes'  
    ELSE 'Not connected within 6' 
  END

Where i already have node1 and node2.

Is a way to do this and also can this be done without using the CYPHER DSL?

Artemis Fowl
  • 301
  • 1
  • 10

1 Answers1

2

Here you go!

n1.query_as(:n1).match_nodes(n2: n2).match('n1-[*1..6]-n2').count

If you want to avoid the Cypher DSL I think you can do that with associations. As a starter example to traverse one level of relationships you can do this:

class N1Class
  include Neo4j::ActiveNode

  has_many :out, :test_association, type: :TEST_ASSOCIATION, model_class: :N2Class
end

n1.test_association.include?(n2)

That will test if they are directly connected via the test_association association. You can even specify false for your type to ignore the direction and false for the model_class to ignore the target labels.

To get the variable length you can do this:

n1.test_association(nil, nil, rel_length: 1..6).include?(n2)
Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
  • Nice i didn't know, you can do it without cypher DSL, is there a way we can get the shortest path between the two nodes also? – Vikash Balasubramanian Oct 18 '15 at 09:08
  • Yeah, i was also thinking the same thing, my cypher was not working, it was returning node urls i will post another question. – Artemis Fowl Oct 18 '15 at 09:39
  • Good idea! I don't think you can do that outside of the Cypher DSL yet, but I just created this issue to capture it: https://github.com/neo4jrb/neo4j/issues/994 – Brian Underwood Oct 18 '15 at 09:52