Giter VIP home page Giter VIP logo

sparksql-protobuf's Introduction

sparksql-protobuf

This library provides utilities to work with Protobuf objects in SparkSQL. It provides a way to read parquet file written by SparkSQL back as an RDD of compatible protobuf object. It can also converts RDD of protobuf objects into DataFrame.

Build Status codecov.io

For sbt 0.13.6+

resolvers += Resolver.jcenterRepo

libraryDependencies ++= Seq(
    "com.github.saurfang" %% "sparksql-protobuf" % "0.1.3",
    "org.apache.parquet" % "parquet-protobuf" % "1.8.3"
)

Motivation

SparkSQL is very powerful and easy to use. However it has a few limitations and schema is only detected during runtime makes developers a lot less confident that they will get things right at first time. Static typing helps a lot! This is where protobuf comes in:

  1. Protobuf defines nested data structure easily
  2. It doesn't constraint you to the 22 fields limit in case class (no longer true once we upgrade to 2.11+)
  3. It is language agnostic and generates code that gives you native objects hence you get all the benefit of type checking and code completion unlike operating Row in Spark/SparkSQL

Features

Read Parquet file as RDD[Protobuf]

val personsPB = new ProtoParquetRDD(sc, "persons.parquet", classOf[Person])

where we need SparkContext, parquet path and protobuf class.

This converts the existing workflow:

  1. Ingest raw data as DataFrame with nested data structure
  2. Create awkward runtime type checking udfs
  3. Transform raw DataFrame using above udfs into a tabular DataFrame for data analytics

to

  1. Ingest raw data as DataFrame with nested data structure and persist as Parquet file
  2. Read Parquet file back as RDD[Protobuf]
  3. Perform any data transformation and extraction by working with compile typesafe Protobuf getters
  4. Create a DataFrame out of the above transformation and perform additional downstream data analytics on the tabular DataFrame

Infer SparkSQL Schema from Protobuf Definition

val personSchema = ProtoReflection.schemaFor[Person].dataType.asInstanceOf[StructType]

Convert RDD[Protobuf] to DataFrame

import com.github.saurfang.parquet.proto.spark.sql._
val personsDF = sqlContext.createDataFrame(protoPersons)

For more information, please see test cases.

Under the hood

  1. ProtoMessageConverter has been improved to read from LIST specification according to latest parquet documentation. This implementation should be backwards compatible and is able to read repeated fields generated by writers like SparkSQL.
  2. ProtoMessageParquetInputFormat helps the above process by correctly returning the built protobuf object as value.
  3. ProtoParquetRDD abstract the Hadoop input format and returns an RDD of your protobuf objects from parquet files directly.
  4. ProtoReflection infers SparkSQL schema from any Protobuf message class.
  5. ProtoRDDConversions converts Protobuf objects into SparkSQL rows.

Related Work

Elephant Bird

Spark-9999

sparksql-protobuf's People

Contributors

amailp avatar saurfang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sparksql-protobuf's Issues

Support for Protobuf DynamicMessages

Hi,
We tested sparksql-protobuf here, works pretty well,
but we need to generate the protobuf classes with Protoc .

We have created a feature to pull the latest proto descriptors version from S3 , so that we don't have to keep compiling and including new versions of the compiled ProtoBuf classes. The problem is that the com.google.protobuf.message doesn't contains the method getDescriptor(), it contains getDescriptorForType() instead.

is it possible to create a Support for Protobuf DynamicMessages like this parquet-proto issue ?
apache/parquet-mr#414

[Question] How to build the project properly?

Hi saurfang,

Awesome project. I am trying to build it locally. This is my very first time exposing to sbt build tool. I am trying to run sbt compile, but it failed due to not be able to to pick up protobuf and @transient.

~/internship/sparksql-protobuf on  master! ⌚ 9:06:21
$ protoc --version
libprotoc 2.6.1

$ tree -L 2 -d
.
├── lib .     // output of my compiled protobuf 2.6.1
│   ├── bin
│   ├── include
│   └── lib
├── project
│   ├── project
│   └── target
├── src
│   ├── main
│   └── test
└── target
    ├── protobuf_external
    ├── resolution-cache
    ├── scala-2.11
    └── streams

When I am trying to compile the project, sbt throws the following errors:

$ sbt compile -Xlint
[info] Loading global plugins from /Users/datng2/.sbt/0.13/plugins
[info] Loading project definition from /Users/datng2/internship/sparksql-protobuf/project
Missing bintray credentials /Users/datng2/.bintray/.credentials. Some bintray features depend on this.
[info] Set current project to sparksql-protobuf (in build file:/Users/datng2/internship/sparksql-protobuf/)
[warn] Credentials file /Users/datng2/.bintray/.credentials does not exist
[warn] Credentials file /Users/datng2/.ivy2/.sbtcredentials does not exist
[info] Compiling 5 Scala sources and 6 Java sources to /Users/datng2/internship/sparksql-protobuf/target/scala-2.11/classes...
[warn] /Users/datng2/internship/sparksql-protobuf/src/main/scala/com/github/saurfang/parquet/proto/spark/ProtoParquetRDD.scala:18: no valid targets for annotation on value conf - it is discarded unused. You may specify targets with meta-annotations, e.g. @(transient @param)
[warn]                                                         @transient conf: Configuration
[warn]                                                          ^
[warn] one warning found
[error] /Users/datng2/internship/sparksql-protobuf/src/test/generated/com/github/saurfang/parquet/proto/AddressBook.java:79: error: cannot find symbol
[error]     com.google.protobuf.ProtocolStringList
[error]                        ^
[error]   symbol:   class ProtocolStringList
[error]   location: package com.google.protobuf
[error] /Users/datng2/internship/sparksql-protobuf/src/test/generated/com/github/saurfang/parquet/proto/AddressBook.java:1367: error: cannot find symbol
[error]     public com.google.protobuf.ProtocolStringList
[error]                               ^
[error]   symbol:   class ProtocolStringList
[error]   location: package com.google.protobuf
[error] /Users/datng2/internship/sparksql-protobuf/src/test/generated/com/github/saurfang/parquet/proto/AddressBook.java:2247: error: cannot find symbol
[error]       public com.google.protobuf.ProtocolStringList
[error]                                 ^
[error]   symbol:   class ProtocolStringList
[error]   location: package com.google.protobuf
[error] /Users/datng2/internship/sparksql-protobuf/src/test/generated/com/github/saurfang/parquet/proto/AddressBook.java:219: error: cannot find symbol
[error]           address_ = address_.getUnmodifiableView();
[error]                              ^
[error]   symbol:   method getUnmodifiableView()
[error]   location: variable address_ of type LazyStringList
[error] /Users/datng2/internship/sparksql-protobuf/src/test/generated/com/github/saurfang/parquet/proto/AddressBook.java:1692: error: cannot find symbol
[error]           address_ = address_.getUnmodifiableView();
[error]                              ^
[error]   symbol:   method getUnmodifiableView()
[error]   location: variable address_ of type LazyStringList
[error] /Users/datng2/internship/sparksql-protobuf/src/test/generated/com/github/saurfang/parquet/proto/AddressBook.java:2249: error: cannot find symbol
[error]         return address_.getUnmodifiableView();
[error]                        ^
[error]   symbol:   method getUnmodifiableView()
[error]   location: variable address_ of type LazyStringList
[error] Note: /Users/datng2/internship/sparksql-protobuf/src/main/java/com/github/saurfang/parquet/proto/ProtoLISTReadSupport.java uses or overrides a deprecated API.
[error] Note: Recompile with -Xlint:deprecation for details.
[error] Note: Some input files use unchecked or unsafe operations.
[error] Note: Recompile with -Xlint:unchecked for details.
[error] 6 errors
[error] (compile:compile) javac returned nonzero exit code
[error] Total time: 6 s, completed Feb 8, 2019 9:14:21 AM

Any pointer or help would be greatly appreciated. Thanks :)

Protobuf 3

How can I help make sure this project can support proto3?

"Loose" Schema Mode

Hi, this is a great, useful library.

I tested this libraries compatibility with various 'schema evolution' scenarios where I changed the protobuf (added fields, renamed fields, changed optional->repeated, etc) pass it to the ProtoParquetWriter and try to read it back using ProtoParquetRDD. I found that many 'legal' protobuf evolution rules, like field renames or type changes were not compatible with this library.

Now, I don't want to conflate parquet's own schema evolution rules, or spark 'schema merging' capabilities (http://spark.apache.org/docs/latest/sql-programming-guide.html#schema-merging), but overall it seems technically feasible to have a 'loose' mode where fields that exist in parquet and which have a compatible protobuf type will hydrate the protobuf, regardless of any schema mismatches which makes the process fail hard and fast.

Any thoughts on this?

Examples:
Adding new Enum:
Caused by: org.apache.parquet.io.InvalidRecordException: Illegal enum value

Adding new field:
org.apache.parquet.schema.IncompatibleSchemaModificationException: Cant find "timeout" Scheme mismatch

how to query on SPARKSQL

Hi Team,

I am trying following SQL:-

var work__store_level_vend_pack_loc_final_data =

  sparksession.read.format("csv")
 .option("header", "true")
 .option("delimiter", "|")
 .option("inferSchema", "true")
 .load("C:\\Users\\jabin\\Desktop\\project_files\\work__store_level_vend_pack_loc_final_data.txt");
 
  work__store_level_vend_pack_loc_final_data.registerTempTable("work__store_level_vend_pack_loc_final_data_table");

var r1 = sparksession.sqlContext.sql( "SELECT shc_item_id ,'K' as source_owner_cd,item_purchase_status_cd, vendor_package_id,vendor_package_purchase_status_cd,flow_type_cd as vendor_package_flow_type_cd,vendor_carton_qty,vendor_stock_nbr,ksn_package_id,ksn_purchase_status_cd,import_ind,sears_divission_nbr,sears_item_nbr,sears_sku_nbr,scan_based_trading_ind,cross_merchandising_cd,retail_carton_vendor_package_id,vendor_package_owner_cd,can_carry_model_id,'' AS days_to_check_begin_day_qty,'' AS days_to_check_end_day_qty ,dotcom_allocation_ind ,retail_carton_internal_package_qty,allocation_replenishment_cd,shc_item_type_cd,idrp_order_method_cd,source_package_qty as store_source_package_qty,order_duns_nbr FROM work__store_level_vend_pack_loc_final_data_table WHERE flow_type_cd = 'JIT' OR servicing_dc_nbr > '0' ")
// .collect.foreach(println)

now i want to distinct all column of the r1 using sparksession.sqlContext.sql("")
how to do above thing?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.