SlideShare une entreprise Scribd logo
Spark Dataframe
Spark User Group
11 Juin 2015
Julien Buret
Formateur
Twitter
@JulienBuret
Spark
public class WordCount {



public static class TokenizerMapper

extends Mapper<Object, Text, Text, IntWritable>{



private final static IntWritable one = new IntWritable(1);

private Text word = new Text();



public void map(Object key, Text value, Context context

) throws IOException, InterruptedException {

StringTokenizer itr = new StringTokenizer(value.toString());

while (itr.hasMoreTokens()) {

word.set(itr.nextToken());

context.write(word, one);

}

}

}



public static class IntSumReducer

extends Reducer<Text,IntWritable,Text,IntWritable> {

private IntWritable result = new IntWritable();



public void reduce(Text key, Iterable<IntWritable> values,

Context context

) throws IOException, InterruptedException {

int sum = 0;

for (IntWritable val : values) {

sum += val.get();

}

result.set(sum);

context.write(key, result);

}

}

}
object WordCount {



def wc(in: String, out: String) = {

val conf = new SparkConf().setAppName("word_count")

val spark = new SparkContext(conf)

val textFile = spark.textFile(in)

val counts = textFile.flatMap(line => line.split(" "))

.map(word => (word, 1))

.reduceByKey(_ + _)

counts.saveAsTextFile(out)

}

}
3 fois moins de code
3 à 100 fois plus rapide
Spark RDD
def groupBy_avg(in: String) = {

val conf = new SparkConf().setAppName("groupby_avg")

val spark = new SparkContext(conf)

val csv = spark.textFile(in).map(_.split(","))

csv.map(rec => ((rec(0), (rec(1).toInt, 1))))

.reduceByKey((x, y) => (x._1 + y._1, x._2 + y._2))

.map(x => (x._1, x._2._1 / x._2._2))

.collect()

}
• Souvent les données sont
structurées (CSV, Json, ...)
• Les PairRDD nécessite de
manipuler des tuple ou des case
class
Date,Visitor_ID,Visit,...

2015_01_01,1123638584_657538536,1,...
2015_01_01,1123638584_657538536,2,...
2015_01_02,1123638584_657538536,1,...
...
SchemaRDD
def groupByAvgSSQL(in: String) = {

val conf = new SparkConf().setAppName("groupbyAvgDF")

val spark = new SparkContext(conf)

val sqlCtx = new SQLContext(spark)

val file = spark.textFile(in)

// Remove first line if necessary

val csv = file.map(l => Row.fromSeq(l.split(',')))

val csvWithSchema = sqlCtx.applySchema(csv, StructType(Seq(

StructField("name", StringType),

StructField("age", IntegerType))))

csvWithSchema.groupBy("name").avg("age").collect()

}
• Permet de manipuler des RDD de données
structuré (Spark 1.0)
• Expérimental
• API type SQL
• Peu de reader
Dataframe
• Collection de 'Rows' organisé avec un 'Schema'
• Abstraction et API inspiré de R, Pandas pour manipulé
des données structurés
Spark Dataframe
def groupByAvgDF(in: String) = {

val conf = new SparkConf().setAppName("groupbyAvgDF")

val spark = new SparkContext(conf)

val sqlCtx = new SQLContext(spark)

val csv = sqlCtx.load("com.databricks.spark.csv", Map("path" -> in))

csv.groupBy("name").avg("age").collect()

}
def groupByAvg(in: String) = {

val conf = new SparkConf().setAppName("groupbyAvg")

val spark = new SparkContext(conf)

val csv = spark.textFile(in).map(_.split(","))

csv.map(rec => ((rec(0), (rec(1).toInt, 1))))

.reduceByKey((x, y) => (x._1 + y._1, x._2 + y._2))

.map(x => (x._1, x._2._1 / x._2._2))

.collect()

}
Spark Dataframe
• Spark pour les data-analystes
• Spark est maintenant, presque, aussi simple à utiliser que
des librairies de type Pandas
• Performance des jobs quasi identique en Java, Scala,
Python, R
• Sauf pour les udf
Spark 1.3
SchemaRDD vers DataFrame
Nouveau reader pour les
données structurées
Adaptation de spark ML
Demo
Spark DataFrame from the
trench
• Utilisation quasi quotidienne en "prod" depuis 3 mois
• Majoritairement de l'exploration de données parquet
ou csv avec pyspark sur notebook
• Par des profils "non développeur"
Spark DataFrame from the
trench
• Complexité cachée par Catalyst
• OutOfMemory
• Nombres de partitions à tuner très fréquemment
• StackTrace incompréhensible pour le neophyte
• Peu de documentation
Autres features
• Partition discovery
• Schema merging
• JSON / JDBC
• Passage implicite de RDD vers Dataframe
Nice to have
• Faciliter la création de nouvelles expressions, les UDAF
• Déterminer le nombre de partitions automatiquement
• Faciliter la manipulation des dataframes (drop, ...)
• Catalyst encore plus intelligent
• Utilisation des statistiques
• CBO
Quelques références
• RDDs are the new bytecode of apache spark.
O.Girardot
• Introducing Dataframes in Spark for Large Scale Data
Science. Databrick
• Deep Dive into Spark SQL’s Catalyst Optimizer.
Databrick

Contenu connexe

PDF
Spark - Ippevent 19-02-2015
PDF
Spark - Alexis Seigneurin (Français)
PDF
Spark, ou comment traiter des données à la vitesse de l'éclair
PDF
Spark (v1.3) - Présentation (Français)
PDF
Introduction spark
PPTX
spark_intro_1208
PDF
Apache Flink par Bilal Baltagi Paris Spark Meetup Dec 2015
PDF
Spark SQL principes et fonctions
Spark - Ippevent 19-02-2015
Spark - Alexis Seigneurin (Français)
Spark, ou comment traiter des données à la vitesse de l'éclair
Spark (v1.3) - Présentation (Français)
Introduction spark
spark_intro_1208
Apache Flink par Bilal Baltagi Paris Spark Meetup Dec 2015
Spark SQL principes et fonctions

Tendances (20)

PPTX
Spark Streaming
PDF
Chapitre 3 spark
PPTX
Paris Spark meetup : Extension de Spark (Tachyon / Spark JobServer) par jlamiel
PDF
BigData_TP5 : Neo4J
PDF
Base de données graphe, Noe4j concepts et mise en oeuvre
PDF
De 20 000 à 4 millions d'utilisateurs : mode d'emploi
PDF
BigData_TP3 : Spark
PDF
BigData_TP4 : Cassandra
PDF
Spark RDD : Transformations & Actions
PDF
Paris stormusergroup intrudocution
PDF
Big Data, Hadoop & Spark
PDF
Tech day hadoop, Spark
PPTX
Déploiement ELK en conditions réelles
PDF
Chapitre 4 no sql
PDF
HADOOP + R
PDF
Hadoop et son écosystème - v2
PPTX
Une Introduction à R
PPTX
ElasticSearch : Architecture et Développement
PDF
Présentation de ElasticSearch / Digital apéro du 12/11/2014
PDF
Migrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshop
Spark Streaming
Chapitre 3 spark
Paris Spark meetup : Extension de Spark (Tachyon / Spark JobServer) par jlamiel
BigData_TP5 : Neo4J
Base de données graphe, Noe4j concepts et mise en oeuvre
De 20 000 à 4 millions d'utilisateurs : mode d'emploi
BigData_TP3 : Spark
BigData_TP4 : Cassandra
Spark RDD : Transformations & Actions
Paris stormusergroup intrudocution
Big Data, Hadoop & Spark
Tech day hadoop, Spark
Déploiement ELK en conditions réelles
Chapitre 4 no sql
HADOOP + R
Hadoop et son écosystème - v2
Une Introduction à R
ElasticSearch : Architecture et Développement
Présentation de ElasticSearch / Digital apéro du 12/11/2014
Migrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshop
Publicité

Plus de Modern Data Stack France (20)

PDF
Stash - Data FinOPS
PDF
Vue d'ensemble Dremio
PDF
From Data Warehouse to Lakehouse
PDF
Talend spark meetup 03042017 - Paris Spark Meetup
PDF
Paris Spark Meetup - Trifacta - 03_04_2017
PDF
Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...
PDF
HUG France Feb 2016 - Migration de données structurées entre Hadoop et RDBMS ...
PDF
Hadoop France meetup Feb2016 : recommendations with spark
PPTX
Hug janvier 2016 -EDF
PPTX
HUG France - 20160114 industrialisation_process_big_data CanalPlus
PDF
Hugfr SPARK & RIAK -20160114_hug_france
PDF
HUG France : HBase in Financial Industry par Pierre Bittner (Scaled Risk CTO)
PDF
Datalab 101 (Hadoop, Spark, ElasticSearch) par Jonathan Winandy - Paris Spark...
PDF
Record linkage, a real use case with spark ml - Paris Spark meetup Dec 2015
PDF
June Spark meetup : search as recommandation
PDF
Spark ML par Xebia (Spark Meetup du 11/06/2015)
PPTX
Spark meetup at viadeo
PPTX
Hadoop User Group 29Jan2015 Apache Flink / Haven / CapGemnini REX
PDF
The Cascading (big) data application framework
PPTX
Introduction sur Tez par Olivier RENAULT de HortonWorks Meetup du 25/11/2014
Stash - Data FinOPS
Vue d'ensemble Dremio
From Data Warehouse to Lakehouse
Talend spark meetup 03042017 - Paris Spark Meetup
Paris Spark Meetup - Trifacta - 03_04_2017
Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...
HUG France Feb 2016 - Migration de données structurées entre Hadoop et RDBMS ...
Hadoop France meetup Feb2016 : recommendations with spark
Hug janvier 2016 -EDF
HUG France - 20160114 industrialisation_process_big_data CanalPlus
Hugfr SPARK & RIAK -20160114_hug_france
HUG France : HBase in Financial Industry par Pierre Bittner (Scaled Risk CTO)
Datalab 101 (Hadoop, Spark, ElasticSearch) par Jonathan Winandy - Paris Spark...
Record linkage, a real use case with spark ml - Paris Spark meetup Dec 2015
June Spark meetup : search as recommandation
Spark ML par Xebia (Spark Meetup du 11/06/2015)
Spark meetup at viadeo
Hadoop User Group 29Jan2015 Apache Flink / Haven / CapGemnini REX
The Cascading (big) data application framework
Introduction sur Tez par Olivier RENAULT de HortonWorks Meetup du 25/11/2014
Publicité

Dernier (16)

PDF
Arouna Toure - Senior Ingénieur Logiciel Et Chef De Produit
PPTX
Logique séquentielle : les fondamentaux
PDF
TP de La Masse Volumique apparente et absolue
PDF
Expansion du Réseau de Gazoducs de Gaz Naturel au Brésil _ Analyse Technique ...
PDF
TP L’analyse granulométrique par tamisage
PPTX
CH1-RMELLOULI-Données des problèmes d'ordonnancement de la production.pptx
PDF
FAQ_FORAGE_EAU_SUNRISE_ENGINEERING_GROUP_SARL2025.pdf
PPTX
Lirrigation-et-le-drainage-en-agriculture-Principes-et-Pratiques.pptx
PPTX
COURS DE PROSPECTION MINIERE UTMSIRI - Copie.pptx
PPTX
Introduction aux Systèmes temps réel.pptx
PPTX
mon_expose_de_geophysique_disposotif_de_wener.pptx
PPTX
A Recurrent Neural Network (RNN)s a type of artificial neural network
PDF
Visite de chantier – Projet de Polyclinique à Laghouat
PDF
CHAPITRE 3 Typologie des réseaux [Enregistrement automatique] 4.pdf
PPTX
UMAPON Cours de traitement des minerais 2.pptx
PPTX
FormationFormation e pFormationour HC .pptx
Arouna Toure - Senior Ingénieur Logiciel Et Chef De Produit
Logique séquentielle : les fondamentaux
TP de La Masse Volumique apparente et absolue
Expansion du Réseau de Gazoducs de Gaz Naturel au Brésil _ Analyse Technique ...
TP L’analyse granulométrique par tamisage
CH1-RMELLOULI-Données des problèmes d'ordonnancement de la production.pptx
FAQ_FORAGE_EAU_SUNRISE_ENGINEERING_GROUP_SARL2025.pdf
Lirrigation-et-le-drainage-en-agriculture-Principes-et-Pratiques.pptx
COURS DE PROSPECTION MINIERE UTMSIRI - Copie.pptx
Introduction aux Systèmes temps réel.pptx
mon_expose_de_geophysique_disposotif_de_wener.pptx
A Recurrent Neural Network (RNN)s a type of artificial neural network
Visite de chantier – Projet de Polyclinique à Laghouat
CHAPITRE 3 Typologie des réseaux [Enregistrement automatique] 4.pdf
UMAPON Cours de traitement des minerais 2.pptx
FormationFormation e pFormationour HC .pptx

Spark dataframe

  • 1. Spark Dataframe Spark User Group 11 Juin 2015
  • 3. Spark public class WordCount {
 
 public static class TokenizerMapper
 extends Mapper<Object, Text, Text, IntWritable>{
 
 private final static IntWritable one = new IntWritable(1);
 private Text word = new Text();
 
 public void map(Object key, Text value, Context context
 ) throws IOException, InterruptedException {
 StringTokenizer itr = new StringTokenizer(value.toString());
 while (itr.hasMoreTokens()) {
 word.set(itr.nextToken());
 context.write(word, one);
 }
 }
 }
 
 public static class IntSumReducer
 extends Reducer<Text,IntWritable,Text,IntWritable> {
 private IntWritable result = new IntWritable();
 
 public void reduce(Text key, Iterable<IntWritable> values,
 Context context
 ) throws IOException, InterruptedException {
 int sum = 0;
 for (IntWritable val : values) {
 sum += val.get();
 }
 result.set(sum);
 context.write(key, result);
 }
 }
 } object WordCount {
 
 def wc(in: String, out: String) = {
 val conf = new SparkConf().setAppName("word_count")
 val spark = new SparkContext(conf)
 val textFile = spark.textFile(in)
 val counts = textFile.flatMap(line => line.split(" "))
 .map(word => (word, 1))
 .reduceByKey(_ + _)
 counts.saveAsTextFile(out)
 }
 } 3 fois moins de code 3 à 100 fois plus rapide
  • 4. Spark RDD def groupBy_avg(in: String) = {
 val conf = new SparkConf().setAppName("groupby_avg")
 val spark = new SparkContext(conf)
 val csv = spark.textFile(in).map(_.split(","))
 csv.map(rec => ((rec(0), (rec(1).toInt, 1))))
 .reduceByKey((x, y) => (x._1 + y._1, x._2 + y._2))
 .map(x => (x._1, x._2._1 / x._2._2))
 .collect()
 } • Souvent les données sont structurées (CSV, Json, ...) • Les PairRDD nécessite de manipuler des tuple ou des case class Date,Visitor_ID,Visit,...
 2015_01_01,1123638584_657538536,1,... 2015_01_01,1123638584_657538536,2,... 2015_01_02,1123638584_657538536,1,... ...
  • 5. SchemaRDD def groupByAvgSSQL(in: String) = {
 val conf = new SparkConf().setAppName("groupbyAvgDF")
 val spark = new SparkContext(conf)
 val sqlCtx = new SQLContext(spark)
 val file = spark.textFile(in)
 // Remove first line if necessary
 val csv = file.map(l => Row.fromSeq(l.split(',')))
 val csvWithSchema = sqlCtx.applySchema(csv, StructType(Seq(
 StructField("name", StringType),
 StructField("age", IntegerType))))
 csvWithSchema.groupBy("name").avg("age").collect()
 } • Permet de manipuler des RDD de données structuré (Spark 1.0) • Expérimental • API type SQL • Peu de reader
  • 6. Dataframe • Collection de 'Rows' organisé avec un 'Schema' • Abstraction et API inspiré de R, Pandas pour manipulé des données structurés
  • 7. Spark Dataframe def groupByAvgDF(in: String) = {
 val conf = new SparkConf().setAppName("groupbyAvgDF")
 val spark = new SparkContext(conf)
 val sqlCtx = new SQLContext(spark)
 val csv = sqlCtx.load("com.databricks.spark.csv", Map("path" -> in))
 csv.groupBy("name").avg("age").collect()
 } def groupByAvg(in: String) = {
 val conf = new SparkConf().setAppName("groupbyAvg")
 val spark = new SparkContext(conf)
 val csv = spark.textFile(in).map(_.split(","))
 csv.map(rec => ((rec(0), (rec(1).toInt, 1))))
 .reduceByKey((x, y) => (x._1 + y._1, x._2 + y._2))
 .map(x => (x._1, x._2._1 / x._2._2))
 .collect()
 }
  • 8. Spark Dataframe • Spark pour les data-analystes • Spark est maintenant, presque, aussi simple à utiliser que des librairies de type Pandas • Performance des jobs quasi identique en Java, Scala, Python, R • Sauf pour les udf
  • 9. Spark 1.3 SchemaRDD vers DataFrame Nouveau reader pour les données structurées Adaptation de spark ML
  • 10. Demo
  • 11. Spark DataFrame from the trench • Utilisation quasi quotidienne en "prod" depuis 3 mois • Majoritairement de l'exploration de données parquet ou csv avec pyspark sur notebook • Par des profils "non développeur"
  • 12. Spark DataFrame from the trench • Complexité cachée par Catalyst • OutOfMemory • Nombres de partitions à tuner très fréquemment • StackTrace incompréhensible pour le neophyte • Peu de documentation
  • 13. Autres features • Partition discovery • Schema merging • JSON / JDBC • Passage implicite de RDD vers Dataframe
  • 14. Nice to have • Faciliter la création de nouvelles expressions, les UDAF • Déterminer le nombre de partitions automatiquement • Faciliter la manipulation des dataframes (drop, ...) • Catalyst encore plus intelligent • Utilisation des statistiques • CBO
  • 15. Quelques références • RDDs are the new bytecode of apache spark. O.Girardot • Introducing Dataframes in Spark for Large Scale Data Science. Databrick • Deep Dive into Spark SQL’s Catalyst Optimizer. Databrick