SlideShare a Scribd company logo
Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India)
Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api
1
Apache Spark™ is a fast and general engine for large-scale data processing, and Couchbase is
in-memory no-sql database. So by connecting these two we can get a lightening fast speed.
In this blog we are focusing on how to make CRUD operations on couchbase
with Spark’s speed.
I am assuming that you have a basic Spark’s installation and couchbase installation on your
system.
So for using Couchbase API’s with RDD’s we need to make a build.sbt file and add this line to
it.
"com.couchbase.client" %% "spark-connector" % "1.1.0"
So basically your build.sbt should look like.
name := "spark-spray-couchbase-example1"
version := "1.0"
scalaVersion := "2.10.4"
organization := "com.MoonLightIT"
libraryDependencies ++= Seq(
"org.apache.spark" %% "spark-core" % "1.4.1",
"io.spray" %% "spray-can" % "1.3.3",
"io.spray" %% "spray-routing" % "1.3.3",
"org.apache.spark" %% "spark-sql" % "1.4.1",
"io.spray" %% "spray-testkit" % "1.3.3",
"org.specs2" %% "specs2" % "2.4.7",
"com.couchbase.client" %% "spark-connector" % "1.1.0"
)
assembleArtifact in packageScala := false // We don't need the Scala library,
Spark already includes it
Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India)
Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api
2
mergeStrategy in assembly := {
case m if m.toLowerCase.endsWith("manifest.mf") => MergeStrategy.discard
case m if m.toLowerCase.matches("meta-inf.*.sf$") => MergeStrategy.discard
case "reference.conf" => MergeStrategy.concat
case _ => MergeStrategy.first
}
fork in run := true
Now you can access the Couchbase’s API’s for RDD’s in your code.
So now the next part is making building a service and binding it to the port.
package com.MoonLightIT.sprayservices
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import spray.can.Http
import scala.concurrent.duration.DurationInt
object StartSpark extends App {
// we need an ActorSystem to host our application in
implicit val actorSystem = ActorSystem("spark-services")
implicit val timeout = 30 seconds
// create and start our service actor
val service = actorSystem.actorOf(Props[SparkServices], "spark-services")
// start a new HTTP server on port 8080 with our service actor as the handler
IO(Http) ! Http.Bind(service, "0.0.0.0", port = 8080)
}
Here we are just using the spray server for building the REST Api and binding it to
the 8080 port.
Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India)
Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api
3
Now comes the main part of implementing the couchbase CRUD operation using Spark and
spray. So for performing this we need to set the spark conf so that it may know where to insert
the data.
val sparkConf: SparkConf = new SparkConf().setAppName("couchbase-
spark-spray-starter-kit").setMaster("local")
.set("com.couchbase.nodes",
"127.0.0.1").set("com.couchbase.bucket.userBucket", "")
val sc: SparkContext = new SparkContext(sparkConf)
Here we are giving the node 127.0.0.1 and the bucket name here is userBucket. Using this
configuration we are making the Spark Context(sc).
Now we are going to implement the CRUD operations using the Couchbase’s API for RDD’s.
</pre>
<pre>package com.MoonLightIT.sprayservices
import java.util.UUID
import akka.actor.{Actor, ActorContext}
import com.couchbase.client.java.document.JsonDocument
import com.couchbase.client.java.document.json.JsonObject
import com.couchbase.client.java.query.N1qlQuery
import com.couchbase.client.java.view.ViewQuery
import com.couchbase.spark._
import org.apache.spark.{SparkConf, SparkContext}
import spray.http.StatusCodes._
import spray.http._
import spray.routing.Directive.pimpApply
import spray.routing.HttpService
import scala.util.Try
Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India)
Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api
4
trait SparkService extends HttpService {
val sparkConf: SparkConf = new SparkConf().setAppName("spark-spray-
starter").setMaster("local")
.set("com.couchbase.nodes",
"127.0.0.1").set("com.couchbase.bucket.userBucket", "")
val sc: SparkContext = new SparkContext(sparkConf)
val sparkRoutes =
path("insert" / "name" / Segment / "email" / Segment) { (name: String,
email: String) =>
get {
complete {
val documentId = "user::" + UUID.randomUUID().toString
val jsonObject = JsonObject.create().put("name", name).put("email",
email)
val jsonDocument = JsonDocument.create(documentId, jsonObject)
val savedData = sc.parallelize(Seq(jsonDocument))
val issaved =
Try(savedData.saveToCouchbase()).toOption.fold(false)(x => true)
issaved match {
case true => HttpResponse(OK, s"Data is successfully persisted
with id $documentId")
case false => HttpResponse(InternalServerError, s"Data is not
persisted and something went wrong")
}
}
}
} ~
path("updateViaKV" / "name" / Segment / "email" / Segment / "id" /
Segment) { (name: String, email: String, id: String) =>
get {
complete {
val documentId = id
val jsonObject = JsonObject.create().put("name",
name).put("email", email)
val jsonDocument = JsonDocument.create(documentId, jsonObject)
val savedData = sc.parallelize(Seq(jsonDocument))
val issaved =
Try(savedData.saveToCouchbase()).toOption.fold(false)(x => true)
issaved match {
Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India)
Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api
5
case true => HttpResponse(OK, s"Data is successfully persisted
with id $documentId")
case false => HttpResponse(InternalServerError, s"Data is not
persisted and something went wrong")
}
}
}
} ~
path("getViaKV" / "id" / Segment) { (id: String) =>
get {
complete {
val idAsRDD = sc.parallelize(Seq(id))
val fetchedDocument =
Try(idAsRDD.couchbaseGet[JsonDocument]().map(_.content.toString).collect).toO
ption
fetchedDocument match {
case Some(data) => HttpResponse(OK, data(0))
case None => HttpResponse(InternalServerError, s"Data is not
fetched and something went wrong")
}
}
}
} ~
Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India)
Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api
6
path("getViaView" / "name" / Segment) { (name: String) =>
get {
complete {
val viewRDDData = Try(sc.couchbaseView(ViewQuery.from("userDdoc",
"emailtoName").startKey(name)).collect()).toOption
val emailFetched = viewRDDData.map(_.map(a => a.value.toString))
emailFetched match {
case Some(data) => HttpResponse(OK, data(0))
case None => HttpResponse(InternalServerError, s"Data is not
fetched and something went wrong")
}
}
}
} ~
path("getViaN1Ql" / "name" / Segment) { (name: String) =>
get {
complete {
val n1qlRDD = Try(sc.couchbaseQuery(N1qlQuery.simple(s"SELECT *
FROM `userBucket` WHERE name LIKE '$name%'")).collect()).toOption
val emailFetched = n1qlRDD.map(_.map(a => a.value.toString))
emailFetched match {
case Some(data) => HttpResponse(OK, data(0))
case None => HttpResponse(InternalServerError, s"Data is not
fetched and something went wrong")
}
}
}
}
}
Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India)
Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api
7
class SparkServices extends Actor with SparkService {
def actorRefFactory: ActorContext = context
def receive: Actor.Receive = runRoute(sparkRoutes)
}</pre>
<pre>
The methods saveToCouchbase(), couchbaseGet(), couchbaseView(),couchbaseQuery() are
provided by couchbase so that we can perform the functionality on RDD’s .
This is a basic implementation of how to perform CRUD operation on couchbase using the
Spark.
We can also use the power of N1QL in this too by using the SQLContext, and they are said to be
highly compatible too.

More Related Content

ODP
An Overview of Node.js
PDF
Node.js and Parse
PDF
Building Android apps with Parse
PDF
Parse cloud code
PDF
Making connected apps with BaaS (Droidcon Bangalore 2014)
PPT
A Brief Introduce to WSGI
PPT
Parse Server Open Source
PDF
Firebase slide
An Overview of Node.js
Node.js and Parse
Building Android apps with Parse
Parse cloud code
Making connected apps with BaaS (Droidcon Bangalore 2014)
A Brief Introduce to WSGI
Parse Server Open Source
Firebase slide

What's hot (17)

PDF
Asynchronous web apps with the Play Framework 2.0
PDF
Using OpenStack With Fog
PPTX
Play + scala + reactive mongo
PPTX
06 integrate elasticsearch
PPTX
Meetup bangalore 9_novupdated
PPTX
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
PPTX
Drupal 8 + Elasticsearch + Docker
PPTX
05 integrate redis
PPTX
04 integrate entityframework
PDF
Azure Durable Functions (2018-06-13)
PPTX
10 performance and scalability secrets of ASP.NET websites
PPTX
SPSTC - PowerShell - Through the SharePoint Looking Glass
PPTX
03 integrate webapisignalr
PDF
Node.js vs Play Framework (with Japanese subtitles)
PDF
Tips and Tricks For Faster Asp.NET and MVC Applications
PPT
Intoduction to Play Framework
PPTX
Iac d.damyanov 4.pptx
Asynchronous web apps with the Play Framework 2.0
Using OpenStack With Fog
Play + scala + reactive mongo
06 integrate elasticsearch
Meetup bangalore 9_novupdated
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
Drupal 8 + Elasticsearch + Docker
05 integrate redis
04 integrate entityframework
Azure Durable Functions (2018-06-13)
10 performance and scalability secrets of ASP.NET websites
SPSTC - PowerShell - Through the SharePoint Looking Glass
03 integrate webapisignalr
Node.js vs Play Framework (with Japanese subtitles)
Tips and Tricks For Faster Asp.NET and MVC Applications
Intoduction to Play Framework
Iac d.damyanov 4.pptx
Ad

Similar to Apache spark with akka couchbase code by bhawani (20)

PDF
Spark and Couchbase: Augmenting the Operational Database with Spark
PDF
Spark Summit EU talk by Michael Nitschinger
PPTX
Spark and Couchbase– Augmenting the Operational Database with Spark
PPTX
Big Data Day LA 2016/ NoSQL track - Spark And Couchbase: Augmenting The Opera...
PPTX
Couchbase and Apache Spark
PDF
2014 09 30_sparkling_water_hands_on
PDF
SF Big Analytics 20191112: How to performance-tune Spark applications in larg...
PDF
Couchbase Chennai Meetup: Developing with Couchbase- made easy
PDF
Couchbase Singapore Meetup #2: Why Developing with Couchbase is easy !!
PDF
HBaseConAsia2018 Track2-6: Scaling 30TB's of data lake with Apache HBase and ...
PDF
HBaseConAsia 2018 - Scaling 30 TB's of Data lake with Apache HBase and Scala ...
PDF
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
PPTX
Big data presentationandoverview_of_couchbase
PPTX
Big Data with hadoop, Spark and BigQuery (Google cloud next Extended 2017 Kar...
PPTX
Intro to Apache Spark by CTO of Twingo
PDF
Spark Summit East 2015 Advanced Devops Student Slides
PPTX
Stream your Operational Data with Apache Spark & Kafka into Hadoop using Couc...
PDF
Apache Spark at Viadeo
PDF
IoT Applications and Patterns using Apache Spark & Apache Bahir
PPT
Hadoop presentation
Spark and Couchbase: Augmenting the Operational Database with Spark
Spark Summit EU talk by Michael Nitschinger
Spark and Couchbase– Augmenting the Operational Database with Spark
Big Data Day LA 2016/ NoSQL track - Spark And Couchbase: Augmenting The Opera...
Couchbase and Apache Spark
2014 09 30_sparkling_water_hands_on
SF Big Analytics 20191112: How to performance-tune Spark applications in larg...
Couchbase Chennai Meetup: Developing with Couchbase- made easy
Couchbase Singapore Meetup #2: Why Developing with Couchbase is easy !!
HBaseConAsia2018 Track2-6: Scaling 30TB's of data lake with Apache HBase and ...
HBaseConAsia 2018 - Scaling 30 TB's of Data lake with Apache HBase and Scala ...
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
Big data presentationandoverview_of_couchbase
Big Data with hadoop, Spark and BigQuery (Google cloud next Extended 2017 Kar...
Intro to Apache Spark by CTO of Twingo
Spark Summit East 2015 Advanced Devops Student Slides
Stream your Operational Data with Apache Spark & Kafka into Hadoop using Couc...
Apache Spark at Viadeo
IoT Applications and Patterns using Apache Spark & Apache Bahir
Hadoop presentation
Ad

More from Bhawani N Prasad (20)

PPTX
Understanding Robotic process automation by bhawani nandan prasad
PDF
Agile overview class for scrum masters
PPTX
Product Management
PPTX
Product Engineering
PDF
Machine learning computer science by bhawani n prasad
DOCX
PM conpetency skills
PDF
What we can do in Retail analytics by bhawani nandanprasad
PDF
Big data analytics bhawani nandan prasad
PDF
Program management-steps
PDF
Define enterprise integration strategy by industry leader bhawani nandanprasad
PDF
New IBM Information Server 11.3 - Bhawani Nandan Prasad
PDF
Economic growth inequality across globe by bhawani nandan prasad
PDF
Agile lifecycle handbook by bhawani nandan prasad
PDF
Agile project management tips and techniques
DOCX
Cognos 10 upgrade migrate fixpack by bhawani nandan prasad
PDF
Software development with scrum methodology bhawani nandan prasad
PDF
Agile formanagers by-bhawaninandanprasad
PDF
Dsdm by bhawani nandanprasad
PDF
Cmmi vs-agile
PDF
Pdu session challenges in agile
Understanding Robotic process automation by bhawani nandan prasad
Agile overview class for scrum masters
Product Management
Product Engineering
Machine learning computer science by bhawani n prasad
PM conpetency skills
What we can do in Retail analytics by bhawani nandanprasad
Big data analytics bhawani nandan prasad
Program management-steps
Define enterprise integration strategy by industry leader bhawani nandanprasad
New IBM Information Server 11.3 - Bhawani Nandan Prasad
Economic growth inequality across globe by bhawani nandan prasad
Agile lifecycle handbook by bhawani nandan prasad
Agile project management tips and techniques
Cognos 10 upgrade migrate fixpack by bhawani nandan prasad
Software development with scrum methodology bhawani nandan prasad
Agile formanagers by-bhawaninandanprasad
Dsdm by bhawani nandanprasad
Cmmi vs-agile
Pdu session challenges in agile

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Big Data Technologies - Introduction.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Diabetes mellitus diagnosis method based random forest with bat algorithm
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Machine learning based COVID-19 study performance prediction
Unlocking AI with Model Context Protocol (MCP)
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
cuic standard and advanced reporting.pdf
Encapsulation_ Review paper, used for researhc scholars
Big Data Technologies - Introduction.pptx
NewMind AI Weekly Chronicles - August'25 Week I
The AUB Centre for AI in Media Proposal.docx
Building Integrated photovoltaic BIPV_UPV.pdf
Review of recent advances in non-invasive hemoglobin estimation
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Spectroscopy.pptx food analysis technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
MIND Revenue Release Quarter 2 2025 Press Release
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...

Apache spark with akka couchbase code by bhawani

  • 1. Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India) Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api 1 Apache Spark™ is a fast and general engine for large-scale data processing, and Couchbase is in-memory no-sql database. So by connecting these two we can get a lightening fast speed. In this blog we are focusing on how to make CRUD operations on couchbase with Spark’s speed. I am assuming that you have a basic Spark’s installation and couchbase installation on your system. So for using Couchbase API’s with RDD’s we need to make a build.sbt file and add this line to it. "com.couchbase.client" %% "spark-connector" % "1.1.0" So basically your build.sbt should look like. name := "spark-spray-couchbase-example1" version := "1.0" scalaVersion := "2.10.4" organization := "com.MoonLightIT" libraryDependencies ++= Seq( "org.apache.spark" %% "spark-core" % "1.4.1", "io.spray" %% "spray-can" % "1.3.3", "io.spray" %% "spray-routing" % "1.3.3", "org.apache.spark" %% "spark-sql" % "1.4.1", "io.spray" %% "spray-testkit" % "1.3.3", "org.specs2" %% "specs2" % "2.4.7", "com.couchbase.client" %% "spark-connector" % "1.1.0" ) assembleArtifact in packageScala := false // We don't need the Scala library, Spark already includes it
  • 2. Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India) Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api 2 mergeStrategy in assembly := { case m if m.toLowerCase.endsWith("manifest.mf") => MergeStrategy.discard case m if m.toLowerCase.matches("meta-inf.*.sf$") => MergeStrategy.discard case "reference.conf" => MergeStrategy.concat case _ => MergeStrategy.first } fork in run := true Now you can access the Couchbase’s API’s for RDD’s in your code. So now the next part is making building a service and binding it to the port. package com.MoonLightIT.sprayservices import akka.actor.{ActorSystem, Props} import akka.io.IO import spray.can.Http import scala.concurrent.duration.DurationInt object StartSpark extends App { // we need an ActorSystem to host our application in implicit val actorSystem = ActorSystem("spark-services") implicit val timeout = 30 seconds // create and start our service actor val service = actorSystem.actorOf(Props[SparkServices], "spark-services") // start a new HTTP server on port 8080 with our service actor as the handler IO(Http) ! Http.Bind(service, "0.0.0.0", port = 8080) } Here we are just using the spray server for building the REST Api and binding it to the 8080 port.
  • 3. Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India) Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api 3 Now comes the main part of implementing the couchbase CRUD operation using Spark and spray. So for performing this we need to set the spark conf so that it may know where to insert the data. val sparkConf: SparkConf = new SparkConf().setAppName("couchbase- spark-spray-starter-kit").setMaster("local") .set("com.couchbase.nodes", "127.0.0.1").set("com.couchbase.bucket.userBucket", "") val sc: SparkContext = new SparkContext(sparkConf) Here we are giving the node 127.0.0.1 and the bucket name here is userBucket. Using this configuration we are making the Spark Context(sc). Now we are going to implement the CRUD operations using the Couchbase’s API for RDD’s. </pre> <pre>package com.MoonLightIT.sprayservices import java.util.UUID import akka.actor.{Actor, ActorContext} import com.couchbase.client.java.document.JsonDocument import com.couchbase.client.java.document.json.JsonObject import com.couchbase.client.java.query.N1qlQuery import com.couchbase.client.java.view.ViewQuery import com.couchbase.spark._ import org.apache.spark.{SparkConf, SparkContext} import spray.http.StatusCodes._ import spray.http._ import spray.routing.Directive.pimpApply import spray.routing.HttpService import scala.util.Try
  • 4. Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India) Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api 4 trait SparkService extends HttpService { val sparkConf: SparkConf = new SparkConf().setAppName("spark-spray- starter").setMaster("local") .set("com.couchbase.nodes", "127.0.0.1").set("com.couchbase.bucket.userBucket", "") val sc: SparkContext = new SparkContext(sparkConf) val sparkRoutes = path("insert" / "name" / Segment / "email" / Segment) { (name: String, email: String) => get { complete { val documentId = "user::" + UUID.randomUUID().toString val jsonObject = JsonObject.create().put("name", name).put("email", email) val jsonDocument = JsonDocument.create(documentId, jsonObject) val savedData = sc.parallelize(Seq(jsonDocument)) val issaved = Try(savedData.saveToCouchbase()).toOption.fold(false)(x => true) issaved match { case true => HttpResponse(OK, s"Data is successfully persisted with id $documentId") case false => HttpResponse(InternalServerError, s"Data is not persisted and something went wrong") } } } } ~ path("updateViaKV" / "name" / Segment / "email" / Segment / "id" / Segment) { (name: String, email: String, id: String) => get { complete { val documentId = id val jsonObject = JsonObject.create().put("name", name).put("email", email) val jsonDocument = JsonDocument.create(documentId, jsonObject) val savedData = sc.parallelize(Seq(jsonDocument)) val issaved = Try(savedData.saveToCouchbase()).toOption.fold(false)(x => true) issaved match {
  • 5. Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India) Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api 5 case true => HttpResponse(OK, s"Data is successfully persisted with id $documentId") case false => HttpResponse(InternalServerError, s"Data is not persisted and something went wrong") } } } } ~ path("getViaKV" / "id" / Segment) { (id: String) => get { complete { val idAsRDD = sc.parallelize(Seq(id)) val fetchedDocument = Try(idAsRDD.couchbaseGet[JsonDocument]().map(_.content.toString).collect).toO ption fetchedDocument match { case Some(data) => HttpResponse(OK, data(0)) case None => HttpResponse(InternalServerError, s"Data is not fetched and something went wrong") } } } } ~
  • 6. Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India) Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api 6 path("getViaView" / "name" / Segment) { (name: String) => get { complete { val viewRDDData = Try(sc.couchbaseView(ViewQuery.from("userDdoc", "emailtoName").startKey(name)).collect()).toOption val emailFetched = viewRDDData.map(_.map(a => a.value.toString)) emailFetched match { case Some(data) => HttpResponse(OK, data(0)) case None => HttpResponse(InternalServerError, s"Data is not fetched and something went wrong") } } } } ~ path("getViaN1Ql" / "name" / Segment) { (name: String) => get { complete { val n1qlRDD = Try(sc.couchbaseQuery(N1qlQuery.simple(s"SELECT * FROM `userBucket` WHERE name LIKE '$name%'")).collect()).toOption val emailFetched = n1qlRDD.map(_.map(a => a.value.toString)) emailFetched match { case Some(data) => HttpResponse(OK, data(0)) case None => HttpResponse(InternalServerError, s"Data is not fetched and something went wrong") } } } } }
  • 7. Bhawani Nandan Prasad – Bhawani_nandan@yahoo.com 0091 – 9717570222 (India) Hadoop Technology Stack SME - Using Spark , Spray and Couchbase for lightening fast REST Api 7 class SparkServices extends Actor with SparkService { def actorRefFactory: ActorContext = context def receive: Actor.Receive = runRoute(sparkRoutes) }</pre> <pre> The methods saveToCouchbase(), couchbaseGet(), couchbaseView(),couchbaseQuery() are provided by couchbase so that we can perform the functionality on RDD’s . This is a basic implementation of how to perform CRUD operation on couchbase using the Spark. We can also use the power of N1QL in this too by using the SQLContext, and they are said to be highly compatible too.