SlideShare a Scribd company logo
Getting Started with
    Couchbase Ruby
              Sergey Avseyev
       sergey@couchbase.com
Couchbase Server
What Is Couchbase Server




 • NoSQL database solution
 • No fixed schema
 • Automatic key sharding
 • Automatic replication
 • Low latency optimized
 • No multi-operation transaction support
Who Uses Couchbase Server: Heroku




 • Leading cloud service (PAAS) provider
 • Over 1,500,000 hosted applications
 • Couchbase Server serving over 11,800 Heroku customers
Who Uses Couchbase Server: Zynga




 • Social game leader — FarmVille, Mafia Wars, Empires and Allies,
   Café World, FishVille
 • Over 230 million monthly users
 • Couchbase Server is the primary database behind key Zynga properties
Current Version: 1.1.2
Installation



Install stable version of libcouchbase-dev with dependencies using
instructions at http://www.couchbase.com/develop/c/current

  $ gem install couchbase
  Fetching: couchbase-1.1.2.gem (100%)
  Building native extensions. This could take a while...
  Successfully installed couchbase-1.1.2
  1 gems installed
Connect to the Cluster



Pass connection parameters explicitly

  conn = Couchbase.connect(:bucket => ’test’)


Use thread-local connection instance

  Couchbase.connection_options = :bucket => ’test’
  conn = Couchbase.bucket
Simple CRUD
Write key or fail it it is exists already

     cas = conn.add(”key”, ”value”)


Write key unconditionally

     cas = conn.set(”key”, ”value”)


Write key only if it is exists

     cas = conn.replace(”key”, ”value”)


     value = conn.get(”key”)
Optimistic Locks


All mutators accepts CAS value (some kind of version or checksum of the
key)

    value, flags, cas = conn.get(”key”, ”value”,
                                 :extended => true)


Setting with wrong CAS value will raise Couchbase::Error::KeyExists

    conn.set(”key”, ”newvalue”, :cas => 1234)
    #=> Couchbase::Error::KeyExists: failed to store value
Expiration


Write key and set expiration

    conn.set(”key”, ”value”, :ttl => 1.minute)


Read key and set expiration

    conn.get(”key”, :ttl => 1.minute)


Only update expiration

    conn.touch(”key”, :ttl => 1.minute)
Miscellaneous

Multi get

    foo, bar = conn.get(”foo”, ”bar”)


Multi touch

    conn.touch(”foo” => 30.seconds, ”bar” => 10.minutes)


Increment/Decrement

    conn.incr(”counter”)
    conn.decr(”counter”)
Next Version: 1.2.0.dp5
Installation



Install next version of libcouchbase-dev with dependencies using
instructions at http://www.couchbase.com/develop/c/next

    $ gem install couchbase --pre
    Fetching: couchbase-1.2.0.dp5.gem (100%)
    Building native extensions. This could take a while...
    Successfully installed couchbase-1.2.0.dp5
    1 gems installed
Map/Reduce Analysis
Define design document containing single map function (using admin
panel or Bucket#save_design_doc):

    {
        ”_id”: ”_design/users”,
        ”views”: {
          ”all_by_email”: {
            ”map”: ”function(doc) {
                      if (doc.type == ”User”)
                        emit(doc.email, null);
                    }”
          },
        }
    }
Executing views


Pick up design document:

     ddoc = conn.design_docs[”users”]


Iterate over view results

     ddoc.all_by_email(:include_docs => true).each do |doc|
       puts doc.key
       puts doc.doc.inspect
     end
Pessimistic Locks




    value = conn.get(”key”, :lock => 5.seconds)


All subsequent mutators are forced to use corresponding CAS value or fail
Rack Session Storage




   # config.ru
   require ’rack/session/couchbase’
   use Rack::Session::Couchbase,
       :expire_after => 5.minutes,
       :couchbase => {:bucket => ”sessions”}
Rails Session Storage




   # config/initializers/session_store.rb
   require 
     ’action_dispatch/middleware/session/couchbase_store’

   Name::Application.config.session_store :couchbase_store,
                     :expire_after => 5.minutes,
                     :couchbase => {:bucket => ”sessions”}
Rails Cache Storage



   # config/application.rb
   cache_options = {
     :bucket => ’protected’,
     :username => ’protected’,
     :password => ’secret’,
     :expires_in => 2.hours
   }
   config.cache_store = :couchbase_store, cache_options
Even More :)
ODM (Object Document Model) for Rails


https://github.com/couchbaselabs/ruby-couchbase-model

   $ gem install couchbase-model


   class Post < Couchbase::Model
     attribute :title
     attribute :body
     attribute :created_at, :default => lambda { Time.now }
     view :by_created_at
   end
Couchbase for EventMachine (experimental)




https://github.com/couchbaselabs/couchbase-ruby-client-em

   $ gem install em-couchbase
Thanks
Questions?
Find these slides at:
github.com/avsej/getting-started-with-couchbase-ruby

More Related Content

PPTX
PDF
Configuration Management in Ansible
PPTX
Ansible presentation
PDF
Network Automation: Ansible 102
PDF
Ansible is the simplest way to automate. MoldCamp, 2015
PDF
Ansible Meetup Hamburg / Quickstart
PPTX
Creating Reusable Puppet Profiles
PDF
More tips n tricks
Configuration Management in Ansible
Ansible presentation
Network Automation: Ansible 102
Ansible is the simplest way to automate. MoldCamp, 2015
Ansible Meetup Hamburg / Quickstart
Creating Reusable Puppet Profiles
More tips n tricks

What's hot (20)

PPTX
Ansible 101, Gennadiy Mykhailiuta
PPT
Ansible presentation
PDF
Autoscaling with hashi_corp_nomad
PDF
Ansible loves Python, Python Philadelphia meetup
PDF
AnsibleFest 2014 - Role Tips and Tricks
PDF
Automating OSD and Post-OSD Configuration with Powershell and Orchestrator
PPTX
Data integration with embulk
PDF
Usecase examples of Packer
PDF
Building Distributed System with Celery on Docker Swarm
PDF
V2 and beyond
PDF
Docker & CoreOS at Utah Gophers
PDF
Automation with Ansible and Containers
PDF
#OktoCampus - Workshop : An introduction to Ansible
PPTX
Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...
PDF
Czym jest webpack i dlaczego chcesz go używać?
PPTX
Introduction to Ansible
PPTX
Ansible presentation
PPTX
PowerShell User Group Hamburg - PowerCLI
PPT
Dance for the puppet master: G6 Tech Talk
PDF
Vidoop CouchDB Talk
Ansible 101, Gennadiy Mykhailiuta
Ansible presentation
Autoscaling with hashi_corp_nomad
Ansible loves Python, Python Philadelphia meetup
AnsibleFest 2014 - Role Tips and Tricks
Automating OSD and Post-OSD Configuration with Powershell and Orchestrator
Data integration with embulk
Usecase examples of Packer
Building Distributed System with Celery on Docker Swarm
V2 and beyond
Docker & CoreOS at Utah Gophers
Automation with Ansible and Containers
#OktoCampus - Workshop : An introduction to Ansible
Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...
Czym jest webpack i dlaczego chcesz go używać?
Introduction to Ansible
Ansible presentation
PowerShell User Group Hamburg - PowerCLI
Dance for the puppet master: G6 Tech Talk
Vidoop CouchDB Talk
Ad

Viewers also liked (15)

PDF
2015-12-05 Данил Никифоров - NoSQL для мобайла с синхронизацией данных
PPT
Web весна 2012 лекция 6
PPTX
Опыт использования NoSQL-хранилищ (Андрей Новиков)
PPTX
Спасение 6 млн файлов в условиях полного хецнера (Даниил Подольский, Дмитрий ...
PPTX
NoSQL - World IT Planet, Saint Petersburg 2015
PPT
Как устроен NoSQL, Андрей Аксенов (Sphinx)
PPTX
Oracle NoSQL Database
PPTX
Apache Cassandra. Ещё одно NoSQL хранилище (Владимир Климонтович)
PDF
NoSQL и Zend Framework (Ростислав Михайлив)
PDF
За гранью NoSQL: NewSQL на Cassandra
PPTX
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"
PDF
NoSQL - коротко о главном / Сергей Туленцев (TextMaster)
PPTX
NoSQL - взрыв возможностей
PDF
ClickHouse: очень быстро и очень удобно / Виктор Тарнавский, Алексей Миловидо...
PDF
NoNoSQL = Not Only NoSQL, HappyDev'13
2015-12-05 Данил Никифоров - NoSQL для мобайла с синхронизацией данных
Web весна 2012 лекция 6
Опыт использования NoSQL-хранилищ (Андрей Новиков)
Спасение 6 млн файлов в условиях полного хецнера (Даниил Подольский, Дмитрий ...
NoSQL - World IT Planet, Saint Petersburg 2015
Как устроен NoSQL, Андрей Аксенов (Sphinx)
Oracle NoSQL Database
Apache Cassandra. Ещё одно NoSQL хранилище (Владимир Климонтович)
NoSQL и Zend Framework (Ростислав Михайлив)
За гранью NoSQL: NewSQL на Cassandra
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"
NoSQL - коротко о главном / Сергей Туленцев (TextMaster)
NoSQL - взрыв возможностей
ClickHouse: очень быстро и очень удобно / Виктор Тарнавский, Алексей Миловидо...
NoNoSQL = Not Only NoSQL, HappyDev'13
Ad

Similar to Getting Started with Couchbase Ruby (20)

KEY
Writing robust Node.js applications
PDF
Cutting through the fog of cloud
KEY
fog or: How I Learned to Stop Worrying and Love the Cloud
KEY
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
PPTX
Packer, where DevOps begins
PDF
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013
PPT
Play!ng with scala
PDF
From Dev to DevOps - Codemotion ES 2012
ZIP
Rails 3 (beta) Roundup
KEY
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
PDF
Node.js - async for the rest of us.
ODP
Puppetpreso
ODP
Infrastructure as code with Puppet and Apache CloudStack
ODP
Puppet and Apache CloudStack
ODP
Puppet and CloudStack
PDF
soft-shake.ch - Hands on Node.js
PPTX
Stack kicker devopsdays-london-2013
KEY
Railsconf2011 deployment tips_for_slideshare
PDF
AWS Lambda with Serverless Framework and Java
PDF
Igor Davydenko
Writing robust Node.js applications
Cutting through the fog of cloud
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
Packer, where DevOps begins
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013
Play!ng with scala
From Dev to DevOps - Codemotion ES 2012
Rails 3 (beta) Roundup
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
Node.js - async for the rest of us.
Puppetpreso
Infrastructure as code with Puppet and Apache CloudStack
Puppet and Apache CloudStack
Puppet and CloudStack
soft-shake.ch - Hands on Node.js
Stack kicker devopsdays-london-2013
Railsconf2011 deployment tips_for_slideshare
AWS Lambda with Serverless Framework and Java
Igor Davydenko

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Network Security Unit 5.pdf for BCA BBA.
PPT
Teaching material agriculture food technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Empathic Computing: Creating Shared Understanding
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Machine learning based COVID-19 study performance prediction
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
MYSQL Presentation for SQL database connectivity
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
“AI and Expert System Decision Support & Business Intelligence Systems”
Network Security Unit 5.pdf for BCA BBA.
Teaching material agriculture food technology
Per capita expenditure prediction using model stacking based on satellite ima...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Empathic Computing: Creating Shared Understanding
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
NewMind AI Monthly Chronicles - July 2025
Machine learning based COVID-19 study performance prediction
Advanced Soft Computing BINUS July 2025.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Dropbox Q2 2025 Financial Results & Investor Presentation
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton

Getting Started with Couchbase Ruby

  • 1. Getting Started with Couchbase Ruby Sergey Avseyev [email protected]
  • 3. What Is Couchbase Server • NoSQL database solution • No fixed schema • Automatic key sharding • Automatic replication • Low latency optimized • No multi-operation transaction support
  • 4. Who Uses Couchbase Server: Heroku • Leading cloud service (PAAS) provider • Over 1,500,000 hosted applications • Couchbase Server serving over 11,800 Heroku customers
  • 5. Who Uses Couchbase Server: Zynga • Social game leader — FarmVille, Mafia Wars, Empires and Allies, Café World, FishVille • Over 230 million monthly users • Couchbase Server is the primary database behind key Zynga properties
  • 7. Installation Install stable version of libcouchbase-dev with dependencies using instructions at http://www.couchbase.com/develop/c/current $ gem install couchbase Fetching: couchbase-1.1.2.gem (100%) Building native extensions. This could take a while... Successfully installed couchbase-1.1.2 1 gems installed
  • 8. Connect to the Cluster Pass connection parameters explicitly conn = Couchbase.connect(:bucket => ’test’) Use thread-local connection instance Couchbase.connection_options = :bucket => ’test’ conn = Couchbase.bucket
  • 9. Simple CRUD Write key or fail it it is exists already cas = conn.add(”key”, ”value”) Write key unconditionally cas = conn.set(”key”, ”value”) Write key only if it is exists cas = conn.replace(”key”, ”value”) value = conn.get(”key”)
  • 10. Optimistic Locks All mutators accepts CAS value (some kind of version or checksum of the key) value, flags, cas = conn.get(”key”, ”value”, :extended => true) Setting with wrong CAS value will raise Couchbase::Error::KeyExists conn.set(”key”, ”newvalue”, :cas => 1234) #=> Couchbase::Error::KeyExists: failed to store value
  • 11. Expiration Write key and set expiration conn.set(”key”, ”value”, :ttl => 1.minute) Read key and set expiration conn.get(”key”, :ttl => 1.minute) Only update expiration conn.touch(”key”, :ttl => 1.minute)
  • 12. Miscellaneous Multi get foo, bar = conn.get(”foo”, ”bar”) Multi touch conn.touch(”foo” => 30.seconds, ”bar” => 10.minutes) Increment/Decrement conn.incr(”counter”) conn.decr(”counter”)
  • 14. Installation Install next version of libcouchbase-dev with dependencies using instructions at http://www.couchbase.com/develop/c/next $ gem install couchbase --pre Fetching: couchbase-1.2.0.dp5.gem (100%) Building native extensions. This could take a while... Successfully installed couchbase-1.2.0.dp5 1 gems installed
  • 15. Map/Reduce Analysis Define design document containing single map function (using admin panel or Bucket#save_design_doc): { ”_id”: ”_design/users”, ”views”: { ”all_by_email”: { ”map”: ”function(doc) { if (doc.type == ”User”) emit(doc.email, null); }” }, } }
  • 16. Executing views Pick up design document: ddoc = conn.design_docs[”users”] Iterate over view results ddoc.all_by_email(:include_docs => true).each do |doc| puts doc.key puts doc.doc.inspect end
  • 17. Pessimistic Locks value = conn.get(”key”, :lock => 5.seconds) All subsequent mutators are forced to use corresponding CAS value or fail
  • 18. Rack Session Storage # config.ru require ’rack/session/couchbase’ use Rack::Session::Couchbase, :expire_after => 5.minutes, :couchbase => {:bucket => ”sessions”}
  • 19. Rails Session Storage # config/initializers/session_store.rb require ’action_dispatch/middleware/session/couchbase_store’ Name::Application.config.session_store :couchbase_store, :expire_after => 5.minutes, :couchbase => {:bucket => ”sessions”}
  • 20. Rails Cache Storage # config/application.rb cache_options = { :bucket => ’protected’, :username => ’protected’, :password => ’secret’, :expires_in => 2.hours } config.cache_store = :couchbase_store, cache_options
  • 22. ODM (Object Document Model) for Rails https://github.com/couchbaselabs/ruby-couchbase-model $ gem install couchbase-model class Post < Couchbase::Model attribute :title attribute :body attribute :created_at, :default => lambda { Time.now } view :by_created_at end
  • 23. Couchbase for EventMachine (experimental) https://github.com/couchbaselabs/couchbase-ruby-client-em $ gem install em-couchbase
  • 25. Find these slides at: github.com/avsej/getting-started-with-couchbase-ruby