SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
Image: Cat vs The Internet, The Oatmeal http:// theoatmeal.com/




Tearing The Sofa Apart
CouchDB & CouchApp from a Beginner’s Perspective
It All Started When…

Pain point: Part III on CouchApps

 The example Sofa in the book !=
   the latest code over GitHub
      (#*@#^&^+ FAIL!!!)

(* To be fair, it’s still a great introductory book
    and the other sections are still relevant)
CouchDB in a Nutshell

Core philosophy:
Relax~

It’s a distributed
database

Data represented as        http://guide.couchdb.org/


documents – as flexible
as the paper counterpart
Awesome Distributed DB
     Features!

Replication

Conflict management

Load balancing

Clustering           http://guide.couchdb.org/
All You Need is HTTP


  It’s all HTTP REST-like API!

    No binaries needed! :D
Basic Operations in a
             Glance
Create a database
$ curl -X PUT http://localhost:5984/sofa



Double e: List all databases
$ curl -X GET http://localhost:5984/_all_dbs



Add a document
$ curl -X PUT http://localhost:5984/sofa/[id] -d
‘{“title”: “Hello world”, …}’

                                                   … etc.
Easier Admin: Futon
“OK, that’s neat…”


“… how am I gonna query stuff?”




                         http://www.flickr.com/photos/yiie/4865201576/
Sofa: Blogging Engine Use
          Cases
 Author can write posts and edit their posts

 Commenters can write comments

 Core pages

   Index page: Recent post listing

   Post page: Individual post with comments

   Two feeds: Recent post & recent comments
Design Document &
        Queries

Design documents is special!

  Special power: Can contain application
  code that CouchDB can run!

We can write and save MapReduce view in it

We’ll use the views to do queries later
A Simple Design Document


{
    “_id”: “_design/sofa”, // Determines the URL
    “language”: “javascript”,
    “views”: { … }, // Define your MapReduce views here
    “validate_doc_update”: “function(…) {}”
      // Validation function on document inserts/update
}
MapReduce for Dummies

Map: applies a function
to every single row and
emits key-value data

Reduce: (optional) Take
data spewed from map
and reduce it a
aggregated solution (e.g.
sum, count, standard
deviation)
                            © Nadir Muzaffar, hp://www.cs.berkeley.edu/~ballard/cs267.sp11/hw0/results/
                                                       htmls/Muzaffar.html
                                                   used without permission ^-^||
Example: Sofa Blog Post
           Structure

{
    “type”: “post”,
    “author”: “John Doe”,
    “created_at”: “2011-03-11T11:20:52.22”,
    “title”: “Blog Post Title”,
    “body”: “…”,
    “tags”: [“dummy”, “testing”, “webcamp”]
}
MapReduce Views in Sofa
Recent posts query
“recent-posts”: {
  “map”: “function(doc) {
     if (doc.type == 'post') {
       emit(new Date(doc.created_at), doc);
     }
  }”
}
MapReduce Views in Sofa
Post page query with comments
“post-page”: {
  “map”: “function(doc) {
    if (doc.type == 'post') {
       emit([doc._id], doc);
     } else if (doc.type == 'comment') {
       emit([doc.post_id, doc.created_at], doc);
     }
  }”
}




                 … will talk about how to filter an individual post later
MapReduce Views in Sofa
List and count tags
“tags”: {
  “map”: “function(doc) {
    if (doc.type == 'post' && doc.tags && doc.tags.length) {
      for (var idx in doc.tags) {
        if (doc.tags[idx]) {
          emit([doc.tags[idx].toLowerCase(), doc.created_at], doc);
        }
      }
    }
  }”,

    “reduce”: “_count” // CouchDB’s built-in reduce function
}
Querying Views
$ curl -X GET http://localhost:5984/sofa/_design/sofa/
_view/recent-posts


CouDB response
{
    “total_rows”: 4,
    “offset”: 0,
    “rows”: [ {“title”: “Hello world”, …}, … ]
}
Filtering Data
$ curl -X GET http://localhost:5984/sofa/_design/sofa/
_view/post-page?startkey=[“Huh”]&endkey=[“Huh”, {}]


CouDB response
{
    “total_rows”: 5,
    “offset”: 2,
    “rows”: [ {“title”: “Huh”, …} ]
}


Other query parameters
key, limit, descending, skip, group, reduce,
include_docs…
“Flexible data is cool, but
 I need some structure”
Documents are free-form in CouchDB,
flexibility == WIN!

Define validate_doc_update function if you
need validation, e.g.
                                                co de
  Check for mandatory fields,                  w tten :)
                                            ho go
                                          s
                                    to ’d for
  ACL control,                  A sk e I
                                 in cas
                                (
  Field format checking, etc.
Why stop here?

“OMG! I can write web apps on
CouchDB without frameworks!”




                       http://www.flickr.com/photos/7386864@N08/3802078924
CouchApp: The Easier Way


 Writing design documents is made easy by
 CouchApp

 Follow the file structure and CouchApp will
 make the design document for you
Design Document
               Structure
                                           Co
                                         pro rresp
{                                           jec ond
                                               td
  “_id”: “_design/sofa”,                          ire s to C
                                                     cto
  “language”: “javascript”,                              ry ouch
                                                           str Ap
                                                              uc
  “views”: { … },                                                tur p
                                                                    e
  “validate_doc_update”: “function(…) {}”,

    “show”: { … }, // Formats a single document
    “lists”: { … }, // Formats a list of documents

    “_attachment”: { … }, // CSS, JS, images attached here
    “templates”: { … }, // Templates stored here
    “vendor”: { … } // Libraries and scripts
}
Accessing Show and List
               Pages
        Show (single document)
        hp://localhost:5984/sofa/_design/sofa/_show/
        edit/[id]
            ID is optional; blank ID is good for pages to create new
            documents

        List (list of documents)
        hp://localhost:5984/sofa/_design/sofa/_list/
        index/[view-name]?[query-parameters]

(* I know the default URL’s ugly :( – fix this with URL rewrite module + virtual host seings)
Batteries Provided
Baeries (i.e. libraries) provided with
CouchApp projects:
  jquery.cou.app.js: To interact with CouchDB, query,
  insert, update…

  mustae.js: Template engine

  Evently: Writing interactive, event-based widgets
  without spaghei jery code

  Utilities: Atom feed generator, MD5 checksum, path
  builder, validation functions…
Quick Demo of the Sofa
        Code
                               Ask t
                             (in ca o show
                                   se I’d       code
                                          forgo
Add/Editing post                               tten :
                                                      )

Listing recent posts
  How to serve HTML and Atom feed?

Why showing an individual post is in “lists”
but not “show”?
Learning More
CouDB Wiki
hp://wiki.apache.org/couchdb/FrontPage

/usr/local/share/couchdb/server/main.js
(Seriously!)

CouDB: e Definite Guide
hp://guide.couchdb.org/index.html

CouDB HTTP API Reference
hp://docs.couchone.com/couchdb-api/
Contact Me! :)

Clone my annotated Sofa CouApp!
  hps://github.com/felixleong/sofa


          @felixleong

          hp://felixleong.com/

Más contenido relacionado

La actualidad más candente

jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 
6주 javaScript 시작하며
6주  javaScript 시작하며6주  javaScript 시작하며
6주 javaScript 시작하며지수 윤
 
NoSQL & MongoDB
NoSQL & MongoDBNoSQL & MongoDB
NoSQL & MongoDBShuai Liu
 
routes.rb をもう一度考えてみた #shibuyarb
routes.rb をもう一度考えてみた #shibuyarbroutes.rb をもう一度考えてみた #shibuyarb
routes.rb をもう一度考えてみた #shibuyarbToru Kawamura
 
Elasticsearch - SEARCH & ANALYZE DATA IN REAL TIME
Elasticsearch - SEARCH & ANALYZE DATA IN REAL TIMEElasticsearch - SEARCH & ANALYZE DATA IN REAL TIME
Elasticsearch - SEARCH & ANALYZE DATA IN REAL TIMEPiotr Pelczar
 
Chef on MongoDB and Pyramid
Chef on MongoDB and PyramidChef on MongoDB and Pyramid
Chef on MongoDB and PyramidRick Copeland
 
Understanding the ins and outs of word press metadata
Understanding the ins and outs of word press metadataUnderstanding the ins and outs of word press metadata
Understanding the ins and outs of word press metadataNicholas Batik
 
jQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and BlingjQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and BlingDoug Neiner
 
Advanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and MonitoringAdvanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and MonitoringBurt Beckwith
 
ELK Stack - Turn boring logfiles into sexy dashboard
ELK Stack - Turn boring logfiles into sexy dashboardELK Stack - Turn boring logfiles into sexy dashboard
ELK Stack - Turn boring logfiles into sexy dashboardGeorg Sorst
 
Feed Normalization with Ember Data 1.0
Feed Normalization with Ember Data 1.0Feed Normalization with Ember Data 1.0
Feed Normalization with Ember Data 1.0Jeremy Gillick
 
jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionPaul Irish
 
CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11virtualsciences41
 

La actualidad más candente (17)

jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
Rails vu d'un Javaiste
Rails vu d'un JavaisteRails vu d'un Javaiste
Rails vu d'un Javaiste
 
6주 javaScript 시작하며
6주  javaScript 시작하며6주  javaScript 시작하며
6주 javaScript 시작하며
 
NoSQL & MongoDB
NoSQL & MongoDBNoSQL & MongoDB
NoSQL & MongoDB
 
routes.rb をもう一度考えてみた #shibuyarb
routes.rb をもう一度考えてみた #shibuyarbroutes.rb をもう一度考えてみた #shibuyarb
routes.rb をもう一度考えてみた #shibuyarb
 
Elasticsearch - SEARCH & ANALYZE DATA IN REAL TIME
Elasticsearch - SEARCH & ANALYZE DATA IN REAL TIMEElasticsearch - SEARCH & ANALYZE DATA IN REAL TIME
Elasticsearch - SEARCH & ANALYZE DATA IN REAL TIME
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Chef on MongoDB and Pyramid
Chef on MongoDB and PyramidChef on MongoDB and Pyramid
Chef on MongoDB and Pyramid
 
Understanding the ins and outs of word press metadata
Understanding the ins and outs of word press metadataUnderstanding the ins and outs of word press metadata
Understanding the ins and outs of word press metadata
 
jQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and BlingjQuery: Nuts, Bolts and Bling
jQuery: Nuts, Bolts and Bling
 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
 
Advanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and MonitoringAdvanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and Monitoring
 
ELK Stack - Turn boring logfiles into sexy dashboard
ELK Stack - Turn boring logfiles into sexy dashboardELK Stack - Turn boring logfiles into sexy dashboard
ELK Stack - Turn boring logfiles into sexy dashboard
 
Feed Normalization with Ember Data 1.0
Feed Normalization with Ember Data 1.0Feed Normalization with Ember Data 1.0
Feed Normalization with Ember Data 1.0
 
jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
 
Jquery ui
Jquery uiJquery ui
Jquery ui
 
CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11CT presentatie JQuery 7.12.11
CT presentatie JQuery 7.12.11
 

Similar a Tearing the Sofa Apart: CouchDB and CouchApps from a Beginner's Perspective

CouchDB Open Source Bridge
CouchDB Open Source BridgeCouchDB Open Source Bridge
CouchDB Open Source BridgeChris Anderson
 
FOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDBFOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDBArangoDB Database
 
OSCON 2011 CouchApps
OSCON 2011 CouchAppsOSCON 2011 CouchApps
OSCON 2011 CouchAppsBradley Holt
 
CouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourCouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourPeter Friese
 
OSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBOSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBBradley Holt
 
Rapid Application Development with SwiftUI and Firebase
Rapid Application Development with SwiftUI and FirebaseRapid Application Development with SwiftUI and Firebase
Rapid Application Development with SwiftUI and FirebasePeter Friese
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and HowBigBlueHat
 
Intro to mobile web application development
Intro to mobile web application developmentIntro to mobile web application development
Intro to mobile web application developmentzonathen
 
Couchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problemCouchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problemdelagoya
 
Conexión de MongoDB con Hadoop - Luis Alberto Giménez - CAPSiDE #DevOSSAzureDays
Conexión de MongoDB con Hadoop - Luis Alberto Giménez - CAPSiDE #DevOSSAzureDaysConexión de MongoDB con Hadoop - Luis Alberto Giménez - CAPSiDE #DevOSSAzureDays
Conexión de MongoDB con Hadoop - Luis Alberto Giménez - CAPSiDE #DevOSSAzureDaysCAPSiDE
 
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDBBattle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDBJesse Wolgamott
 
Drupal Theme Development - DrupalCon Chicago 2011
Drupal Theme Development - DrupalCon Chicago 2011Drupal Theme Development - DrupalCon Chicago 2011
Drupal Theme Development - DrupalCon Chicago 2011Ryan Price
 
Everything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebEverything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebJames Rakich
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responsesdarrelmiller71
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformAntonio Peric-Mazar
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRick Copeland
 

Similar a Tearing the Sofa Apart: CouchDB and CouchApps from a Beginner's Perspective (20)

CouchDB Open Source Bridge
CouchDB Open Source BridgeCouchDB Open Source Bridge
CouchDB Open Source Bridge
 
FOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDBFOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDB
 
OSCON 2011 CouchApps
OSCON 2011 CouchAppsOSCON 2011 CouchApps
OSCON 2011 CouchApps
 
CouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 HourCouchDB Mobile - From Couch to 5K in 1 Hour
CouchDB Mobile - From Couch to 5K in 1 Hour
 
OSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBOSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDB
 
Why CouchDB
Why CouchDBWhy CouchDB
Why CouchDB
 
Play framework
Play frameworkPlay framework
Play framework
 
CouchDB
CouchDBCouchDB
CouchDB
 
Rapid Application Development with SwiftUI and Firebase
Rapid Application Development with SwiftUI and FirebaseRapid Application Development with SwiftUI and Firebase
Rapid Application Development with SwiftUI and Firebase
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and How
 
Intro to mobile web application development
Intro to mobile web application developmentIntro to mobile web application development
Intro to mobile web application development
 
Couchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problemCouchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problem
 
Conexión de MongoDB con Hadoop - Luis Alberto Giménez - CAPSiDE #DevOSSAzureDays
Conexión de MongoDB con Hadoop - Luis Alberto Giménez - CAPSiDE #DevOSSAzureDaysConexión de MongoDB con Hadoop - Luis Alberto Giménez - CAPSiDE #DevOSSAzureDays
Conexión de MongoDB con Hadoop - Luis Alberto Giménez - CAPSiDE #DevOSSAzureDays
 
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDBBattle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
 
Drupal Theme Development - DrupalCon Chicago 2011
Drupal Theme Development - DrupalCon Chicago 2011Drupal Theme Development - DrupalCon Chicago 2011
Drupal Theme Development - DrupalCon Chicago 2011
 
Everything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebEverything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the Web
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and Python
 

Último

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Tearing the Sofa Apart: CouchDB and CouchApps from a Beginner's Perspective

  • 1. Image: Cat vs The Internet, The Oatmeal http:// theoatmeal.com/ Tearing The Sofa Apart CouchDB & CouchApp from a Beginner’s Perspective
  • 2. It All Started When… Pain point: Part III on CouchApps The example Sofa in the book != the latest code over GitHub (#*@#^&^+ FAIL!!!) (* To be fair, it’s still a great introductory book and the other sections are still relevant)
  • 3. CouchDB in a Nutshell Core philosophy: Relax~ It’s a distributed database Data represented as http://guide.couchdb.org/ documents – as flexible as the paper counterpart
  • 4. Awesome Distributed DB Features! Replication Conflict management Load balancing Clustering http://guide.couchdb.org/
  • 5. All You Need is HTTP It’s all HTTP REST-like API! No binaries needed! :D
  • 6. Basic Operations in a Glance Create a database $ curl -X PUT http://localhost:5984/sofa Double e: List all databases $ curl -X GET http://localhost:5984/_all_dbs Add a document $ curl -X PUT http://localhost:5984/sofa/[id] -d ‘{“title”: “Hello world”, …}’ … etc.
  • 8. “OK, that’s neat…” “… how am I gonna query stuff?” http://www.flickr.com/photos/yiie/4865201576/
  • 9. Sofa: Blogging Engine Use Cases Author can write posts and edit their posts Commenters can write comments Core pages Index page: Recent post listing Post page: Individual post with comments Two feeds: Recent post & recent comments
  • 10. Design Document & Queries Design documents is special! Special power: Can contain application code that CouchDB can run! We can write and save MapReduce view in it We’ll use the views to do queries later
  • 11. A Simple Design Document { “_id”: “_design/sofa”, // Determines the URL “language”: “javascript”, “views”: { … }, // Define your MapReduce views here “validate_doc_update”: “function(…) {}” // Validation function on document inserts/update }
  • 12. MapReduce for Dummies Map: applies a function to every single row and emits key-value data Reduce: (optional) Take data spewed from map and reduce it a aggregated solution (e.g. sum, count, standard deviation) © Nadir Muzaffar, hp://www.cs.berkeley.edu/~ballard/cs267.sp11/hw0/results/ htmls/Muzaffar.html used without permission ^-^||
  • 13. Example: Sofa Blog Post Structure { “type”: “post”, “author”: “John Doe”, “created_at”: “2011-03-11T11:20:52.22”, “title”: “Blog Post Title”, “body”: “…”, “tags”: [“dummy”, “testing”, “webcamp”] }
  • 14. MapReduce Views in Sofa Recent posts query “recent-posts”: { “map”: “function(doc) { if (doc.type == 'post') { emit(new Date(doc.created_at), doc); } }” }
  • 15. MapReduce Views in Sofa Post page query with comments “post-page”: { “map”: “function(doc) { if (doc.type == 'post') { emit([doc._id], doc); } else if (doc.type == 'comment') { emit([doc.post_id, doc.created_at], doc); } }” } … will talk about how to filter an individual post later
  • 16. MapReduce Views in Sofa List and count tags “tags”: { “map”: “function(doc) { if (doc.type == 'post' && doc.tags && doc.tags.length) { for (var idx in doc.tags) { if (doc.tags[idx]) { emit([doc.tags[idx].toLowerCase(), doc.created_at], doc); } } } }”, “reduce”: “_count” // CouchDB’s built-in reduce function }
  • 17. Querying Views $ curl -X GET http://localhost:5984/sofa/_design/sofa/ _view/recent-posts CouDB response { “total_rows”: 4, “offset”: 0, “rows”: [ {“title”: “Hello world”, …}, … ] }
  • 18. Filtering Data $ curl -X GET http://localhost:5984/sofa/_design/sofa/ _view/post-page?startkey=[“Huh”]&endkey=[“Huh”, {}] CouDB response { “total_rows”: 5, “offset”: 2, “rows”: [ {“title”: “Huh”, …} ] } Other query parameters key, limit, descending, skip, group, reduce, include_docs…
  • 19. “Flexible data is cool, but I need some structure” Documents are free-form in CouchDB, flexibility == WIN! Define validate_doc_update function if you need validation, e.g. co de Check for mandatory fields, w tten :) ho go s to ’d for ACL control, A sk e I in cas ( Field format checking, etc.
  • 20. Why stop here? “OMG! I can write web apps on CouchDB without frameworks!” http://www.flickr.com/photos/7386864@N08/3802078924
  • 21. CouchApp: The Easier Way Writing design documents is made easy by CouchApp Follow the file structure and CouchApp will make the design document for you
  • 22. Design Document Structure Co pro rresp { jec ond td “_id”: “_design/sofa”, ire s to C cto “language”: “javascript”, ry ouch str Ap uc “views”: { … }, tur p e “validate_doc_update”: “function(…) {}”, “show”: { … }, // Formats a single document “lists”: { … }, // Formats a list of documents “_attachment”: { … }, // CSS, JS, images attached here “templates”: { … }, // Templates stored here “vendor”: { … } // Libraries and scripts }
  • 23. Accessing Show and List Pages Show (single document) hp://localhost:5984/sofa/_design/sofa/_show/ edit/[id] ID is optional; blank ID is good for pages to create new documents List (list of documents) hp://localhost:5984/sofa/_design/sofa/_list/ index/[view-name]?[query-parameters] (* I know the default URL’s ugly :( – fix this with URL rewrite module + virtual host seings)
  • 24. Batteries Provided Baeries (i.e. libraries) provided with CouchApp projects: jquery.cou.app.js: To interact with CouchDB, query, insert, update… mustae.js: Template engine Evently: Writing interactive, event-based widgets without spaghei jery code Utilities: Atom feed generator, MD5 checksum, path builder, validation functions…
  • 25. Quick Demo of the Sofa Code Ask t (in ca o show se I’d code forgo Add/Editing post tten : ) Listing recent posts How to serve HTML and Atom feed? Why showing an individual post is in “lists” but not “show”?
  • 26. Learning More CouDB Wiki hp://wiki.apache.org/couchdb/FrontPage /usr/local/share/couchdb/server/main.js (Seriously!) CouDB: e Definite Guide hp://guide.couchdb.org/index.html CouDB HTTP API Reference hp://docs.couchone.com/couchdb-api/
  • 27. Contact Me! :) Clone my annotated Sofa CouApp! hps://github.com/felixleong/sofa @felixleong hp://felixleong.com/

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n