Skip to content

Instantly share code, notes, and snippets.

@cheerfulstoic
Created March 4, 2016 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheerfulstoic/acf0b28355f2d49d8861 to your computer and use it in GitHub Desktop.
Save cheerfulstoic/acf0b28355f2d49d8861 to your computer and use it in GitHub Desktop.
Relationships in Neo4j.rb

You can, of course, just execute a Cypher query:

session = Neo4j::Session.open(:server_db, 'http://neo4j:password@localhost:7474')

result = session.query("MATCH (p:Person {uuid: {uuid}})-[r:LIKES]->(f:Food) RETURN p, r, f", uuid: 1234)

# First result
result[0].p # Person
result[0].r # `LIKES` Relationship
result[0].f # Food

You can also use the Query API:

result = session.query.match('(p:Person {uuid: {uuid}})-[r:LIKES]->(f:Food)').return(:p, :r, :f)

# result is same as above=
# or...

# pluck returns an array of arrays
result = session.query.match('(p:Person {uuid: {uuid}})-[r:LIKES]->(f:Food)').pluck(:p, :r, :f)

person, rel, food = result[0]

Or you can use ActiveNode:

class Person
  include Neo4j::ActiveNode
  has_many :out, :liked_foods, type: :LIKES, model_class: :Food
end

class Food
  include Neo4j::ActiveNode
end

person = Person.first
person.liked_foods(:food, :rel).pluck(:rel, :food)

# Or to get all people:

Person.as(:person).liked_foods(:food, :rel).pluck(:person, :rel, :food)

If you want your relationships to be more substantial (with properties/validations/callbacks/etc...

class Person
  include Neo4j::ActiveNode
  has_many :out, :liked_foods, type: :LIKES, model_class: :Food
end

class Likes
  from_class :Person
  to_class :Food # or :any if people can like other things too
  
  property :how_much, type: Integer
  
  validates :how_much, inclusion: {in: (0..5)}
end

class Food
  include Neo4j::ActiveNode
end

person = Person.first
person.liked_foods(:food, :rel).pluck(:rel, :food).each do |rel, food|
  puts "#{person.name} likes #{food.name} with a score of #{rel.how_much}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment