SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
Introduction to CouchDB


              Jon Allen (JJ)
                           

  http://perl.jonallen.info - jj@jonallen.info
What is CouchDB?
  •  Document Oriented Database




Introduction to CouchDB	

                perl.jonallen.info
What is CouchDB?
  •  Document Oriented Database
       –  No schema
           •  Stores "documents" (i.e. data structures)
       –  No SQL
           •  Uses MapReduce queries written in JavaScript




Introduction to CouchDB	

                           perl.jonallen.info
What is CouchDB?
  •  Document Oriented Database
       –  No schema
           •  Stores "documents" (i.e. data structures)
       –  No SQL
           •  Uses "MapReduce" queries written in JavaScript


  •  Written in Erlang
  •  REST API
  •  Replication, scalability

Introduction to CouchDB	

                           perl.jonallen.info
Why use CouchDB?
                                    
  •    Store complex data structures (JSON)
  •    Store variable data structures (no schema)
  •    De-normalised / self contained
  •    Add attachments to documents
  •    Scalable and fault tolerant

  •  Better fit for certain problem domains
       –  Messaging
       –  CMS

Introduction to CouchDB	

                      perl.jonallen.info
Using CouchDB from Perl
                                      
  •  HTTP REST API
  •  No DBI, DBD, DBIx::Class etc

  •  CPAN modules
       –  CouchDB::Client
       –  AnyEvent::CouchDB




Introduction to CouchDB	

            perl.jonallen.info
Creating a database
                                       
      use CouchDB::Client;
      use Try::Tiny;

      my $client = CouchDB::Client->new(
          uri => 'http://localhost:5984'
      );

      my $db = $client->newDB('jj_test');   # lower case!

      try {
          $db->create;
      } catch {
          die "Could not create DB";
      };


Introduction to CouchDB	

                       perl.jonallen.info
Inserting a document
                                       
      my $client = CouchDB::Client->new();
      my $db     = $client->newDB('jj_test');

      my $doc    = $db->newDoc('docid', undef, {
          type => 'message',
          text => 'Hello, World',
          to   => ['JJ', 'Barbie', 'Brian'],
      });

      try {
          $doc->create;
      } catch {
          die "Could not create document";
      };


Introduction to CouchDB	

                         perl.jonallen.info
Inserting a document
                                       
      my $client = CouchDB::Client->new();
      my $db     = $client->newDB('jj_test');

      my $doc    = $db->newDoc('docid', undef, {
          type => 'message',
          text => 'Hello, World',
          to   => ['JJ', 'Barbie', 'Brian'],
      });

      try {                   Document ID,      Revision ID
          $doc->create;       must be unique
      } catch {
          die "Could not create document";
      };


Introduction to CouchDB	

                           perl.jonallen.info
CouchDB GUI
                                       




Introduction to CouchDB	

                 perl.jonallen.info
Querying documents
                                      

            All                             Map function
         Documents




                                             Key, Value
                                                      
        Key, Value
                 
                           Key, Value
                                                      
                             Query by Key
                                        
        Key, Value
                 
                                             Key, Value
                                                      

                                             Key, Value
                                                      



Introduction to CouchDB	

                      perl.jonallen.info
Views
                                  
  •  A view is a JavaScript function 
       –  Like a stored procedure in SQL
  •  Map function is executed on every document in the
     database
  •  Emits key/value pairs
       –  Can emit 0, 1, or more KV pairs for each document in the
          database
       –  Keys and values can be complex data structures
  •  KV pairs are then ordered and indexed by key


Introduction to CouchDB	

                            perl.jonallen.info
Queries
                                     
  •  Queries are run against views
       –  i.e. searches the "key" of the list of KV pairs
  •  Query types:
       –  Exact: key = x
       –  Range: key is between x and y
       –  Multiple: key is in list (x,y,z) 


  •  Reduce functions
       –  e.g. count, sum, group


Introduction to CouchDB	

                                   perl.jonallen.info
Designing a view
  •  Show messages for a specific user
      my $view = <<EOT;
          function(doc) {
              if (doc.type && doc.to && doc.text) {
                  if (doc.type == 'message') {
                      for (var dest in doc.to) {
                          emit(doc.to[dest], doc.text);
                      }
                  }
              }
          }
      EOT



Introduction to CouchDB	

                      perl.jonallen.info
Creating a view
      my $client = CouchDB::Client->new();
      my $db     = $client->newDB('jj_test');

      my $doc     = $db->newDesignDoc('_design/myview',undef,
      {
          views => {
              messages_to => { map => $view },
          },
      });

      try {
          $doc->create;
      } catch {
          die "Could not create document";
      };

Introduction to CouchDB	

                       perl.jonallen.info
Querying a view
   use Data::Dumper;
   my $client = CouchDB::Client->new();
   my $db     = $client->newDB('jj_test');

   my $view = $db->newDesignDoc('_design/myview')->retrieve;

   my $result = try {
       $view->queryView('messages_to', (key => 'JJ'));
   } catch {
       die "Could not query view";
   };

   say Dumper($result);



Introduction to CouchDB	

                      perl.jonallen.info
Query results
                                         
      varos:talk_scripts jj$ perl5.10.1 query_view.pl

      $VAR1 = {
                      'total_rows' => 3,
                      'rows' => [
                                   {
                                     'value' => 'Hello, World',
                                     'id' => 'docid',
                                     'key' => 'JJ'
                                   }
                                ],
                      'offset' => 2
                 };



Introduction to CouchDB	

                             perl.jonallen.info
Conclusion
                                      
  •  Different mindset to SQL database
  •  Quite low-level, but very powerful
  •  Additional features
       –  Replication
       –  Document revisions
       –  Reduce functions
       –  Changes API


  •  More information: http://books.couchdb.org/relax 

Introduction to CouchDB	

                   perl.jonallen.info
KTHKSBYE!


                 Thank you for listening!

                             Any questions?
                                          
                    http://perl.jonallen.info/talks 




Introduction to CouchDB	

                              perl.jonallen.info

Más contenido relacionado

La actualidad más candente

NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and How
BigBlueHat
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
chriskite
 

La actualidad más candente (20)

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
An Introduction To NoSQL & MongoDB
An Introduction To NoSQL & MongoDBAn Introduction To NoSQL & MongoDB
An Introduction To NoSQL & MongoDB
 
CouchDB
CouchDBCouchDB
CouchDB
 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
 
CouchDB
CouchDBCouchDB
CouchDB
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and How
 
OSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBOSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDB
 
Mongo db operations_v2
Mongo db operations_v2Mongo db operations_v2
Mongo db operations_v2
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
 
Apache CouchDB
Apache CouchDBApache CouchDB
Apache CouchDB
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
 
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
JS App Architecture
JS App ArchitectureJS App Architecture
JS App Architecture
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architecture
 
Top 10 frameworks of node js
Top 10 frameworks of node jsTop 10 frameworks of node js
Top 10 frameworks of node js
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
 
Mongodb - NoSql Database
Mongodb - NoSql DatabaseMongodb - NoSql Database
Mongodb - NoSql Database
 

Destacado

Promotions executive kpi
Promotions executive kpiPromotions executive kpi
Promotions executive kpi
furesdavit
 
Cis336 week 5 i lab 5
Cis336 week 5 i lab 5Cis336 week 5 i lab 5
Cis336 week 5 i lab 5
jackiechaner
 
II Guerra Mundial
II Guerra MundialII Guerra Mundial
II Guerra Mundial
agatagc
 
Tiger sec posting order
Tiger sec posting orderTiger sec posting order
Tiger sec posting order
dineshangirish
 
Przentacja o kwiatach
Przentacja o kwiatachPrzentacja o kwiatach
Przentacja o kwiatach
nela007
 

Destacado (20)

Socialtools
SocialtoolsSocialtools
Socialtools
 
9
99
9
 
Training: the (Not So) Secret Key to Repository Sustainability
Training: the (Not So) Secret Key to Repository SustainabilityTraining: the (Not So) Secret Key to Repository Sustainability
Training: the (Not So) Secret Key to Repository Sustainability
 
Ivan
IvanIvan
Ivan
 
Promotions executive kpi
Promotions executive kpiPromotions executive kpi
Promotions executive kpi
 
Dfsi Group1
Dfsi Group1Dfsi Group1
Dfsi Group1
 
Cis336 week 5 i lab 5
Cis336 week 5 i lab 5Cis336 week 5 i lab 5
Cis336 week 5 i lab 5
 
A Model for Activity Recognition in Pervasive Enviornment Inspired by Global ...
A Model for Activity Recognition in Pervasive Enviornment Inspired by Global ...A Model for Activity Recognition in Pervasive Enviornment Inspired by Global ...
A Model for Activity Recognition in Pervasive Enviornment Inspired by Global ...
 
II Guerra Mundial
II Guerra MundialII Guerra Mundial
II Guerra Mundial
 
Tiger sec posting order
Tiger sec posting orderTiger sec posting order
Tiger sec posting order
 
QUESTION 1
QUESTION 1QUESTION 1
QUESTION 1
 
Przentacja o kwiatach
Przentacja o kwiatachPrzentacja o kwiatach
Przentacja o kwiatach
 
ใบความรู้ กลุ่มทางเศรษฐกิจ+497+dltvsocp6+54soc p06 f26-1page
ใบความรู้  กลุ่มทางเศรษฐกิจ+497+dltvsocp6+54soc p06 f26-1pageใบความรู้  กลุ่มทางเศรษฐกิจ+497+dltvsocp6+54soc p06 f26-1page
ใบความรู้ กลุ่มทางเศรษฐกิจ+497+dltvsocp6+54soc p06 f26-1page
 
Everything Must Go exhibition opens for one weekend only
Everything Must Go exhibition opens for one weekend only Everything Must Go exhibition opens for one weekend only
Everything Must Go exhibition opens for one weekend only
 
School nr 5
School nr 5School nr 5
School nr 5
 
Biotalousstrategian työpaja: Toimenpideohjelma
Biotalousstrategian työpaja: ToimenpideohjelmaBiotalousstrategian työpaja: Toimenpideohjelma
Biotalousstrategian työpaja: Toimenpideohjelma
 
물뽕 3방울이면 박근혜도 미친년으로 된다.【카톡:SKP999 & DDF11.KR】물뽕 50mg정품파는곳,물뽕 50mg구입,물뽕 50mg팝니...
물뽕 3방울이면 박근혜도 미친년으로 된다.【카톡:SKP999 & DDF11.KR】물뽕 50mg정품파는곳,물뽕 50mg구입,물뽕 50mg팝니...물뽕 3방울이면 박근혜도 미친년으로 된다.【카톡:SKP999 & DDF11.KR】물뽕 50mg정품파는곳,물뽕 50mg구입,물뽕 50mg팝니...
물뽕 3방울이면 박근혜도 미친년으로 된다.【카톡:SKP999 & DDF11.KR】물뽕 50mg정품파는곳,물뽕 50mg구입,물뽕 50mg팝니...
 
What Customer Loyalty Means To Me!
What Customer Loyalty Means To Me!What Customer Loyalty Means To Me!
What Customer Loyalty Means To Me!
 
Foro de debate y argumentación gr
Foro de debate y argumentación grForo de debate y argumentación gr
Foro de debate y argumentación gr
 
The 3 Roots of Evil
The 3 Roots of Evil The 3 Roots of Evil
The 3 Roots of Evil
 

Similar a Introduction to couchdb

Introduction to couch_db
Introduction to couch_dbIntroduction to couch_db
Introduction to couch_db
Romain Testard
 
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache KafkaSolutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Guido Schmutz
 
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
confluent
 
Introduction to Riak and Ripple (KC.rb)
Introduction to Riak and Ripple (KC.rb)Introduction to Riak and Ripple (KC.rb)
Introduction to Riak and Ripple (KC.rb)
Sean Cribbs
 

Similar a Introduction to couchdb (20)

Introduction to CouchDB
Introduction to CouchDBIntroduction to CouchDB
Introduction to CouchDB
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
Introduction to couch_db
Introduction to couch_dbIntroduction to couch_db
Introduction to couch_db
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
Cooking 5 Star Infrastructure with Chef
Cooking 5 Star Infrastructure with ChefCooking 5 Star Infrastructure with Chef
Cooking 5 Star Infrastructure with Chef
 
Spring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_dataSpring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_data
 
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache KafkaSolutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
 
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
 
Solutions for bi-directional integration between Oracle RDBMS & Apache Kafka
Solutions for bi-directional integration between Oracle RDBMS & Apache KafkaSolutions for bi-directional integration between Oracle RDBMS & Apache Kafka
Solutions for bi-directional integration between Oracle RDBMS & Apache Kafka
 
Introduction to ArangoDB (nosql matters Barcelona 2012)
Introduction to ArangoDB (nosql matters Barcelona 2012)Introduction to ArangoDB (nosql matters Barcelona 2012)
Introduction to ArangoDB (nosql matters Barcelona 2012)
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
No sql Database
No sql DatabaseNo sql Database
No sql Database
 
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
 
Introduction to Riak and Ripple (KC.rb)
Introduction to Riak and Ripple (KC.rb)Introduction to Riak and Ripple (KC.rb)
Introduction to Riak and Ripple (KC.rb)
 
Introduction to RavenDB
Introduction to RavenDBIntroduction to RavenDB
Introduction to RavenDB
 
Mongodb my
Mongodb myMongodb my
Mongodb my
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
 
Hive jdbc
Hive jdbcHive jdbc
Hive jdbc
 

Más de iammutex

Realtime hadoopsigmod2011
Realtime hadoopsigmod2011Realtime hadoopsigmod2011
Realtime hadoopsigmod2011
iammutex
 

Más de iammutex (20)

Scaling Instagram
Scaling InstagramScaling Instagram
Scaling Instagram
 
Redis深入浅出
Redis深入浅出Redis深入浅出
Redis深入浅出
 
深入了解Redis
深入了解Redis深入了解Redis
深入了解Redis
 
NoSQL误用和常见陷阱分析
NoSQL误用和常见陷阱分析NoSQL误用和常见陷阱分析
NoSQL误用和常见陷阱分析
 
MongoDB 在盛大大数据量下的应用
MongoDB 在盛大大数据量下的应用MongoDB 在盛大大数据量下的应用
MongoDB 在盛大大数据量下的应用
 
8 minute MongoDB tutorial slide
8 minute MongoDB tutorial slide8 minute MongoDB tutorial slide
8 minute MongoDB tutorial slide
 
skip list
skip listskip list
skip list
 
Thoughts on Transaction and Consistency Models
Thoughts on Transaction and Consistency ModelsThoughts on Transaction and Consistency Models
Thoughts on Transaction and Consistency Models
 
Rethink db&tokudb调研测试报告
Rethink db&tokudb调研测试报告Rethink db&tokudb调研测试报告
Rethink db&tokudb调研测试报告
 
redis 适用场景与实现
redis 适用场景与实现redis 适用场景与实现
redis 适用场景与实现
 
What every data programmer needs to know about disks
What every data programmer needs to know about disksWhat every data programmer needs to know about disks
What every data programmer needs to know about disks
 
Ooredis
OoredisOoredis
Ooredis
 
Ooredis
OoredisOoredis
Ooredis
 
redis运维之道
redis运维之道redis运维之道
redis运维之道
 
Realtime hadoopsigmod2011
Realtime hadoopsigmod2011Realtime hadoopsigmod2011
Realtime hadoopsigmod2011
 
[译]No sql生态系统
[译]No sql生态系统[译]No sql生态系统
[译]No sql生态系统
 
Couchdb + Membase = Couchbase
Couchdb + Membase = CouchbaseCouchdb + Membase = Couchbase
Couchdb + Membase = Couchbase
 
Redis cluster
Redis clusterRedis cluster
Redis cluster
 
Redis cluster
Redis clusterRedis cluster
Redis cluster
 
Hadoop introduction berlin buzzwords 2011
Hadoop introduction   berlin buzzwords 2011Hadoop introduction   berlin buzzwords 2011
Hadoop introduction berlin buzzwords 2011
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Introduction to couchdb

  • 1. Introduction to CouchDB Jon Allen (JJ) http://perl.jonallen.info - jj@jonallen.info
  • 2. What is CouchDB? •  Document Oriented Database Introduction to CouchDB perl.jonallen.info
  • 3. What is CouchDB? •  Document Oriented Database –  No schema •  Stores "documents" (i.e. data structures) –  No SQL •  Uses MapReduce queries written in JavaScript Introduction to CouchDB perl.jonallen.info
  • 4. What is CouchDB? •  Document Oriented Database –  No schema •  Stores "documents" (i.e. data structures) –  No SQL •  Uses "MapReduce" queries written in JavaScript •  Written in Erlang •  REST API •  Replication, scalability Introduction to CouchDB perl.jonallen.info
  • 5. Why use CouchDB? •  Store complex data structures (JSON) •  Store variable data structures (no schema) •  De-normalised / self contained •  Add attachments to documents •  Scalable and fault tolerant •  Better fit for certain problem domains –  Messaging –  CMS Introduction to CouchDB perl.jonallen.info
  • 6. Using CouchDB from Perl •  HTTP REST API •  No DBI, DBD, DBIx::Class etc •  CPAN modules –  CouchDB::Client –  AnyEvent::CouchDB Introduction to CouchDB perl.jonallen.info
  • 7. Creating a database use CouchDB::Client; use Try::Tiny; my $client = CouchDB::Client->new( uri => 'http://localhost:5984' ); my $db = $client->newDB('jj_test'); # lower case! try { $db->create; } catch { die "Could not create DB"; }; Introduction to CouchDB perl.jonallen.info
  • 8. Inserting a document my $client = CouchDB::Client->new(); my $db = $client->newDB('jj_test'); my $doc = $db->newDoc('docid', undef, { type => 'message', text => 'Hello, World', to => ['JJ', 'Barbie', 'Brian'], }); try { $doc->create; } catch { die "Could not create document"; }; Introduction to CouchDB perl.jonallen.info
  • 9. Inserting a document my $client = CouchDB::Client->new(); my $db = $client->newDB('jj_test'); my $doc = $db->newDoc('docid', undef, { type => 'message', text => 'Hello, World', to => ['JJ', 'Barbie', 'Brian'], }); try { Document ID, Revision ID $doc->create; must be unique } catch { die "Could not create document"; }; Introduction to CouchDB perl.jonallen.info
  • 10. CouchDB GUI Introduction to CouchDB perl.jonallen.info
  • 11. Querying documents All Map function Documents Key, Value Key, Value Key, Value Query by Key Key, Value Key, Value Key, Value Introduction to CouchDB perl.jonallen.info
  • 12. Views •  A view is a JavaScript function –  Like a stored procedure in SQL •  Map function is executed on every document in the database •  Emits key/value pairs –  Can emit 0, 1, or more KV pairs for each document in the database –  Keys and values can be complex data structures •  KV pairs are then ordered and indexed by key Introduction to CouchDB perl.jonallen.info
  • 13. Queries •  Queries are run against views –  i.e. searches the "key" of the list of KV pairs •  Query types: –  Exact: key = x –  Range: key is between x and y –  Multiple: key is in list (x,y,z) •  Reduce functions –  e.g. count, sum, group Introduction to CouchDB perl.jonallen.info
  • 14. Designing a view •  Show messages for a specific user my $view = <<EOT; function(doc) { if (doc.type && doc.to && doc.text) { if (doc.type == 'message') { for (var dest in doc.to) { emit(doc.to[dest], doc.text); } } } } EOT Introduction to CouchDB perl.jonallen.info
  • 15. Creating a view my $client = CouchDB::Client->new(); my $db = $client->newDB('jj_test'); my $doc = $db->newDesignDoc('_design/myview',undef, { views => { messages_to => { map => $view }, }, }); try { $doc->create; } catch { die "Could not create document"; }; Introduction to CouchDB perl.jonallen.info
  • 16. Querying a view use Data::Dumper; my $client = CouchDB::Client->new(); my $db = $client->newDB('jj_test'); my $view = $db->newDesignDoc('_design/myview')->retrieve; my $result = try { $view->queryView('messages_to', (key => 'JJ')); } catch { die "Could not query view"; }; say Dumper($result); Introduction to CouchDB perl.jonallen.info
  • 17. Query results varos:talk_scripts jj$ perl5.10.1 query_view.pl $VAR1 = { 'total_rows' => 3, 'rows' => [ { 'value' => 'Hello, World', 'id' => 'docid', 'key' => 'JJ' } ], 'offset' => 2 }; Introduction to CouchDB perl.jonallen.info
  • 18. Conclusion •  Different mindset to SQL database •  Quite low-level, but very powerful •  Additional features –  Replication –  Document revisions –  Reduce functions –  Changes API •  More information: http://books.couchdb.org/relax Introduction to CouchDB perl.jonallen.info
  • 19. KTHKSBYE! Thank you for listening! Any questions? http://perl.jonallen.info/talks Introduction to CouchDB perl.jonallen.info