domingo, 6 de mayo de 2018

Ejemplo de Apache Spark Sql

Para este ejemplo, cargaremos datos de clientes de un archivo de texto y crearemos un objeto DataFrame a partir del conjunto de datos. Entonces podemos ejecutar las funciones de DataFrame como consultas específicas para seleccionar los datos.

Veamos el archivo customers.txt.

100,John Smith, Austin, TX, 78727
200,Joe Johnson, Dallas, TX, 75201
300,Bob Jones, Houston, TX, 77028
400,Andy Davis, San Antonio, TX, 78227
500,James Williams, Austin, TX, 78727

El siguiente código muestra los comandos Spark SQL que podemos ejecutar en la consola del shell Spark.

// Create the SQLContext first from the existing Spark Context
val sqlContext = new org.apache.spark.sql.SQLContext(sc)

// Import statement to implicitly convert an RDD to a DataFrame
import sqlContext.implicits._

// Create a custom class to represent the Customer
case class Customer(customer_id: Int, name: String, city: String, state: String, zip_code: String)

// Create a DataFrame of Customer objects from the data set text file.
val dfCustomers = sc.textFile(“/home/emanuel/eje.csv”).map(_.split(“,”)).map(p => Customer(p(0).trim.toInt, p(1), p(2), p(3), p(4))).toDF()

// Register DataFrame as a table.
dfCustomers.registerTempTable(“customers”)

// Display the content of DataFrame
dfCustomers.show()

// Print the DF schema
dfCustomers.printSchema()

// Select customer name column
dfCustomers.select(“name”).show()

// Select customer name and city columns
dfCustomers.select(“name”, “city”).show()

// Select a customer by id
dfCustomers.filter(dfCustomers(“customer_id”).equalTo(500)).show()

// Count the customers by zip code
dfCustomers.groupBy(“zip_code”).count().show()

No hay comentarios.:

Publicar un comentario