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

What's hot (20)

PPTX
Ansible 101, Gennadiy Mykhailiuta
Tetiana Saputo
 
PPT
Ansible presentation
John Lynch
 
PDF
Autoscaling with hashi_corp_nomad
Bram Vogelaar
 
PDF
Ansible loves Python, Python Philadelphia meetup
Greg DeKoenigsberg
 
PDF
AnsibleFest 2014 - Role Tips and Tricks
jimi-c
 
PDF
Automating OSD and Post-OSD Configuration with Powershell and Orchestrator
Digicomp Academy AG
 
PPTX
Data integration with embulk
Teguh Nugraha
 
PDF
Usecase examples of Packer
Hiroshi SHIBATA
 
PDF
Building Distributed System with Celery on Docker Swarm
Wei Lin
 
PDF
V2 and beyond
jimi-c
 
PDF
Docker & CoreOS at Utah Gophers
Josh Braegger
 
PDF
Automation with Ansible and Containers
Rodolfo Carvalho
 
PDF
#OktoCampus - Workshop : An introduction to Ansible
Cédric Delgehier
 
PPTX
Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...
mCloud
 
PDF
Czym jest webpack i dlaczego chcesz go używać?
Marcin Gajda
 
PPTX
Introduction to Ansible
CoreStack
 
PPTX
Ansible presentation
Arthur Freyman
 
PPTX
PowerShell User Group Hamburg - PowerCLI
Markus Kraus
 
PPT
Dance for the puppet master: G6 Tech Talk
Michael Peacock
 
PDF
Vidoop CouchDB Talk
Chris Anderson
 
Ansible 101, Gennadiy Mykhailiuta
Tetiana Saputo
 
Ansible presentation
John Lynch
 
Autoscaling with hashi_corp_nomad
Bram Vogelaar
 
Ansible loves Python, Python Philadelphia meetup
Greg DeKoenigsberg
 
AnsibleFest 2014 - Role Tips and Tricks
jimi-c
 
Automating OSD and Post-OSD Configuration with Powershell and Orchestrator
Digicomp Academy AG
 
Data integration with embulk
Teguh Nugraha
 
Usecase examples of Packer
Hiroshi SHIBATA
 
Building Distributed System with Celery on Docker Swarm
Wei Lin
 
V2 and beyond
jimi-c
 
Docker & CoreOS at Utah Gophers
Josh Braegger
 
Automation with Ansible and Containers
Rodolfo Carvalho
 
#OktoCampus - Workshop : An introduction to Ansible
Cédric Delgehier
 
Developers’ mDay 2019. - Rastko Vasiljević, SuperAdmins – Infrastructure as c...
mCloud
 
Czym jest webpack i dlaczego chcesz go używać?
Marcin Gajda
 
Introduction to Ansible
CoreStack
 
Ansible presentation
Arthur Freyman
 
PowerShell User Group Hamburg - PowerCLI
Markus Kraus
 
Dance for the puppet master: G6 Tech Talk
Michael Peacock
 
Vidoop CouchDB Talk
Chris Anderson
 

Viewers also liked (15)

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

Similar to Getting Started with Couchbase Ruby (20)

KEY
Writing robust Node.js applications
Tom Croucher
 
PDF
Cutting through the fog of cloud
Kyle Rames
 
KEY
fog or: How I Learned to Stop Worrying and Love the Cloud
Wesley Beary
 
KEY
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
Wesley Beary
 
PPTX
Packer, where DevOps begins
Jeff Hung
 
PDF
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013
Carlos Sanchez
 
PPT
Play!ng with scala
Siarzh Miadzvedzeu
 
PDF
From Dev to DevOps - Codemotion ES 2012
Carlos Sanchez
 
ZIP
Rails 3 (beta) Roundup
Wayne Carter
 
KEY
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
SV Ruby on Rails Meetup
 
PDF
Node.js - async for the rest of us.
Mike Brevoort
 
ODP
Puppetpreso
ke4qqq
 
ODP
Infrastructure as code with Puppet and Apache CloudStack
ke4qqq
 
ODP
Puppet and Apache CloudStack
Puppet
 
ODP
Puppet and CloudStack
ke4qqq
 
PDF
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
PPTX
Stack kicker devopsdays-london-2013
Simon McCartney
 
KEY
Railsconf2011 deployment tips_for_slideshare
tomcopeland
 
PDF
AWS Lambda with Serverless Framework and Java
Manish Pandit
 
PDF
Igor Davydenko
SCRUMguides
 
Writing robust Node.js applications
Tom Croucher
 
Cutting through the fog of cloud
Kyle Rames
 
fog or: How I Learned to Stop Worrying and Love the Cloud
Wesley Beary
 
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
Wesley Beary
 
Packer, where DevOps begins
Jeff Hung
 
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013
Carlos Sanchez
 
Play!ng with scala
Siarzh Miadzvedzeu
 
From Dev to DevOps - Codemotion ES 2012
Carlos Sanchez
 
Rails 3 (beta) Roundup
Wayne Carter
 
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
SV Ruby on Rails Meetup
 
Node.js - async for the rest of us.
Mike Brevoort
 
Puppetpreso
ke4qqq
 
Infrastructure as code with Puppet and Apache CloudStack
ke4qqq
 
Puppet and Apache CloudStack
Puppet
 
Puppet and CloudStack
ke4qqq
 
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
Stack kicker devopsdays-london-2013
Simon McCartney
 
Railsconf2011 deployment tips_for_slideshare
tomcopeland
 
AWS Lambda with Serverless Framework and Java
Manish Pandit
 
Igor Davydenko
SCRUMguides
 
Ad

Recently uploaded (20)

PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Digital Circuits, important subject in CS
contactparinay1
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 

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