Skip to content

Instantly share code, notes, and snippets.

@ckwang8128
Created March 1, 2012 19:35
Show Gist options
  • Select an option

  • Save ckwang8128/1952512 to your computer and use it in GitHub Desktop.

Select an option

Save ckwang8128/1952512 to your computer and use it in GitHub Desktop.
Neo4j Snippet
require 'neo4j'
class User < Neo4j::Rails::Model
include Neo4j::NodeMixin #Should this be here?
property :name
property :id
index :id, :type => :exact
index :name, :type => :exact
has_n(:friends).to(User).relationship(Friend)
def User.get_or_create_node(inserter, id, clazz)
n = inserter.index_query("id: #{id}", :exact, clazz)
n = n.first if n
unless n
n = inserter.create_node({'id' => id}, clazz)
inserter.index_flush(clazz)
end
n
end
def User.friend_batch
Neo4j.shutdown
inserter = Neo4j::Batch::Inserter.new
for i in 1..10
#Here I'm reading a csv file of lines with two ids and creating what I think are Users and friend rels between them.
File.open("app/models/friends_split/friends#{i}.csv", 'r').each_line { |line|
id1, id2 = line.split(',')
n = get_or_create_node(inserter, id1.to_i, User)
m = get_or_create_node(inserter, id2.to_i, User)
inserter.create_rel(User.friends, n, m)
inserter.create_rel(User.friends, m, n)
}
puts "Done with #{i}"
end
inserter.shutdown
end
end
class Friend < Neo4j::Rails::Relationship
property :created_at, :type => DateTime
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment