Mongodb with Rails

2,813 views

Published on

First presentation from Trójmiasto Ruby Users Group.
Primary information about MongoDB and using it with Rails & MongoMapper.

Published in: Technology
1 Comment
3 Likes
Statistics
Notes
  • Cool!!!!!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
2,813
On SlideShare
0
From Embeds
0
Number of Embeds
41
Actions
Shares
0
Downloads
0
Comments
1
Likes
3
Embeds 0
No embeds

No notes for slide

Mongodb with Rails

  1. 1. MongoDB - case study Sebastian Nowak 3 marca 2010
  2. 2. NoSQL NoSQL - po co? ACID nie zawsze jest potrzebny RDBMS nie radzą sobie z dużym wolumenem danych (TB, PB) elastyczność
  3. 3. NoSQL NoSQL - po co? ACID nie zawsze jest potrzebny RDBMS nie radzą sobie z dużym wolumenem danych (TB, PB) elastyczność NoSQL - wady Godne zaufania?
  4. 4. NoSQL CouchDB MongoDB Redis Neo4j Memcachedb
  5. 5. MongoDB - właściwości napisane w C++
  6. 6. MongoDB - właściwości napisane w C++ dokumenty składuje jako BSON
  7. 7. MongoDB - właściwości napisane w C++ dokumenty składuje jako BSON zaprojektowane by pracować w chmurze
  8. 8. MongoDB - właściwości napisane w C++ dokumenty składuje jako BSON zaprojektowane by pracować w chmurze UTF-8
  9. 9. MongoDB - właściwości napisane w C++ dokumenty składuje jako BSON zaprojektowane by pracować w chmurze UTF-8 protokół binarny
  10. 10. MongoDB - właściwości napisane w C++ dokumenty składuje jako BSON zaprojektowane by pracować w chmurze UTF-8 protokół binarny sterowniki do wielu języków
  11. 11. MongoDB - właściwości napisane w C++ dokumenty składuje jako BSON zaprojektowane by pracować w chmurze UTF-8 protokół binarny sterowniki do wielu języków GridFS
  12. 12. MongoDB - właściwości napisane w C++ dokumenty składuje jako BSON zaprojektowane by pracować w chmurze UTF-8 protokół binarny sterowniki do wielu języków GridFS map-reduce, JavaScript
  13. 13. Capped collections Idealne do składowania: logów próbek pomiarów (round robin?) db.createCollection("books"); db.createCollection("probes",{capped:true, size:86400});
  14. 14. Insert - save doc = { title:"Ruby wzorce projektowe", author:"Russ Olsen", tags:["oop","ruby"] }; db.books.save(doc); db.books.save({ title:”The Ruby Way”, :author:”Obie Fernandez”, tags[”ruby”]});
  15. 15. Select - find db.books.findOne(); db.books.find(); db.books.find({title:"The Ruby Way"}); db.books.find({tags:"ruby"}); db.books.find({}, {title:1}); db.books.find().skip(10).limit(10); db.books.find({tags:{$size: 2}}); db.books.find({title:/Ruby/}); db.books.find({author:{$in:["Obie Fernandez", "Russ Olsen", "Gabierl Garcia Marquez"]}}); Inne modyfikatory: $ne, $in, $nin, $exist, $mod, $all, $size, $where
  16. 16. Select - group db.books.group({ key:author:true, cond:, reduce: function(obj,prev) { prev.count++; }, initial:{count:0} });
  17. 17. config/database.yml development: database: ratemymodel_development test: database: ratemymodel_test production: host: port: 9099 database: ratemymodel_production
  18. 18. initializers/mongodb.rb conf = File.read("#{RAILS_ROOT}/config/database.yml") db_conf = YAML.load(conf)[RAILS_ENV] db_conf["host"] ||= "127.0.0.1" db_conf["port"] ||= 27017 logger = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}_mongodb.log") MongoMapper.connection = Mongo::Connection.new(db_conf["host"], db_conf["port"] :logger => logger) MongoMapper.database = db_conf["database"]
  19. 19. test/test helper.rb class ActiveSupport::TestCase # Drop all columns after each test case. def teardown MongoMapper.database.collections.each do |coll| coll.remove end end # Make sure that each test case has a teardown # method to clear the db after each test. def inherited(base) base.define_method teardown do super end end end
  20. 20. config/environment.rb Rails::Initializer.run do |config| config.gem ’mongo_mapper’ config.gem ’haml’ config.gem ’will_paginate’ config.gem ’hoptoad_notifier’ config.gem ’carrierwave’ config.gem ’newrelic_rpm’ config.frameworks -= [:active_record] config.metals = ["GridFile"] end
  21. 21. app/models/model.rb # This class represents a model saved in application. class Model include MongoMapper::Document include MongoMapper::FindRandom # Fields definition key :name, String, :required => true key :description, String, :required => true key :tags, Array key :wins, Integer, :default => 0 key :defeats, Integer, :default => 0 key :ratio, Float, :default => 0 key :user_id, ObjectId # Associations belongs_to :user many :assets, :dependent => :destroy # Use created_at and updated_at timestamps timestamps! end
  22. 22. CarrierWave — konfiguracja # CarrierWave configuration CarrierWave.configure do |config| config.grid_fs_database = MongoMapper.database.name config.grid_fs_host = MongoMapper.connection.host config.grid_fs_access_url = "/images" end ./script/generate uploader asset
  23. 23. app/uploaders/asset uploader.rb class AssetUploader < CarrierWave::Uploader::Base include CarrierWave::RMagick storage :grid_fs def store_dir "assets/#{model.id}" end version :thumb { process :resize_to_fill => [200, 200] } version :comparable { process :resize_to_fill => [450,450] } def extension_white_list %w(jpg jpeg png) end end
  24. 24. app/models/asset.rb # Asset connected with model. It could be photo image etc. class Asset include MongoMapper::Document include MongoMapper::FindRandom # Uploader for image mount_uploader :image, AssetUploader # Fields definition key :model_id, ObjectId, :required => true # Callbacks after_destroy :remove_image_from_db # Associations belongs_to :model end
  25. 25. >> @asset.image.url => "/images/assets/4b6f009f00090d3b0c000002/10769300.jpg" >> @asset.image.comparable.url => "/images/assets/4b6f009f00090d3b0c000002/comparable_10769300.jpg" >> @asset.image.thumb.url => "/images/assets/4b6f009f00090d3b0c000002/thumb_10769300.jpg"
  26. 26. app/metals/grid file.rb class GridFile def self.call(env) if env["PATH_INFO"] =~ /^/images/assets/(.+)$/ key = "assets/" + $1 if ::GridFS::GridStore.exist?(MongoMapper.database, key) ::GridFS::GridStore.open(MongoMapper.database, key, ’r’) do |file| [200, {’Content-Type’ => file.content_type}, [file.read]] end else [404, {’Content-Type’ => ’text/plain’}, [’File not found.’]] end else [404, {’Content-Type’ => ’text/plain’}, [’File not found.’]] end end end
  27. 27. http://www.mongodb.org/display/DOCS/Home http://mongotips.com/ http://github.com/jnunemaker/mongomapper http://github.com/jnicklas/carrierwave http://guides.rubyonrails.org/rails on rack.html http://railstips.org/blog/archives/2009/12/18/why-i-think- mongo-is-to-databases-what-rails-was-to-frameworks/ http://blog.boxedice.com/2010/02/28/notes-from-a- production-mongodb-deployment/

×