0

I have one node and one relationship

class User
  include Neo4j::ActiveNode

  property :first_name
end


class Connection
  include Neo4j::ActiveRel
  include Enumable

  creates_unique

  from_class 'User'
  to_class 'User'
  type 'connected_to'

  property :status, type: Integer, default: 0
end

I want to find 2nd degree connected user's from User1 which is not connected with User1 yet

User.find(1).query_as(:s)
  .match('(s) - [r1 :connected_to] - (mutual_friend) 
    - [r2 :connected_to] - (friends_of_friend: `User`)')
  .match('(s)-[r4:connected_to]-[friends_of_friend]')
  .where('r1.status = 1 AND r2.status = 1 AND r4 IS NULL')
  .pluck('DISTINCT friends_of_friend.uuid').count

But this is giving me 0 results everytime I also tried with optional match but it was giving a huge number, Any help on this??

Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
Vishal G
  • 1,521
  • 11
  • 30

2 Answers2

2

InverseFalcon is right, though there are various other things you can do to make it a lot simpler:

class User
  include Neo4j::ActiveNode

  property :first_name

  has_many :both, :connected_users, type: :connected_to, model_class: :User
end


# ActiveRel isn't strictly needed for this,
# though to have the `default` or any other logic it's good to have it


user = User.find(1)

user.as(:user)
    .connected_users.rel_where(status: 1)
    .connected_users(:friend_of_friend).rel_where(status: 1)
    .where_not('(user)-[:connected_to]-(friend_of_friend)')
    .count(:distinct)

I think that this would also work:

user.as(:user)
    .connected_users(:friend_of_friend, nil, rel_length: 2).rel_where(status: 1)
    .where_not('(user)-[:connected_to]-(friend_of_friend)')
    .count(:distinct)
Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
1

MATCH can't be used to find the lack of a pattern, that will never return rows. Using OPTIONAL MATCH instead should work.

Or, if the where_not() method allows patterns, you could use:

 .where_not('(s)-[:connected_to]-(friends_of_friend)')

as an alternate means to exclude that relationship.

Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
InverseFalcon
  • 29,576
  • 4
  • 38
  • 51