SlideShare a Scribd company logo
1 of 58
Couchbase
NoSQL document-oriented database
Basic Knowledge
Document is prepared by
A Little about NoSQL
• “non SQL“ "non relational" or “Not Only SQL“
• Data modeling in other than tabular relations (column family store, key-value
stores, documents, xml, graph ; No Schema)
• useful for very large sets of distributed data
• seeks to solve the scalability and big data performance issues that
relational databases weren’t designed to address
• Pros: Elastic scaling, Flexible data models
• Cons: Maturity, Support, Analytics and business intelligence,
Administration, Expertise
Trends
Some of
Couchbase
Customers
Couchbase History
• CouchDB, actively maintained and
enhanced as an Apache project
• Couchbase not entirely open-
source/free software.
• Editions: enterprise, community…
• Few more confusing names
Couchbase Mobile, Couchbase Lite,
CouchApps, BigCouch, Touchbase,
Membase, Memcached,
MemcacheDB
Couchbase Basic Concepts
• NoSQL document database
• no database schema, flexible data model
• Easy scalability
• Consistent high performance
• Always online/high availability
• supports broad set of web, mobile and IoT applications
• Powerful Query Language (N1QL)
• Simple Administration (web console)
Couchbase Server Architecture
• works on peer-to-peer node mechanism
• no single point of failure. When there is a failure of one node,
another node takes up its responsibility, thus providing high
availability.
Couchbase Data Flow
Terminology
• Node: A single Couchbase Server
• Cluster: a collection of nodes. Expand/Shrink. Cluster manager.
• Bucket: database (types: memcached and couchbase)
• Documents/Item/objects/key-value pair: as rows in the RDBMS table. Document id as PK. Metadata:
Rev/Expiration/flag
• vBucket: physical partitions of the bucket data. typically 1024.
• Replicas: redundant copies of data stored by buckets.-> again creates replica vBuckets
• Cluster map: mapping of which services belong to which nodes at a given point in time
• vBucket map: Cluster map contains a vBucket map.
• Replication: creating additional copies of active data on alternate nodes
• Rebalancing: As the number of nodes changes, the rebalance operation is used to redistribute the load.
• Failover: process that diverts traffic away from failing nodes
• Node Lifecycle: Add Node, Remove Node, Rebalance, and Failover cause state transitions
Installation & Setup
https://www.couchbase.com/nosql-databases/downloads
SDKs available at:
https://developer.couchbase.com/open-source-projects
Couchbase Node.js Client Library
Installation completed
services.msc
http://localhost:8091/
Using Couchbase
Querying data by
• SDK (node.js)
• command-line cbc tool (mainly used by MAC / Linux)
• Web console
Couchbase Web Console /Admin UI
http://localhost:8091/
Web Console
Pre-release in angular material different view
Configuring a server
Configuring a server
Configuring a server
Configuring a server
Note: Don’t give your mobile number you will end up getting lots of calls from Couchbase
Couchbase Web Console /Admin UI
Couchbase Web Console /Admin UI
Couchbase Web Console /Admin UI
Couchbase Web Console /Admin UI
buckets
Couchbase Web Console /Admin UI
documents
Documents in ‘travel-sample’
airline airport
Querying Data using
Console
• MapReduce views accessed via the View
API.
• Spatial views accessed via the Spatial View
API.
• N1QL queries
Querying Data from Application
One of following;
• key-value access data service
• Views API
• Using N1QL
Need Indexes
Views
Indexes are data-structure that provides quick and efficient means to query
Views use existing indexes as is.
• Global Secondary Index
• MapReduce views (Views)
• Spatial views
• Full Text Index (not yet released)
• Created using
JavaScript map and reduce functions
• data service is responsible to handle views
MapReduce views (Views) Every document passes through View Map() function
Map
f u n c t i o n ( d o c , m e t a ) {
e m i t ( d o c . i d , d o c . t i t l e ) ;
}
JSON doc JSON metadata
Create row Indexed key Output value(s)
[doc.iata, doc.name, doc.country]
Select id, name, title, city from usertable
Where id = 55
Creating a MapReduce View
MapReduce View
emit function generates a list of key-value pairs
map function: generates output data, which represents
a mapping of the documents stored within the bucket
Adding array of values
Adding Where clause
• Simply add &key="landmark_37519“ in last
Using a built-in Reduce Function
Count and Group by
Using a custom Reduce Function
• It is Group By in nature
• complex logic written in javascript to
strict the output of map function.
• Should be used very carefully.
• They are very tricky.
Adding filter from console
Using MapReduce Views in node.js
with viewQuery class
Using MapReduce Views in node.js
HTTP method URI path Description
GET /[bucket_name]/_design/[ddoc-name] Retrieves design documents.
PUT /[bucket_name]/_design/[ddoc-name] Creates a news design document with one
or more views.
DELETE /[bucket_name]/_design/[ddoc-name] Deletes design documents.
GET /[bucket_name]/_design/[ddoc-
name]/_view/[view-name]
Retrieves views.
POST /internalSettings Changes the number of simultaneous
requests each node can accept.
with Views REST APIView functions are stored in a design document as JSON.
Use REST API to manage your design documents.Views endpoints
Using N1QL
system catalog stores metadata about a database.
A declarative query language that extends SQL for JSON.
SELECT * FROM system:datastores;
SELECT 2+5 FROM system:dual;
Namespace
N1QL – Retrieve data
N1QL – Retrieve data
N1QL – Insert
Insert multiple records
INSERT INTO namespace:keyspace (KEY,
VALUE)
VALUES ( "1",
{ "value": "one" } ),
VALUES ( "2",
{ "value": "two" } ),
…,
VALUES ( "n",
{ "value": "n" } );
What an insert query can return?
default:`travel-sample` AS t
What Insert can return
Result keys Values description
requestID Request ID of the statement generated by the server.
signature Signature of the fields specified in the returning clause.
results If returning clause specified return
errors error codes and messages
status "successful" or "errors"
metrics elapsedTime elapsed time
executionTime Couchbase Server to execute time
resultCount May 0
resultSize Total number of results
mutationCount number of documents inserted
DML Operation error
Documents with same id cannot be created.
But by default there is no restriction on values.
N1QL – Update
UPDATE keyspace-ref
[use-keys-clause]
[set-clause]
[unset-clause]
[where-clause]
[limit-clause]
[returning-clause]
default:`travel-sample` AS t
[(namespace-name :)] keyspace [ [AS] alias]
‘document name’
country = “my country”
Sample Update
Updating one row Multiple rows
array of values
N1QL – Upsert
Insert or Update
UPSERT INTO keyspace-ref
[insert-values | insert-select]
[ returning-clause]
default:`travel-sample` AS t
[(namespace-name :)] keyspace [ [AS] alias]
Sample Upsert Query
Using N1QL in Node.JS
bucket.query(couchbase.N1qlQuery.fromSt
ring("SELECT name FROM ‘travel-sample’
WHERE type=‘airline'"));
Travel-sample data model
Airline
Airport
Route landmark
Id/key = primary key (airline_10) UUID()
Inbound/outbound refernces
Key ref
hotel Review, amenities, geo etc
hotel
Views
View to return all airline docs only.
function (doc, meta) {
emit(meta.id, doc.name);
}
• Create a development view and view the sample
view output.
• Refine and update your view definition to suit your
needs, repeating the process until your view is
complete. During this phase you can access your
view from your client library and application to
ensure it suits your needs.
• Once the view definition is complete, apply your view
to your entire cluster data set.
• Push your development view into production. This
moves the view from development into production,
and renames the index (so that the index does not
need to be rebuilt).
• Start using your production view.
View – select all doc not recommended
function (doc, meta) {
if(doc.type == "airline")
{
emit(meta.id, doc);
}
}
Views
Check nulls – best practice
function (doc, meta)
{
if (doc.type && doc.type == "airline" && doc.name)
{
emit(doc.name, [doc.name, doc.id, doc.country]);
}
}
View – using variable as output
var getSpecificRecords = function(doc,
meta){
//emit dunction.
} };
This can later be use in design doc as follows;
var designDoc =
{
"views":
{
"winGameSessions": getSpecificRecords .toString();
}
};
Views
Getting all the flights
function(doc, meta) {
if (doc.type === 'route') {
for (var i = 0; i < doc.schedule.length; i++) {
var schedule = doc.schedule[i];
var time = parseInt(schedule.utc.replace(/:/g, ''));
var key = [schedule.day, time];
var value = [
schedule.flight,
doc.sourceairport,
doc.destinationairport
];
emit(key, value);
}
}
}
L3a
Getting hotel reviews
Can be done by adding a where param in the url or wth view
function(doc, meta)
{
if (doc.type === 'hotel')
{
for (i=0; i < doc.reviews.length; i++)
{
emit(doc.reviews[i].author, [doc.reviews[i].date, doc.reviews[i].ratings] );
}
}
}
L3b
L3b
Getting hotel reviews add where
Can be done by adding a where param in the url or wth view
function(doc, meta)
{
if (doc.type === 'hotel')
{
for (i=0; i < doc.reviews.length; i++)
{
emit(doc.reviews[i].author, [doc.reviews[i].date, doc.reviews[i].ratings] );
}
}
}
Param value to be added based on the key given in emit function.
http://127.0.0.1:8092/travel-
sample/_design/dev_simpleVU/_view/L4?connection_timeout=60000&full_set=true&inclusive_end=true&key=%22Un
ited%20Kingdom%22&limit=9000&skip=90&stale=false
Keys=[“c1",“c2"]
Adding reduce function
L5
function (doc, meta) {
emit(meta.id, [9,7,8,5]);
}
function (keys, values, rereduce) {
if(!rereduce) {
return values.length;
} else {
var sum = 0;
for (i in values) {
sum += values[i];
}
return sum;
}
}
Date and time selections
function(doc, meta) {
emit([doc.year, doc.mon, doc.day, doc.logtype], null);
}
L6
View (joins)
• Pseudo joins
Will create a join with airline and airport type documents.
function (keys, values){ // ignoring reduce here to join only
var airport = “’ ;
//write your logic on keys and values here
return values.filter(function (e, i, arr) {
return arr.lastIndexOf(e) === i;
});
//return values;
}
function (doc, meta) {
if( doc.type == "airline")
{
emit(doc.id, doc.country);
}
else if(doc.type == "airport")
{
emit (doc.name, doc.country);
}
}

More Related Content

What's hot

Introduction to Apache Kafka
Introduction to Apache KafkaIntroduction to Apache Kafka
Introduction to Apache KafkaShiao-An Yuan
 
Common issues with Apache Kafka® Producer
Common issues with Apache Kafka® ProducerCommon issues with Apache Kafka® Producer
Common issues with Apache Kafka® Producerconfluent
 
Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011Milind Bhandarkar
 
Kubernetes: A Short Introduction (2019)
Kubernetes: A Short Introduction (2019)Kubernetes: A Short Introduction (2019)
Kubernetes: A Short Introduction (2019)Megan O'Keefe
 
Bringing Kafka Without Zookeeper Into Production with Colin McCabe | Kafka Su...
Bringing Kafka Without Zookeeper Into Production with Colin McCabe | Kafka Su...Bringing Kafka Without Zookeeper Into Production with Colin McCabe | Kafka Su...
Bringing Kafka Without Zookeeper Into Production with Colin McCabe | Kafka Su...HostedbyConfluent
 
Red Hat OpenShift Operators - Operators ABC
Red Hat OpenShift Operators - Operators ABCRed Hat OpenShift Operators - Operators ABC
Red Hat OpenShift Operators - Operators ABCRobert Bohne
 
Flink on Kubernetes operator
Flink on Kubernetes operatorFlink on Kubernetes operator
Flink on Kubernetes operatorEui Heo
 
Intelligent, Automatic Restarts for Unhealthy Kafka Consumers on Kubernetes w...
Intelligent, Automatic Restarts for Unhealthy Kafka Consumers on Kubernetes w...Intelligent, Automatic Restarts for Unhealthy Kafka Consumers on Kubernetes w...
Intelligent, Automatic Restarts for Unhealthy Kafka Consumers on Kubernetes w...HostedbyConfluent
 
Apache Kafka® Security Overview
Apache Kafka® Security OverviewApache Kafka® Security Overview
Apache Kafka® Security Overviewconfluent
 
Introduction to Kafka Cruise Control
Introduction to Kafka Cruise ControlIntroduction to Kafka Cruise Control
Introduction to Kafka Cruise ControlJiangjie Qin
 
Apache Kafka
Apache KafkaApache Kafka
Apache Kafkaemreakis
 
Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink Slim Baltagi
 
카프카, 산전수전 노하우
카프카, 산전수전 노하우카프카, 산전수전 노하우
카프카, 산전수전 노하우if kakao
 
Kafka Tutorial - introduction to the Kafka streaming platform
Kafka Tutorial - introduction to the Kafka streaming platformKafka Tutorial - introduction to the Kafka streaming platform
Kafka Tutorial - introduction to the Kafka streaming platformJean-Paul Azar
 
Kafka Tutorial - basics of the Kafka streaming platform
Kafka Tutorial - basics of the Kafka streaming platformKafka Tutorial - basics of the Kafka streaming platform
Kafka Tutorial - basics of the Kafka streaming platformJean-Paul Azar
 
A Deep Dive into Kafka Controller
A Deep Dive into Kafka ControllerA Deep Dive into Kafka Controller
A Deep Dive into Kafka Controllerconfluent
 
Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?confluent
 

What's hot (20)

Introduction to Apache Kafka
Introduction to Apache KafkaIntroduction to Apache Kafka
Introduction to Apache Kafka
 
Common issues with Apache Kafka® Producer
Common issues with Apache Kafka® ProducerCommon issues with Apache Kafka® Producer
Common issues with Apache Kafka® Producer
 
Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011
 
Kubernetes: A Short Introduction (2019)
Kubernetes: A Short Introduction (2019)Kubernetes: A Short Introduction (2019)
Kubernetes: A Short Introduction (2019)
 
Bringing Kafka Without Zookeeper Into Production with Colin McCabe | Kafka Su...
Bringing Kafka Without Zookeeper Into Production with Colin McCabe | Kafka Su...Bringing Kafka Without Zookeeper Into Production with Colin McCabe | Kafka Su...
Bringing Kafka Without Zookeeper Into Production with Colin McCabe | Kafka Su...
 
Red Hat OpenShift Operators - Operators ABC
Red Hat OpenShift Operators - Operators ABCRed Hat OpenShift Operators - Operators ABC
Red Hat OpenShift Operators - Operators ABC
 
Flink on Kubernetes operator
Flink on Kubernetes operatorFlink on Kubernetes operator
Flink on Kubernetes operator
 
Intelligent, Automatic Restarts for Unhealthy Kafka Consumers on Kubernetes w...
Intelligent, Automatic Restarts for Unhealthy Kafka Consumers on Kubernetes w...Intelligent, Automatic Restarts for Unhealthy Kafka Consumers on Kubernetes w...
Intelligent, Automatic Restarts for Unhealthy Kafka Consumers on Kubernetes w...
 
Apache Kafka® Security Overview
Apache Kafka® Security OverviewApache Kafka® Security Overview
Apache Kafka® Security Overview
 
Introduction to Kafka Cruise Control
Introduction to Kafka Cruise ControlIntroduction to Kafka Cruise Control
Introduction to Kafka Cruise Control
 
Apache Kafka
Apache KafkaApache Kafka
Apache Kafka
 
Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink Step-by-Step Introduction to Apache Flink
Step-by-Step Introduction to Apache Flink
 
카프카, 산전수전 노하우
카프카, 산전수전 노하우카프카, 산전수전 노하우
카프카, 산전수전 노하우
 
Kubernetes 101
Kubernetes 101Kubernetes 101
Kubernetes 101
 
Kafka Tutorial - introduction to the Kafka streaming platform
Kafka Tutorial - introduction to the Kafka streaming platformKafka Tutorial - introduction to the Kafka streaming platform
Kafka Tutorial - introduction to the Kafka streaming platform
 
Kafka Tutorial - basics of the Kafka streaming platform
Kafka Tutorial - basics of the Kafka streaming platformKafka Tutorial - basics of the Kafka streaming platform
Kafka Tutorial - basics of the Kafka streaming platform
 
A Deep Dive into Kafka Controller
A Deep Dive into Kafka ControllerA Deep Dive into Kafka Controller
A Deep Dive into Kafka Controller
 
Apache Kafka Best Practices
Apache Kafka Best PracticesApache Kafka Best Practices
Apache Kafka Best Practices
 
Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?Kafka Streams: What it is, and how to use it?
Kafka Streams: What it is, and how to use it?
 
Salesforce CLI
Salesforce CLISalesforce CLI
Salesforce CLI
 

Similar to Couchbas for dummies

Cnam azure ze cloud resource manager
Cnam azure ze cloud  resource managerCnam azure ze cloud  resource manager
Cnam azure ze cloud resource managerAymeric Weinbach
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffJAX London
 
KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!Guido Schmutz
 
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...Inhacking
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Аліна Шепшелей
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english versionSabino Labarile
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)Paul Chao
 
Apache Druid Auto Scale-out/in for Streaming Data Ingestion on Kubernetes
Apache Druid Auto Scale-out/in for Streaming Data Ingestion on KubernetesApache Druid Auto Scale-out/in for Streaming Data Ingestion on Kubernetes
Apache Druid Auto Scale-out/in for Streaming Data Ingestion on KubernetesDataWorks Summit
 
2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongo2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongoMichael Bright
 
Using MongoDB and Python
Using MongoDB and PythonUsing MongoDB and Python
Using MongoDB and PythonMike Bright
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSuzquiano
 
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UKIntroduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UKSkills Matter
 
Jump Start with Apache Spark 2.0 on Databricks
Jump Start with Apache Spark 2.0 on DatabricksJump Start with Apache Spark 2.0 on Databricks
Jump Start with Apache Spark 2.0 on DatabricksDatabricks
 
Webinar: The Anatomy of the Cloudant Data Layer
Webinar: The Anatomy of the Cloudant Data LayerWebinar: The Anatomy of the Cloudant Data Layer
Webinar: The Anatomy of the Cloudant Data LayerIBM Cloud Data Services
 
Serverless in-action
Serverless in-actionServerless in-action
Serverless in-actionAssaf Gannon
 

Similar to Couchbas for dummies (20)

Cnam azure ze cloud resource manager
Cnam azure ze cloud  resource managerCnam azure ze cloud  resource manager
Cnam azure ze cloud resource manager
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
Presentation
PresentationPresentation
Presentation
 
Linq
LinqLinq
Linq
 
KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!
 
Igor Davydenko
Igor DavydenkoIgor Davydenko
Igor Davydenko
 
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english version
 
Oracle OpenWorld 2014 Review Part Four - PaaS Middleware
Oracle OpenWorld 2014 Review Part Four - PaaS MiddlewareOracle OpenWorld 2014 Review Part Four - PaaS Middleware
Oracle OpenWorld 2014 Review Part Four - PaaS Middleware
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
 
Apache Druid Auto Scale-out/in for Streaming Data Ingestion on Kubernetes
Apache Druid Auto Scale-out/in for Streaming Data Ingestion on KubernetesApache Druid Auto Scale-out/in for Streaming Data Ingestion on Kubernetes
Apache Druid Auto Scale-out/in for Streaming Data Ingestion on Kubernetes
 
2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongo2016 feb-23 pyugre-py_mongo
2016 feb-23 pyugre-py_mongo
 
Using MongoDB and Python
Using MongoDB and PythonUsing MongoDB and Python
Using MongoDB and Python
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMS
 
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UKIntroduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
Introduction to Sqoop Aaron Kimball Cloudera Hadoop User Group UK
 
Jump Start with Apache Spark 2.0 on Databricks
Jump Start with Apache Spark 2.0 on DatabricksJump Start with Apache Spark 2.0 on Databricks
Jump Start with Apache Spark 2.0 on Databricks
 
Webinar: The Anatomy of the Cloudant Data Layer
Webinar: The Anatomy of the Cloudant Data LayerWebinar: The Anatomy of the Cloudant Data Layer
Webinar: The Anatomy of the Cloudant Data Layer
 
Serverless in-action
Serverless in-actionServerless in-action
Serverless in-action
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 

Couchbas for dummies

  • 1. Couchbase NoSQL document-oriented database Basic Knowledge Document is prepared by
  • 2. A Little about NoSQL • “non SQL“ "non relational" or “Not Only SQL“ • Data modeling in other than tabular relations (column family store, key-value stores, documents, xml, graph ; No Schema) • useful for very large sets of distributed data • seeks to solve the scalability and big data performance issues that relational databases weren’t designed to address • Pros: Elastic scaling, Flexible data models • Cons: Maturity, Support, Analytics and business intelligence, Administration, Expertise
  • 4. Couchbase History • CouchDB, actively maintained and enhanced as an Apache project • Couchbase not entirely open- source/free software. • Editions: enterprise, community… • Few more confusing names Couchbase Mobile, Couchbase Lite, CouchApps, BigCouch, Touchbase, Membase, Memcached, MemcacheDB
  • 5. Couchbase Basic Concepts • NoSQL document database • no database schema, flexible data model • Easy scalability • Consistent high performance • Always online/high availability • supports broad set of web, mobile and IoT applications • Powerful Query Language (N1QL) • Simple Administration (web console)
  • 6. Couchbase Server Architecture • works on peer-to-peer node mechanism • no single point of failure. When there is a failure of one node, another node takes up its responsibility, thus providing high availability.
  • 8. Terminology • Node: A single Couchbase Server • Cluster: a collection of nodes. Expand/Shrink. Cluster manager. • Bucket: database (types: memcached and couchbase) • Documents/Item/objects/key-value pair: as rows in the RDBMS table. Document id as PK. Metadata: Rev/Expiration/flag • vBucket: physical partitions of the bucket data. typically 1024. • Replicas: redundant copies of data stored by buckets.-> again creates replica vBuckets • Cluster map: mapping of which services belong to which nodes at a given point in time • vBucket map: Cluster map contains a vBucket map. • Replication: creating additional copies of active data on alternate nodes • Rebalancing: As the number of nodes changes, the rebalance operation is used to redistribute the load. • Failover: process that diverts traffic away from failing nodes • Node Lifecycle: Add Node, Remove Node, Rebalance, and Failover cause state transitions
  • 9. Installation & Setup https://www.couchbase.com/nosql-databases/downloads SDKs available at: https://developer.couchbase.com/open-source-projects Couchbase Node.js Client Library
  • 11. Using Couchbase Querying data by • SDK (node.js) • command-line cbc tool (mainly used by MAC / Linux) • Web console
  • 12. Couchbase Web Console /Admin UI http://localhost:8091/ Web Console Pre-release in angular material different view
  • 16. Configuring a server Note: Don’t give your mobile number you will end up getting lots of calls from Couchbase
  • 20. Couchbase Web Console /Admin UI buckets
  • 21. Couchbase Web Console /Admin UI documents
  • 23. Querying Data using Console • MapReduce views accessed via the View API. • Spatial views accessed via the Spatial View API. • N1QL queries
  • 24. Querying Data from Application One of following; • key-value access data service • Views API • Using N1QL Need Indexes
  • 25. Views Indexes are data-structure that provides quick and efficient means to query Views use existing indexes as is. • Global Secondary Index • MapReduce views (Views) • Spatial views • Full Text Index (not yet released) • Created using JavaScript map and reduce functions • data service is responsible to handle views
  • 26. MapReduce views (Views) Every document passes through View Map() function Map f u n c t i o n ( d o c , m e t a ) { e m i t ( d o c . i d , d o c . t i t l e ) ; } JSON doc JSON metadata Create row Indexed key Output value(s) [doc.iata, doc.name, doc.country] Select id, name, title, city from usertable Where id = 55
  • 27. Creating a MapReduce View MapReduce View emit function generates a list of key-value pairs map function: generates output data, which represents a mapping of the documents stored within the bucket
  • 28. Adding array of values
  • 29. Adding Where clause • Simply add &key="landmark_37519“ in last
  • 30. Using a built-in Reduce Function
  • 32. Using a custom Reduce Function • It is Group By in nature • complex logic written in javascript to strict the output of map function. • Should be used very carefully. • They are very tricky.
  • 34.
  • 35. Using MapReduce Views in node.js with viewQuery class
  • 36. Using MapReduce Views in node.js HTTP method URI path Description GET /[bucket_name]/_design/[ddoc-name] Retrieves design documents. PUT /[bucket_name]/_design/[ddoc-name] Creates a news design document with one or more views. DELETE /[bucket_name]/_design/[ddoc-name] Deletes design documents. GET /[bucket_name]/_design/[ddoc- name]/_view/[view-name] Retrieves views. POST /internalSettings Changes the number of simultaneous requests each node can accept. with Views REST APIView functions are stored in a design document as JSON. Use REST API to manage your design documents.Views endpoints
  • 37. Using N1QL system catalog stores metadata about a database. A declarative query language that extends SQL for JSON. SELECT * FROM system:datastores; SELECT 2+5 FROM system:dual; Namespace
  • 41. Insert multiple records INSERT INTO namespace:keyspace (KEY, VALUE) VALUES ( "1", { "value": "one" } ), VALUES ( "2", { "value": "two" } ), …, VALUES ( "n", { "value": "n" } ); What an insert query can return? default:`travel-sample` AS t
  • 42. What Insert can return Result keys Values description requestID Request ID of the statement generated by the server. signature Signature of the fields specified in the returning clause. results If returning clause specified return errors error codes and messages status "successful" or "errors" metrics elapsedTime elapsed time executionTime Couchbase Server to execute time resultCount May 0 resultSize Total number of results mutationCount number of documents inserted
  • 43. DML Operation error Documents with same id cannot be created. But by default there is no restriction on values.
  • 44. N1QL – Update UPDATE keyspace-ref [use-keys-clause] [set-clause] [unset-clause] [where-clause] [limit-clause] [returning-clause] default:`travel-sample` AS t [(namespace-name :)] keyspace [ [AS] alias] ‘document name’ country = “my country”
  • 45. Sample Update Updating one row Multiple rows array of values
  • 46. N1QL – Upsert Insert or Update UPSERT INTO keyspace-ref [insert-values | insert-select] [ returning-clause] default:`travel-sample` AS t [(namespace-name :)] keyspace [ [AS] alias]
  • 48. Using N1QL in Node.JS bucket.query(couchbase.N1qlQuery.fromSt ring("SELECT name FROM ‘travel-sample’ WHERE type=‘airline'"));
  • 49. Travel-sample data model Airline Airport Route landmark Id/key = primary key (airline_10) UUID() Inbound/outbound refernces Key ref hotel Review, amenities, geo etc
  • 50. hotel
  • 51. Views View to return all airline docs only. function (doc, meta) { emit(meta.id, doc.name); } • Create a development view and view the sample view output. • Refine and update your view definition to suit your needs, repeating the process until your view is complete. During this phase you can access your view from your client library and application to ensure it suits your needs. • Once the view definition is complete, apply your view to your entire cluster data set. • Push your development view into production. This moves the view from development into production, and renames the index (so that the index does not need to be rebuilt). • Start using your production view. View – select all doc not recommended function (doc, meta) { if(doc.type == "airline") { emit(meta.id, doc); } }
  • 52. Views Check nulls – best practice function (doc, meta) { if (doc.type && doc.type == "airline" && doc.name) { emit(doc.name, [doc.name, doc.id, doc.country]); } } View – using variable as output var getSpecificRecords = function(doc, meta){ //emit dunction. } }; This can later be use in design doc as follows; var designDoc = { "views": { "winGameSessions": getSpecificRecords .toString(); } };
  • 53. Views Getting all the flights function(doc, meta) { if (doc.type === 'route') { for (var i = 0; i < doc.schedule.length; i++) { var schedule = doc.schedule[i]; var time = parseInt(schedule.utc.replace(/:/g, '')); var key = [schedule.day, time]; var value = [ schedule.flight, doc.sourceairport, doc.destinationairport ]; emit(key, value); } } } L3a
  • 54. Getting hotel reviews Can be done by adding a where param in the url or wth view function(doc, meta) { if (doc.type === 'hotel') { for (i=0; i < doc.reviews.length; i++) { emit(doc.reviews[i].author, [doc.reviews[i].date, doc.reviews[i].ratings] ); } } } L3b
  • 55. L3b Getting hotel reviews add where Can be done by adding a where param in the url or wth view function(doc, meta) { if (doc.type === 'hotel') { for (i=0; i < doc.reviews.length; i++) { emit(doc.reviews[i].author, [doc.reviews[i].date, doc.reviews[i].ratings] ); } } } Param value to be added based on the key given in emit function. http://127.0.0.1:8092/travel- sample/_design/dev_simpleVU/_view/L4?connection_timeout=60000&full_set=true&inclusive_end=true&key=%22Un ited%20Kingdom%22&limit=9000&skip=90&stale=false Keys=[“c1",“c2"]
  • 56. Adding reduce function L5 function (doc, meta) { emit(meta.id, [9,7,8,5]); } function (keys, values, rereduce) { if(!rereduce) { return values.length; } else { var sum = 0; for (i in values) { sum += values[i]; } return sum; } }
  • 57. Date and time selections function(doc, meta) { emit([doc.year, doc.mon, doc.day, doc.logtype], null); } L6
  • 58. View (joins) • Pseudo joins Will create a join with airline and airport type documents. function (keys, values){ // ignoring reduce here to join only var airport = “’ ; //write your logic on keys and values here return values.filter(function (e, i, arr) { return arr.lastIndexOf(e) === i; }); //return values; } function (doc, meta) { if( doc.type == "airline") { emit(doc.id, doc.country); } else if(doc.type == "airport") { emit (doc.name, doc.country); } }