Created
January 13, 2010 23:18
-
-
Save dinge/276672 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$LOAD_PATH << './lib' | |
require "lib/neo4j" | |
require "rubygems" | |
require "ruby-debug" | |
class Person | |
include Neo4j::NodeMixin | |
# define Neo4j properties | |
property :name | |
# define an one way relationship to any other node | |
has_n :friends | |
has_one :loves # only one in this monogamic model | |
has_n :has_coded | |
# adds a Lucene index on the following properties | |
index :name | |
# hook method in initialize | |
# allows us to use more compact property setting | |
# like neo = Person.new(:name => 'Neos') | |
def init_node(*args) | |
(properties = args.first).is_a?(Hash) ? properties.each{ |k, v| self[k] = v } : nil | |
end | |
end | |
Neo4j::Transaction.run do | |
neo = Person.new(:name => 'Neo') # using init_node hook here | |
morpheus = Person.new(:name => 'Morpheus') | |
trinity = Person.new(:name => 'Trinity') | |
cypher = Person.new | |
cypher.name = 'Cypher' | |
cypher.friends << morpheus | |
smith = Person.new | |
smith.name = 'Agent Smith' | |
architect = Person.new | |
architect.name = 'Architect' | |
neo.friends << morpheus | |
morpheus.friends << trinity | |
cypher.friends << smith | |
trinity.loves = neo | |
architect.has_coded << smith | |
# or architect.rels.outgoing(:has_coded) << smith | |
# find Neo's friends | |
neo.friends.each { |n| puts 'Friend: ' + n.name } | |
# Neo's friends of friends | |
neo.friends.depth(2).each { |n| puts 'FOAF: ' + n.name } | |
# architect.traverse.both(:friends, :loves, :has_coded).depth(:all).filter do | |
architect.traverse.both(*Person.relationships_info.keys).depth(:all).filter do | |
outgoing(:loves).to_a.any? | |
# loves.to_a.any? # nicer and works also, but throws warning: default 'to_a' will be obsolete | |
end.each do |n| | |
puts n.name + ' loves ' + n.outgoing(:loves).to_a.first.name | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment