ruby-on-railsneo4jneo4jrb

Rails Neo4j Find all nodes related to some node


Say there are 2 models:

class A
  include Neo4j::ActiveNode
    property :name, type: String
    has_many :in, :bs, type: :HAS_B
end

class B
  include Neo4j::ActiveNode
    property :name, type: String
end

And following nodes and relations:

a1 <- b1
a2 <- b1
a3 <- b2
a1 <- b2

Now, I want all nodes of label: A that are in relation to a specific node of label: B.

How can I achieve that through neo4jrb?

In simple english, I want "All nodes labelled A which have a relation to node b1" (and this can be extended to multiple nodes, like all nodes of label A which have relation with nodes b1 and b2)


Solution

  • This is how I did it:

    A.as(:a).B.where(name: [b1])
    

    Here, for multiple b's, just send array of all required b's.

    Note that, this query gives all a's which are connected to any of the b's in the array, which suited my requirement in this case. If you want something that gives all a's which are connected to all b's, this won't work. However, if anyone comes across such query, post it in comments and I will include it here in this post.