Monday 28 August 2017

Moving average hadoop


Contoh Hadoop: Hello World dengan Java, Pig, Hive, Flume, Fuse, Oozie, dan Sqoop dengan Informix, DB2, dan MySQL Ada banyak kegembiraan tentang Big Data dan banyak kebingungan untuk melakukannya. Artikel ini memberikan definisi kerja Big Data yang bekerja dan kemudian bekerja melalui serangkaian contoh sehingga Anda dapat memiliki pemahaman langsung tentang beberapa kemampuan Hadoop, teknologi open source terkemuka di domain Big Data. Secara khusus mari kita fokus pada pertanyaan berikut. Apa itu Big Data, Hadoop, Sqoop, Hive, dan Pig, dan mengapa ada begitu banyak kegembiraan di ruang ini Bagaimana Hadoop berhubungan dengan IBM DB2 dan Informix Dapatkah teknologi ini dimainkan bersama Bagaimana saya bisa memulai dengan Big Data Apa yang mudah Contoh yang berjalan di satu PC Untuk yang super tidak sabar, jika Anda sudah bisa menentukan Hadoop dan ingin mendapatkan hak untuk mengerjakan sampel kode, lakukan hal berikut. Jalankan instance Informix atau DB2 Anda. Download gambar VMWare dari Situs Cloudera dan tambahkan pengaturan RAM mesin virtual menjadi 1,5 GB. Langsung ke bagian yang berisi contoh kode. Ada contoh MySQL yang terpasang pada gambar VMWare. Jika Anda melakukan latihan tanpa konektivitas jaringan, gunakan contoh MySQL. Untuk orang lain, baca terus. Apa itu Big Data Big Data yang besar jumlahnya, ditangkap dengan kecepatan tinggi, dan terstruktur atau tidak terstruktur, atau beberapa kombinasi di atas. Faktor-faktor ini membuat Big Data sulit ditangkap, saya, dan dikelola dengan menggunakan metode tradisional. Ada begitu banyak hype di ruang ini sehingga bisa ada perdebatan panjang hanya tentang definisi data besar. Menggunakan teknologi Big Data tidak terbatas pada volume besar. Contoh dalam artikel ini menggunakan sampel kecil untuk menggambarkan kemampuan teknologi. Pada tahun 2012, kelompok yang besar berada di kisaran 100 Petabyte. Big Data bisa terstruktur dan tidak terstruktur. Database relasional tradisional, seperti Informix dan DB2, memberikan solusi yang telah terbukti untuk data terstruktur. Melalui perpanjangan mereka juga mengelola data tidak terstruktur. Teknologi Hadoop membawa teknik pemrograman baru dan lebih mudah diakses untuk mengerjakan penyimpanan data masif dengan data terstruktur dan tidak terstruktur. Mengapa semua kegembiraan Ada banyak faktor yang berkontribusi terhadap hype seputar Big Data, termasuk yang berikut. Membawa perhitungan dan penyimpanan bersama pada perangkat keras komoditas: Hasilnya berkobar dengan biaya rendah. Kinerja harga: Teknologi data Hadoop yang besar memberikan penghematan biaya yang signifikan (bayangkan faktor sekitar 10) dengan peningkatan kinerja yang signifikan (sekali lagi, faktor berpikir 10). Jarak tempuh Anda mungkin berbeda. Jika teknologi yang ada bisa begitu drastis kalah, perlu dipastikan apakah Hadoop dapat melengkapi atau mengganti aspek arsitektur Anda saat ini. Linear Scalability: Setiap teknologi paralel membuat klaim tentang peningkatan. Hadoop memiliki skalabilitas asli sejak rilis terbaru memperluas batas jumlah node menjadi 4.000. Akses penuh ke data tidak terstruktur: Penyimpanan data yang sangat terukur dengan model pemrograman paralel yang baik, MapReduce, telah menjadi tantangan bagi industri ini untuk beberapa lama. Model pemrograman Hadoops tidak menyelesaikan semua masalah, namun ini adalah solusi kuat untuk banyak tugas. Distribusi Hadoop: IBM dan Cloudera Salah satu titik kebingungannya adalah, Dimana saya mendapatkan perangkat lunak untuk mengerjakan Big Data Contoh dalam artikel ini didasarkan pada distribusi Cloudera gratis dari Hadoop yang disebut CDH (untuk distribusi Cloudera termasuk Hadoop). Ini tersedia sebagai gambar VMWare dari situs web Cloudera. IBM baru-baru ini mengumumkan bahwa porting platform data besar untuk dijalankan di CDH. Istilah teknologi yang mengganggu sangat sering digunakan, namun dalam kasus ini mungkin tepat. Apa itu Hadoop Berikut adalah beberapa definisi dari Hadoop, masing-masing menargetkan audiens yang berbeda dalam perusahaan: Bagi para eksekutif: Hadoop adalah proyek perangkat lunak open source Apache untuk mendapatkan nilai dari volumevelocityvariety data yang luar biasa tentang organisasi Anda. Gunakan data alih-alih membuang sebagian besar dari itu. Bagi para manajer teknis: Perangkat lunak open source yang menambang BigData terstruktur dan tidak terstruktur tentang perusahaan Anda. Ini terintegrasi dengan ekosistem Business Intelligence yang ada. Legal: Perangkat lunak open source yang dikemas dan didukung oleh beberapa pemasok. Teknik: Sebuah paralel besar-besaran, tidak berbagi apa-apa, peta berbasis Java - mengurangi lingkungan eksekusi. Pikirkan ratusan sampai ribuan komputer yang mengerjakan masalah yang sama, dengan ketahanan kegagalan built-in. Proyek di ekosistem Hadoop menyediakan pemuatan data, bahasa tingkat tinggi, penyebaran awan otomatis, dan kemampuan lainnya. Keamanan: Perangkat lunak yang dijamin Kerberos. Apa saja komponen Hadoop Proyek Apache Hadoop memiliki dua komponen inti, yaitu file store bernama Hadoop Distributed File System (HDFS), dan framework pemrograman yang disebut MapReduce. Ada sejumlah proyek pendukung yang memanfaatkan HDFS dan MapReduce. Artikel ini akan memberikan ringkasan, dan mendorong Anda untuk mendapatkan buku Hadoop The Definitive Guide, 3rd Edition yang orisinal, untuk lebih jelasnya. Definisi di bawah ini dimaksudkan untuk memberikan latar belakang yang cukup bagi Anda untuk menggunakan contoh kode berikut. Artikel ini benar-benar dimaksudkan untuk Anda mulai dengan pengalaman langsung dengan teknologi. Ini adalah artikel bagaimana-untuk lebih dari artikel apa-apa atau mari-membahas. HDFS Jika Anda ingin 4000 komputer bekerja pada data Anda, maka Anda akan menyebarkan data Anda dengan lebih baik di 4000 komputer. HDFS melakukan ini untuk Anda. HDFS memiliki beberapa bagian yang bergerak. Datanodes menyimpan data Anda, dan Namenode melacak dari mana barang disimpan. Ada potongan lain, tapi Anda punya cukup banyak untuk memulai. MapReduce. Ini adalah model pemrograman untuk Hadoop. Ada dua fase, tidak mengherankan disebut Map and Reduce. Untuk mengesankan teman Anda mengatakan bahwa mereka ada semacam shuffle antara fase Map and Reduce. JobTracker mengelola 4000 komponen pekerjaan MapReduce Anda. TaskTracker menerima perintah dari JobTracker. Jika Anda menyukai Java maka kode di Jawa. Jika Anda menyukai SQL atau bahasa non-Jawa lainnya, Anda masih beruntung, Anda bisa menggunakan utilitas bernama Hadoop Streaming. Hadoop Streaming Sebuah utilitas untuk mengaktifkan kode MapReduce dalam bahasa apa pun: C, Perl, Python, C, Bash, dll. Contohnya termasuk pemeta Python dan peredam AWK. Hive dan Hue. Jika Anda menyukai SQL, Anda akan senang mendengar bahwa Anda dapat menulis SQL dan membiarkan Hive mengubahnya menjadi pekerjaan MapReduce. Tidak, Anda tidak mendapatkan lingkungan ANSI-SQL penuh, tapi Anda mendapatkan 4.000 catatan dan skalabilitas multi-Petabyte. Hue memberi Anda antarmuka grafis berbasis browser untuk melakukan pekerjaan sarang Anda. Babi . Lingkungan pemrograman tingkat tinggi melakukan pengkodean MapReduce. Bahasa babi disebut Pig Latin. Anda mungkin menemukan konvensi penamaan agak tidak konvensional, namun Anda mendapatkan kinerja harga dan ketersediaan yang luar biasa. Sqoop. Menyediakan transfer data bi-directional antara Hadoop dan database relasional favorit Anda. Oozie. Mengelola alur kerja Hadoop. Ini tidak menggantikan penjadwal atau tooler BPM Anda, tapi ini memberi percabangan dan kontrol apakah-kemudian-lain dalam pekerjaan Hadoop Anda. HBase. Toko nilai kunci super-scalable. Ini bekerja sangat mirip dengan peta hash yang terus-menerus (karena para penggemar python menganggap kamus). Ini bukan database relasional meski ada nama HBase. FlumeNG. Pemuat real time untuk mengalirkan data ke Hadoop. Ini menyimpan data di HDFS dan HBase. Anda ingin memulai dengan FlumeNG, yang meningkatkan flume asli. Whirr. Penyediaan awan untuk Hadoop. Anda bisa memulai sebuah cluster hanya dalam beberapa menit dengan file konfigurasi yang sangat singkat. Mahout. Mesin belajar untuk Hadoop. Digunakan untuk analisis prediktif dan analisis lanjutan lainnya. Sekering Membuat sistem HDFS terlihat seperti sistem file biasa sehingga Anda bisa menggunakan ls, rm, cd, dan lainnya pada data HDFS Zookeeper. Digunakan untuk mengatur sinkronisasi cluster. Anda tidak akan banyak bekerja dengan Zookeeper, tapi ini bekerja keras untuk Anda. Jika Anda pikir Anda perlu menulis sebuah program yang menggunakan Zookeeper, Anda sangat pintar dan sangat pintar dan bisa menjadi panitia proyek Apache, atau Anda akan mengalami hari yang sangat buruk. Gambar 1 menunjukkan potongan kunci dari Hadoop. Gambar 1. Arsitektur Hadoop HDFS, lapisan bawah, berada pada sekelompok perangkat keras komoditas. Server rack-mounted sederhana, masing-masing memiliki CPU inti 2-Hex, disk 6 sampai 12, dan 32 gig ram. Untuk mengurangi pekerjaan peta, lapisan mapper membaca dari disk pada kecepatan sangat tinggi. Pemeta memancarkan pasangan nilai kunci yang disortir dan dipresentasikan ke peredam, dan lapisan peredam merangkum pasangan nilai kunci. Tidak, Anda tidak perlu meringkas, Anda sebenarnya bisa memiliki pekerjaan pemetaan peta yang hanya memiliki pemotong. Ini harus menjadi lebih mudah untuk memahami ketika Anda sampai ke contoh python-awk. Bagaimana Hadoop mengintegrasikan dengan infrastruktur Informix atau DB2 saya, Hadoop terintegrasi dengan sangat baik dengan database Informix dan DB2 Anda dengan Sqoop. Sqoop adalah implementasi open-source terdepan untuk memindahkan data antara database Hadoop dan relasional. Menggunakan JDBC untuk membaca dan menulis Informix, DB2, MySQL, Oracle, dan sumber lainnya. Ada adapter yang dioptimalkan untuk beberapa database, termasuk Netezza dan DB2. Persiapan: Bagaimana cara menjalankan contoh sederhana Hadoop, Hive, Pig, Oozie, dan Sqoop Anda selesai dengan perkenalan dan definisi, sekarang saatnya untuk hal yang baik. Untuk melanjutkan, Anda perlu mendownload VMWare, virtual box, atau gambar lainnya dari Situs Web Cloudera dan mulai melakukan MapReduce Gambar virtual mengasumsikan Anda memiliki komputer 64bit dan salah satu lingkungan virtualisasi yang populer. Sebagian besar lingkungan virtualisasi memiliki download gratis. Saat Anda mencoba booting gambar virtual 64bit Anda mungkin mendapatkan keluhan tentang pengaturan BIOS. Gambar 2 menunjukkan perubahan yang dibutuhkan pada BIOS, dalam hal ini pada Thinkpad8482. Hati-hati saat melakukan perubahan. Beberapa paket keamanan perusahaan akan memerlukan passcode setelah perubahan BIOS sebelum sistem akan di-reboot. Gambar 2. Pengaturan BIOS untuk tamu virtual 64bit Data besar yang digunakan di sini sebenarnya agak kecil. Intinya bukan membuat laptop Anda terbakar karena menggiling file besar, tapi untuk menunjukkan sumber data yang menarik, dan memetakan mengurangi pekerjaan yang menjawab pertanyaan yang berarti. Download gambar virtual Hadoop Sangat disarankan agar Anda menggunakan gambar Cloudera untuk menjalankan contoh-contoh ini. Hadoop adalah teknologi yang memecahkan masalah. Kemasan gambar Cloudera memungkinkan Anda untuk berfokus pada pertanyaan data besar. Tapi jika Anda memutuskan untuk merakit semua komponen sendiri, Hadoop telah menjadi masalah, bukan solusinya. Download gambar Gambar CDH4, penawaran terbaru tersedia di sini: Gambar CDH4. Versi Sebelumnya, CDH3, tersedia di sini: gambar CDH3. Anda memiliki pilihan teknologi virtualisasi. Anda bisa mendownload lingkungan virtualisasi gratis dari VMWare dan lainnya. Misalnya, pergi ke vmware dan mendownload vmware-player. Laptop Anda mungkin menjalankan Windows sehingga Anda bisa mendownload vmware-player untuk windows. Contoh dalam artikel ini akan menggunakan VMWare untuk contoh ini, dan menjalankan Ubuntu Linux menggunakan tar dan bukan winzip atau yang setara. Setelah didownload, untarunzip sebagai berikut: tar - zxvf cloudera-demo-vm-cdh4.0.0-vmware. tar. gz. Atau, jika Anda menggunakan CDH3, gunakan berikut ini: tar - zxvf cloudera-demo-vm-cdh3u4-vmware. tar. gz Unzip biasanya bekerja pada file tar. Setelah membuka ritsleting, Anda bisa menyalakan gambar sebagai berikut: vmplayer cloudera-demo-vm. vmx. Anda sekarang memiliki layar yang terlihat seperti apa yang ditunjukkan pada Gambar 3. Gambar 3. Citra virtual Cloudera Perintah vmplayer menyeleksi benar dan menghidupkan mesin virtual. Jika Anda menggunakan CDH3, Anda perlu mematikan mesin dan mengubah pengaturan memori. Gunakan ikon tombol daya di sebelah jam di bagian tengah bawah layar untuk mematikan mesin virtual. Anda kemudian memiliki akses edit ke pengaturan mesin virtual. Untuk CDH3 langkah selanjutnya adalah super-charge virtual image dengan lebih banyak RAM. Sebagian besar pengaturan hanya bisa diubah dengan mesin virtual dimatikan. Gambar 4 menunjukkan bagaimana cara mengakses setting dan meningkatkan RAM yang dialokasikan ke lebih dari 2GB. Gambar 4. Menambahkan RAM ke mesin virtual Seperti ditunjukkan pada Gambar 5, Anda dapat mengubah pengaturan jaringan menjadi dijembatani. Dengan pengaturan ini mesin virtual akan mendapatkan alamat IP-nya sendiri. Jika ini menciptakan masalah pada jaringan Anda, Anda dapat menggunakan Network Address Translation (NAT) secara opsional. Anda akan menggunakan jaringan untuk terhubung ke database. Gambar 5. Mengubah pengaturan jaringan untuk dijembatani Anda dibatasi oleh RAM pada sistem host, jadi jangan mencoba mengalokasikan RAM lebih banyak daripada yang ada pada komputer Anda. Jika Anda melakukannya, komputer akan berjalan sangat lambat. Sekarang, untuk saat ini Anda telah menunggu, maju dan menyalakan mesin virtual. Cloudera pengguna secara otomatis login saat startup. Jika Anda membutuhkannya, password Cloudera adalah: cloudera. Instal Informix dan DB2 Anda memerlukan database untuk bekerja dengan. Jika Anda belum memiliki database, Anda dapat mendownload edisi Pengembang Informix di sini, atau Edisi DB2 Express-C gratis. Alternatif lain untuk menginstal DB2 adalah mendownload gambar VMWare yang telah menginstal DB2 pada sistem operasi SuSE Linux. Login sebagai root, dengan password: password. Beralih ke db2inst1 userid. Bekerja sebagai root ibarat mengendarai mobil tanpa sabuk pengaman. Silakan berbicara dengan DBA ramah setempat Anda tentang mendapatkan database berjalan. Artikel ini tidak akan membahasnya di sini. Jangan mencoba menginstall database di dalam gambar virtual Cloudera karena tidak ada cukup ruang disk kosong. Mesin virtual akan terhubung ke database menggunakan Sqoop yang membutuhkan driver JDBC. Anda harus memiliki driver JDBC untuk database Anda di virtual image. Anda bisa memasang driver Informix disini. Driver Informix JDBC (ingat, hanya driver di dalam gambar virtual, bukan database) instal ditunjukkan pada Listing 1. Daftar 1. Pemasangan driver Informix JDBC Catatan: Pilih subdirektori relatif ke homecloudera agar tidak memerlukan izin root untuk instalasi. Driver DB2 JDBC ada dalam format zip, jadi cukup unzip di direktori tujuan, seperti yang ditunjukkan pada Listing 2. Listing 2. Driver JDBC DB2 menginstal Pengantar singkat tentang HDFS dan MapReduce Sebelum Anda mulai memindahkan data antara database relasional dan Hadoop Anda, Anda memerlukan pengenalan singkat tentang HDFS dan MapReduce. Ada banyak tutorial hello world style untuk Hadoop, jadi contoh di sini dimaksudkan untuk memberi cukup banyak latar belakang agar latihan database masuk akal bagi Anda. HDFS menyediakan penyimpanan di seluruh node dalam cluster Anda. Langkah pertama dalam menggunakan Hadoop adalah memasukkan data ke dalam HDFS. Kode yang ditunjukkan pada Listing 3 mendapat salinan buku oleh Mark Twain dan sebuah buku oleh James Fenimore Cooper dan menyalin teks-teks ini ke dalam HDFS. Kode 3. Load Mark Twain dan James Fenimore Cooper ke HDFS Anda sekarang memiliki dua file dalam sebuah direktori di HDFS. Tolong isi kegembiraan anda. Serius, pada satu simpul dan hanya sekitar 1 megabyte, ini sama serunya dengan menonton cat yang kering. Tapi jika ini adalah cluster 400 node dan Anda memiliki 5 petabyte live, maka Anda benar-benar akan mengalami masalah yang mengandung kegembiraan Anda. Banyak tutorial Hadoop menggunakan contoh kata yang disertakan dalam contoh jar file. Ternyata banyak analisis melibatkan penghitungan dan penggabungan. Contoh pada Listing 4 menunjukkan bagaimana cara memanggil penghitung kata. Listing 4. Menghitung kata-kata Twain dan Cooper Sufiks. gz pada DS. txt. gz memberitahu Hadoop untuk menghadapi dekompresi sebagai bagian dari pemrosesan Peta-Mengurangi. Cooper adalah sedikit verbose sehingga layak pemadatan. Ada cukup banyak pesan dari menjalankan pekerjaan hitungan kata Anda. Hadoop dengan senang hati memberikan banyak detail tentang program Pemetaan dan Pengurangan yang berjalan atas nama Anda. Baris kritis yang ingin Anda cari ditunjukkan pada Listing 5, termasuk daftar kedua pekerjaan yang gagal dan bagaimana memperbaiki salah satu kesalahan paling umum yang Anda hadapi saat menjalankan MapReduce. Daftar 5. MapReduce pesan - jalan bahagia Apa arti semua pesan Hadoop telah melakukan banyak pekerjaan dan mencoba menceritakannya, termasuk yang berikut. Diperiksa untuk melihat apakah file input ada. Diperiksa untuk melihat apakah direktori output ada dan jika tidak, batalkan pekerjaan. Tidak ada yang lebih buruk dari tabrakan jam perhitungan dengan kesalahan keyboard sederhana. Mendistribusikan file jar Jawa ke semua node yang bertanggung jawab untuk melakukan pekerjaan. Dalam kasus ini, ini hanya satu simpul. Jalankan tahap pemetaan pekerjaan. Biasanya ini mem-parsing file input dan memancarkan sepasang nilai kunci. Perhatikan tombol dan nilai bisa berupa objek. Jalankan fase sortir, yang memilah output pengumpul berdasarkan kuncinya. Jalankan fase pengurangan, biasanya ini merangkum value stream dan menulis output ke HDFS. Membuat banyak metrik pada kemajuan. Gambar 6 menunjukkan contoh halaman web metrik pekerjaan Hadoop setelah menjalankan latihan Hive. Gambar 6. Contoh halaman web Hadoop Apa pekerjaannya, dan di mana hasilnya Keduanya adalah pertanyaan bagus, dan ditunjukkan pada Listing 6. Listing 6. Map-Mengurangi Output Jika Anda menjalankan pekerjaan yang sama dua kali dan lupa untuk melakukannya. Hapus direktori output, Anda akan menerima pesan kesalahan yang ditunjukkan pada Listing 7. Memperbaiki kesalahan ini semudah menghapus direktori. Listing 7. MapReduce message - kegagalan karena output yang sudah ada di HDFS Hadoop menyertakan antarmuka browser untuk memeriksa status HDFS. Gambar 7 menunjukkan output dari jumlah kata kerja. Gambar 7. Menjelajahi HDFS dengan browser Konsol yang lebih canggih tersedia secara gratis dari situs web Cloudera. Ini menyediakan sejumlah kemampuan di luar antarmuka web Hadoop standar. Perhatikan bahwa status kesehatan HDFS pada Gambar 8 ditunjukkan sebagai Bad. Gambar 8. Layanan Hadoop yang dikelola oleh Cloudera Manager Mengapa Bad Karena dalam satu mesin virtual, HDFS tidak dapat membuat tiga salinan blok data. Bila blok kurang tereplikasi, maka ada risiko kehilangan data, sehingga kesehatan sistemnya buruk. Untunglah Anda mencoba menjalankan pekerjaan produksi Hadoop di satu simpul tunggal. Anda tidak terbatas pada Java untuk pekerjaan MapReduce Anda. Contoh terakhir dari MapReduce ini menggunakan Hadoop Streaming untuk mendukung mapper yang ditulis dengan Python dan reducer menggunakan AWK. Tidak, Anda tidak perlu menjadi seorang guru Java untuk menulis Map-Reduce Mark Twain bukan penggemar berat Cooper. Dalam kasus penggunaan ini, Hadoop akan memberikan beberapa kritik sastra sederhana yang membandingkan Twain dan Cooper. Tes Fleschkaid menghitung tingkat membaca teks tertentu. Salah satu faktor dalam analisis ini adalah panjang kalimat rata-rata. Kalimat parsing ternyata lebih rumit daripada sekedar mencari karakter periode. Paket openNLP dan paket NLTK Python memiliki parser kalimat yang sangat bagus. Untuk kesederhanaan, contoh yang ditunjukkan pada Listing 8 akan menggunakan kata length sebagai pengganti jumlah suku kata dalam satu kata. Jika Anda ingin membawa ini ke tingkat berikutnya, lakukan tes FleschKaid di MapReduce, jelajahi web, dan hitung tingkat membaca untuk situs berita favorit Anda. Kode 8. Kritik sastra mapons berbasis Python Output mapper, untuk kata Twain, adalah: 5 0. Panjang kata numerik diurutkan secara berurutan dan dipresentasikan ke reducer dengan urutan yang diurutkan. Dalam contoh yang ditunjukkan pada Listing 9 dan 10, menyortir data isnt yang dibutuhkan untuk mendapatkan output yang benar, namun jenisnya dibangun di dalam infrastruktur MapReduce dan akan terjadi pula. Daftar 9. Pengurang AWK untuk Kritik Ilmiah Daftar 10. Menjalankan pemeta Python dan peredam AWK dengan Hadoop Streaming Penggemar Mark Twain dapat dengan senang hati rileks karena mengetahui bahwa Hadoop menemukan Cooper menggunakan kata-kata yang lebih panjang, dan dengan standar deviasi yang mengejutkan (humor yang dimaksudkan). Itu tentu saja mengasumsikan bahwa kata-kata yang lebih pendek lebih baik. Mari melanjutkan, selanjutnya menulis data di HDFS ke Informix dan DB2. Menggunakan Sqoop untuk menulis data dari HDFS ke Informix, DB2, atau MySQL melalui JDBC Proyek Apache Sqoop adalah sumber terbuka JDBC berbasis Hadoop untuk utilitas pergerakan data database. Sqoop awalnya dibuat dalam sebuah hackathon di Cloudera dan kemudian terbuka bersumber. Memindahkan data dari HDFS ke database relasional adalah kasus penggunaan umum. HDFS dan Map-Reduce sangat hebat saat melakukan pengangkatan berat. Untuk pertanyaan sederhana atau toko back-end untuk situs web, caching Map-Reduce output di toko relasional adalah pola desain yang bagus. Anda dapat menghindari menjalankan kembali Map-Mengurangi jumlah kata dengan hanya Sqooping hasilnya ke Informix dan DB2. Anda telah menghasilkan data tentang Twain dan Cooper, sekarang mari kita pindahkan ke database, seperti yang ditunjukkan pada Listing 11. Listing 11. Penyiapan driver JDBC Contoh yang ditunjukkan pada Listing 12 sampai 15 disajikan untuk setiap database. Silahkan lompat ke contoh yang menarik bagi anda, termasuk Informix, DB2, atau MySQL. Untuk database polyglots, bersenang-senanglah melakukan setiap contoh. Jika database pilihan Anda tidak disertakan di sini, tidak menjadi tantangan besar untuk membuat contoh ini bekerja di tempat lain. Listing 12. Pengguna Informix: Sqoop menuliskan hasil penghitungan kata ke Listing Informix 13. Informix Users: Sqoop menuliskan hasil penghitungan kata ke Listing Informix 14. Pengguna DB2: Sqoop menuliskan hasil penghitungan kata ke Daftar DB2 15 Pengguna MySQL: Sqoop menuliskan hasil penghitungan kata ke MySQL Mengimpor data ke HDFS dari Informix dan DB2 dengan Sqoop Memasukkan data ke Hadoop HDFS juga dapat dilakukan dengan Sqoop. Fungsi bi-directional dikendalikan melalui parameter impor. Database sampel yang disertakan dengan kedua produk memiliki beberapa kumpulan data sederhana yang dapat Anda gunakan untuk tujuan ini. Listing 16 menunjukkan sintaks dan hasil untuk Sqooping setiap server. Untuk pengguna MySQL, silahkan mengadaptasi sintaks dari contoh Informix atau DB2 yang mengikutinya. Kode 16. Impor Sqoop dari database sampel Informix ke HDFS Mengapa ada empat file berbeda yang masing-masing hanya berisi bagian dari data Sqoop adalah utilitas yang sangat paralel. Jika cluster 4000 node yang menjalankan Sqoop melakukan impor throttle penuh dari database, 4000 koneksi akan terlihat sangat mirip dengan penolakan serangan layanan terhadap database. Batas koneksi default Sqoops adalah empat koneksi JDBC. Setiap koneksi menghasilkan file data dalam HDFS. Dengan demikian keempat file tersebut. Tidak perlu khawatir, Anda akan melihat bagaimana Hadoop bekerja di file-file ini tanpa kesulitan. Langkah selanjutnya adalah mengimpor tabel DB2. Seperti ditunjukkan pada Listing 17, dengan menentukan opsi - m 1, sebuah tabel tanpa primary key dapat diimpor, dan hasilnya adalah satu file. Listing 17. Sqoop mengimpor dari database sampel DB2 ke HDFS Menggunakan Hive: Bergabung dengan data Informix dan DB2 Ada kasus penggunaan yang menarik untuk menggabungkan data dari Informix ke DB2. Tidak terlalu menarik untuk dua tabel sepele, tapi menang besar untuk beberapa terabyte atau petabyte data. Ada dua pendekatan mendasar untuk menggabungkan sumber data yang berbeda. Meninggalkan data saat istirahat dan menggunakan teknologi federasi versus memindahkan data ke satu toko untuk melakukan join. Ekonomi dan kinerja Hadoop membuat data bergerak ke HDFS dan melakukan pengangkatan berat dengan MapReduce menjadi pilihan yang mudah. Keterbatasan bandwidth jaringan membuat hambatan mendasar jika mencoba menggabungkan data saat beristirahat dengan teknologi gaya federasi. Hive menyediakan subset dari SQL untuk beroperasi pada sebuah cluster. Ini tidak menyediakan transaksi semantik. Ini bukan pengganti Informix atau DB2. Jika Anda memiliki beberapa angkat berat dalam bentuk meja bergabung, bahkan jika Anda memiliki beberapa meja yang lebih kecil namun perlu melakukan produk Cartesian yang buruk, Hadoop adalah alat pilihan. Untuk menggunakan bahasa query Hive, subset dari SQL disebut metadata tabel Hiveql diperlukan. Anda dapat menentukan metadata terhadap file yang ada di HDFS. Sqoop menyediakan cara pintas yang mudah digunakan dengan opsi create-sarang meja. Pengguna MySQL harus merasa bebas untuk menyesuaikan contoh yang ditunjukkan pada Listing 18. Latihan yang menarik akan bergabung dengan MySQL, atau tabel database relasional lainnya, ke spreadsheet besar. Listing 18. Bergabung dengan tabel informix. customer ke tabel db2.staff Ini jauh lebih cantik saat Anda menggunakan Hue untuk antarmuka browser grafis, seperti yang ditunjukkan pada Gambar 9, 10, dan 11. Gambar 9. Beeswax Hue GUI untuk Hive di CDH4 , Lihat query Hiveql Gambar 10. Hue Beeswax GUI untuk Hive, lihat query Hiveql Gambar 11. Browser grafis Hue Beeswax, lihat Informix-DB2 join result Using Pig: Bergabung dengan Informix dan data DB2 Babi adalah bahasa prosedural. Sama seperti Hive, di bawah selimut itu menghasilkan kode MapReduce. Hadoop kemudahan penggunaan akan terus membaik karena semakin banyak proyek tersedia. Sama seperti beberapa dari kita sangat menyukai command line, ada beberapa antarmuka pengguna grafis yang bekerja sangat baik dengan Hadoop. Kode 19 menunjukkan kode Babi yang digunakan untuk bergabung dengan tabel pelanggan dan tabel staf dari contoh sebelumnya. Listing 19. Contoh babi untuk bergabung dengan tabel Informix ke tabel DB2 Bagaimana cara memilih Java, Hive, atau Pig Anda memiliki banyak pilihan untuk pemrograman Hadoop, dan yang terbaik adalah melihat use case untuk memilih alat yang tepat untuk pekerjaan itu. . Anda tidak terbatas pada mengerjakan data relasional tapi artikel ini difokuskan pada Informix, DB2, dan Hadoop yang bermain bagus bersama. Menulis ratusan baris di Jawa untuk menerapkan gaya relasional hash-join adalah pemborosan waktu karena algoritma Hadoop MapReduce ini sudah tersedia. Bagaimana Anda memilih Ini adalah masalah preferensi pribadi. Beberapa seperti pengkodean mengatur operasi di SQL. Beberapa memilih kode prosedural. Anda harus memilih bahasa yang akan membuat Anda paling produktif. Jika Anda memiliki banyak sistem relasional dan ingin menggabungkan semua data dengan kinerja hebat pada titik harga rendah, Hadoop, MapReduce, Hive, dan Pig siap membantu. Jangan menghapus data Anda: Menggulir partisi dari Informix ke HDFS Sebagian besar database relasional modern dapat mempartisi data. Kasus penggunaan umum adalah partisi menurut jangka waktu. Jendela data tetap disimpan, misalnya interval 18 bulan bergulir, setelah data diarsipkan. Kemampuan partisi detach sangat kuat. Tapi setelah partisi terlepas apa yang dilakukan seseorang dengan data Tape arsip data lama adalah cara yang sangat mahal untuk membuang byte lama. Setelah pindah ke media yang kurang mudah diakses, datanya sangat jarang diakses kecuali ada persyaratan audit legal. Hadoop memberikan alternatif yang jauh lebih baik. Memindahkan byte arsip dari partisi lama ke Hadoop memberikan akses berkinerja tinggi dengan biaya jauh lebih rendah daripada menyimpan data di sistem transaksional atau datamartdatawarehouse asli. Data terlalu tua untuk menjadi nilai transaksional, namun masih sangat berharga bagi organisasi untuk analisis jangka panjang. Contoh Sqoop yang ditunjukkan sebelumnya memberikan dasar-dasar bagaimana memindahkan data ini dari partisi relasional ke HDFS. Fuse - Mendapatkan file HDFS Anda melalui NFS Data file InformixDB2flat di HDFS dapat diakses melalui NFS, seperti yang ditunjukkan pada Listing 20. Ini menyediakan operasi baris perintah tanpa menggunakan antarmuka hadoop fs - yadayada. Dari perspektif penggunaan teknologi, NFS sangat terbatas di lingkungan Data Besar, namun contohnya disertakan untuk pengembang dan bukan data yang sangat besar. Listing 20. Menyiapkan Fuse - mengakses data HDFS Anda melalui NFS Flume - membuat file ready ready Flume generasi berikutnya, atau flume-ng adalah loader paralel berkecepatan tinggi. Database memiliki pemuat berkecepatan tinggi, jadi bagaimana cara bermain ini dengan baik. Kasus penggunaan relasional untuk Flume-ng adalah membuat file siap beban, secara lokal atau jarak jauh, sehingga server relasional dapat menggunakan loader berkecepatan tinggi. Ya, fungsi ini tumpang tindih dengan Sqoop, namun skrip yang ditunjukkan pada Listing 21 dibuat atas permintaan klien khusus untuk gaya beban basis data ini. Listing 21. Mengekspor data HDFS ke file flat untuk loading oleh database Oozie - menambahkan alur kerja untuk banyak pekerjaan Oozie akan menggabungkan beberapa pekerjaan Hadoop. Ada seperangkat contoh bagus yang disertakan dengan oozie yang digunakan dalam kumpulan kode yang ditunjukkan pada Listing 22. Listing 22. Kontrol pekerjaan dengan oozie HBase, toko value-value store berkinerja tinggi HBase adalah toko dengan nilai kinerja tinggi. Jika kasus penggunaan Anda memerlukan skalabilitas dan hanya memerlukan database yang setara dengan transaksi komit otomatis, HBase mungkin adalah teknologi yang dapat dikendarai. HBase bukan database. Nama itu sangat disayangkan karena bagi beberapa orang, istilah dasar menyiratkan database. Ini memang melakukan pekerjaan yang sangat baik untuk toko dengan nilai kinerja tinggi. Ada beberapa tumpang tindih antara fungsi basis data HBase, Informix, DB2 dan relasional lainnya. Untuk transaksi ACID, kepatuhan penuh SQL, dan beberapa indeks database relasional tradisional adalah pilihan yang jelas. Latihan kode terakhir ini adalah untuk memberikan keakraban dasar dengan HBASE. Hal ini sederhana dengan desain dan sama sekali tidak mewakili cakupan fungsionalitas HBases. Silakan gunakan contoh ini untuk memahami beberapa kemampuan dasar dalam HBase. HBase, Panduan Definitif, oleh Lars George, adalah bacaan wajib jika Anda berencana untuk menerapkan atau menolak HBase untuk kasus penggunaan khusus Anda. Contoh terakhir ini, yang ditunjukkan pada Listing 23 dan 24, menggunakan antarmuka REST yang dilengkapi dengan HBase untuk memasukkan nilai kunci ke dalam tabel HBase. Penggunaan uji adalah curl based. Kode 23. Buat tabel HBase dan masukkan Listing baris 24. Menggunakan antarmuka HBase REST Kesimpulan Wow, Anda berhasil mencapai akhir, well done Ini hanyalah awal dari pemahaman Hadoop dan bagaimana ia berinteraksi dengan Informix dan DB2. Berikut adalah beberapa saran untuk langkah selanjutnya. Ambil contoh yang ditunjukkan sebelumnya dan sesuaikan dengan server Anda. Anda ingin menggunakan data kecil karena tidak banyak ruang dalam gambar virtual. Dapatkan sertifikasi sebagai Administrator Hadoop. Kunjungi situs Cloudera untuk kursus dan informasi pengujian. Dapatkan sertifikasi sebagai Pengembang Hadoop. Memulai sebuah cluster menggunakan edisi gratis dari Cloudera Manager. Mulailah dengan IBM Big Sheets yang berjalan di atas CDH4. Sumber daya yang dapat didownload Topik terkaitMenghilangkan HBase dan Hive Konten ini adalah bagian dari rangkaian: SQL ke Hadoop dan kembali lagi, Bagian 2 Nantikan konten tambahan dalam seri ini. Hive dan HBase Mengintegrasikan Hadoop dan SQL dengan InfoSphere BigInsights InfoSphere174 BigInsights8482 membuat integrasi antara database Hadoop dan SQL lebih sederhana, karena menyediakan alat dan mekanika yang diperlukan untuk mengekspor dan mengimpor data antar database. Dengan menggunakan InfoSphere BigInsights, Anda dapat menentukan sumber database, pandangan, kueri, dan kriteria seleksi lainnya, lalu secara otomatis mengubahnya menjadi berbagai format sebelum mengimpor koleksi tersebut secara langsung ke Hadoop (lihat topik terkait untuk informasi lebih lanjut). Misalnya, Anda dapat membuat kueri yang mengekstrak data dan mengisi array JSON dengan data rekaman. Setelah diekspor, pekerjaan dapat dibuat untuk memproses dan mengurangi data sebelum menampilkannya atau mengimpor data yang diproses dan mengekspor data kembali ke DB2. Hive adalah solusi data warehouse yang memiliki bahasa query mirip SQL seperti HiveQL. Bahasa ini digunakan untuk query data, dan menghemat penulisan asli dari MapReduce untuk mengeluarkan data Anda. Karena Anda sudah tahu SQL, Hive adalah solusi yang baik karena memungkinkan Anda memanfaatkan pengetahuan SQL Anda untuk mendapatkan data masuk dan keluar dari Apache Hadoop. One limitation of the Hive approach, though, is that it makes use of the append-only nature of HDFS to provide storage. This means that it is phenomenally easy to get the data in, but you cannot update it. Hive is not a database but a data warehouse with convenient SQL querying built on top of it. Despite the convenient interface, particularly on very large datasets, the fact that the query time required to process requests is so large means that jobs are submitted and results accessed when available. This means that the information is not interactively available. HBase, by comparison, is a key-value (NoSQL) data store that enables you to write, update, and read data randomly, just like any other database. But its not SQL. HBase enables you to make use of Hadoop in a more traditional real-time fashion than would normally be possible with the Hadoop architecture. Processing and querying data is more complex with HBase, but you can combine the HBase structure with Hive to get an SQL-like interface. HBase can be really practical as part of a solution that adds the data, processes it, summarizes it through MapReduce, and stores the output for use in future processing. In short, think of Hive as an append-only SQL database and HBase as a more typical read-write NoSQL data store. Hive is useful for SQL integration if you want to store long-term data to be processed and summarized and loaded back. Hives major limitation is query speed. When dealing with billions of rows, there is no live querying of the data that would be fast enough for any interactive interface to the data. For example, with data logging, the quantities of data can be huge, but what you often need is quick, flexible querying on either summarized or extreme data (i. e. faults and failures). HBase is useful when what you want is to store large volumes of flexible data and query that information, but you might want only smaller datasets to work with. Hence, you might export data that simultaneously: Needs to be kept whole, such as sales or financial data May change over time Also needs to be queried HBase can then be combined with traditional SQL or Hive to allow snapshots, ranges, or aggregate data to be queried. Making use of Hive The primary reason to use Hive over a typical SQL database infrastructure is simply the size of the data and the length of time required to perform the query. Rather than dumping information into Hadoop, writing your own MapReduce query, and getting the information back out, with Hive you can (normally) write the same SQL statement, but on a much larger dataset. Hive accomplishes this task by translating the SQL statement into a more typical Hadoop MapReduce job that assembles the data into a tabular format. This is where the limitation comes, in that Hive is not a real-time, or live querying solution. Once you submit the job, it can take a long time to get a response. A typical use of Hive is to combine the real-time accessibility of data in a local SQL table, export that information into Hive long-term, and reimport the processed version that summarizes the data so it can be used in a live query environment, as seen in Figure 1. Figure 1. Typical use of Hive We can use the same SQL statement to get and obtain the data in both situations, a convenience that helps to harmonize and streamline your applications. Getting data into Hive from SQL The simplest way to get data in and out is by writing a custom application that will extract the required data from your existing SQL table and insert that data into Hive 8212 that is, perform a select query and use INSERT to place those values directly into Hive. Alternatively, depending on your application type, you might consider inserting data directly into both your standard SQL and Hive stores. This way, you can check your standard SQL for recent queries and process Hive data on an hourlydailyweekly schedule as required to produce the statistical data you require longer-term. Remember, with Hive, in the majority of cases we can: Use the tabular data directly Export without conversion Export without reformatting or restructuring More typically, you will be dumping entire tables or entire datasets by hour or day into Hive through an intermediary file. One benefit of this approach is that we easily introduce the file by running a local import or by copying that data directly into HDFS. Lets look at this with an example, using the City of Chicago Traffic Tracker that studies bus data, giving a historical view of the speed of buses in different regions of Chicago at different times. A sample of the data is shown in Listing 1. Listing 1. Sample of bus data from City of Chicago Traffic Tracker The sample dataset is just over 2 million records, and it has been loaded from a CSV export. To get that information into Hive, we can export it to a CSV file. Listing 2. Exporting data to a CSV file Then copy the data into HDFS: hdfs dfs - copyFromLocal chicago. csv. Now open Hive and create a suitable table. Listing 3. Opening Hive and creating a suitable table The first thing to notice with Hive is that compared to most standard SQL environments, we have a somewhat limited set of data types that can be used. Although core types like integers, strings, and floats are there, date types are limited. That said, Hive supports reading complex types, such as hashmaps. The core types supported by Hive: Integers (1-8 bytes) Boolean FloatDouble String 8212 any sequence of characters, and therefore good for CHAR, VARCHAR, SET, ENUM, TEXT, and BLOB types if the BLOG is storing text Timestamp 8212 either an EPOCH or YYYY-MM-DD hh:mm:ss. fffffffff - formatted string Binary 8212 for BLOBs that are not TEXT The second observation is that we are defining the table structure. There are binary structures within Hive, but using CSV natively is convenient for our purposes since weve exported the data to a CSV file. When loading the data, the CSV format specification here will be used to identify the fields in the data. The above example creates a standard table (the table within Hives data store within HDFS). You can also create an external table that uses the copied file directly. However, in an SQL-to-Hive environment, we want to make use of one big table into which we can append new data. Now the data can be loaded into the table: hivegt load data inpath chicago. csv into table chicagobus . This code adds the contents of the CSV file to the existing table. In this case, it is empty, but you can see how easy it would be to import additional data. Processing and querying Hive data Once the data is loaded, you can execute Hive queries from the Hive shell just as you would in any other SQL environment. For example, Listing 4 shows the same query to get the first 10 rows. Listing 4. Query to get the first 10 rows The benefit comes when we perform an aggregate query. For example, lets obtain an average bus speed for each region by day. Listing 5. Obtaining average bus speed for each region by day As you can see from the output, the query is fundamentally the same as with MySQL (we are grouping by an alternative value), but Hive converts this into a MapReduce job, then calculates the summary values. The reality with data of this style is that the likelihood of requiring the speed in region 1, for example, at 9:50 last Thursday is quite low. But knowing the average speed per day for each region might help predict the timing of traffic or buses in the future. The summary data can be queried and analyzed efficiently with a few thousand rows in an SQL store to allow the data to be sliced and diced accordingly. To output that information back to a file, a number of options are available, but you can simply export back to a local file using the statement in Listing 6. Listing 6. Exporting back to a local file This code creates a directory (chicagoout), into which the output is written as a series of text files. These can be loaded back into MySQL, but by default, the fields are separated by CtrlA . The output can be simplified to a CSV file again by creating a table beforehand, which uses the CSV formatting. Listing 7. Simplifying to a CSV file Now rerun the job and insert the information into the table. Listing 8. Rerunning the job You can now find the files that make up the table in your Hive datawarehouse directory, so you can copy them out for loading into your standard SQL store, for example, using LOAD DATA INFILE. Listing 9. Loading files into your standard SQL store This process sounds clunky, but it can be automated, and because we have files from each stage, it is easy to re-execute or reformat the information if required. Using views If you are using Hive in the manner suggested earlier, and regularly processing and summarizing data daily, weekly or monthly, it might be simpler to create a view. Views within Hive are logical 8212 that is, the output of the view gets re-created each time a query is executed. Although using views is more expensive, for a data exchange environment, views hugely simplify the process by simplifying the query structure and allowing consistent output as the underlying source tables expand with new data. For example, to create a view from our original speedregion summary, use Listing 10. Listing 10. Creating a view from our original speedregion summary Now we can perform Hive queries on the view including new selections. Listing 11. Performing Hive queries on the view Not looking good for traffic in region 28, is it Data life-cycle management If you decide to use Hive as a live component of your querying mechanism 8212 exporting data from SQL, into Hive, and back out again so it can be used regularly 8212 give careful thought as to how you manage the files to ensure accuracy. I tend to use the following basic sequence: Insert new data into a table 8212 datalog, for example. When datalog is full (i. e. an hour, day, week, or month of information is complete), the table is renamed (to datalogarchive, for example), and a new table (same structure) is created. Data is exported from datalogarchive and appended into the Hive table for the data. Depending on how the data is used and processed, analysis occurs by accessing the live data or by running the exact same SQL query statement on Hive. If the data is needed quickly, a view or query is executed that imports the corresponding data back into an SQL table in a summarized format. For example, for systems logging data (RAM, disk, and other usages) of large clusters, the data is stored in SQL for a day. This approach allows for live monitoring and makes it possible to spot urgent trends. Data is written out each day to Hive where the log content is analyzed by a series of views that collect extreme values (for example, disk space less than 5 percent), as well as average disk usage. While reviewing the recent data, its easy to examine and correlate problems (extreme disk usage and increased CPU time, for example), and execute the same query on the Hive long-term store to get the detailed picture. Using HBase Whereas Hive is useful for huge datasets where live queries are not required, HBase allows us to perform live queries on data, but it works differently. The primary difference is that HBase is not a tabular data store, so importing tabular data from an SQL store is more complex. That said, the flexible internal structure of HBase is also more flexible. Data sources of multiple different data structures can be merged together within HBase. For example, with log data, you can store multiple sensor data into a single table within HBase, a situation that would require multiple tables in an SQL store. Getting data in HBase from SQL Unlike Hive, which supports a native tabular layout for the source data, HBase stores key-value pairs. This key-value system complicates the process of exporting data and using it directly because it first needs to be identified and then formatted accordingly to be understood within HBase. Each item (or item identifier) requires a unique key. The unique ID is important because it is the only way to get individual data back again the unique ID locates the record within the HBase table. Remember that HBase is about key-value pairs, and the unique ID (or key) is the identifier to the stored record data. For some data types, such as the log data in our Hive examples, the unique key is meaningless because we are unlikely to want to view just one record. For other types, the data may already have a suitable unique ID within the table you want to use. This dilemma can be solved by pre-processing our output, for example, and inserting a UUID() into our output. Listing 12. Pre-processing the output This code creates a new UUID for each row of output. The UUID can be used to identify each record 8212 even though for this type of data, that identification is not individually useful. A secondary consideration within the export process is that HBase does not support joins. If you want to use HBase to write complex queries on your SQL data, you need to run a query within your SQL store that outputs an already-joined or aggregate record. Within HBase, tables are organized according to column families, and these can be used to bond multiple groups of individual columns, or you can use the column families as actual columns. The translation is from the table to the document structure, as shown in Figure 2. Figure 2. Translation from table to the document structure To import the data, you have to first create the table. HBase includes a basic shell for accepting commands. We can open it and create a table and a table group called cf. Listing 13. Creating a table group called cf Copy the tab-separated file created earlier into HDFS: hdfs dfs - copyFromLocal chicago. tsv. Now we can run importtsv, a tool inside the HBase JAR that imports values from a tab-delimited file. Listing 14. Running importtsv The content needs to be split to make it understandable: hadoop jar usrlibhbasehbase. jar importtsv. This code runs the importtsv tool, which is included as part of the HBase JAR: - Dimporttsv. columnsHBASEROWKEY, logtime, region, buscount, readnumber, speed . The tool defines the columns that will be imported and how they will be identified. The fields are defined as a list at least one of them must be the identifier (UUID) for each row, specified by HBASEROWKEY. and the others define the field names (within the column family, cf) used for each input column. chicago 8212 The table name. It must have been created before this tool is executed. chicago. tsv 8212 The name of the file in HDFS to be imported. The output from this command (see Listing 15) is rather immense, but the import process is complicated. The data cannot be directly loaded. Instead, it gets parsed by a MapReduce process that extracts and then inserts the data into an HBase table. Listing 15. Output from importtsv command If you get a bad-lines output that shows a high number of errors, particularly if the number equals the number of rows you are importing, the problem is probably the format of the source file or the fact that the number of columns in the source file does not match the number of columns defined in the import specification. Once the data has been imported, we can use the shell to get one record to check that the import has worked. Listing 16. Checking to see if the import has worked You can see the basic structure of the data as it exists within the HBase table. The unique ID identifies each record, then individual key-value pairs contain the detail (i. e. the columns from the original SQL table). Alternative SQL or Hive to HBase An alternative model to the raw-data export (less common to HBase because of the record structure) is to use HBase to store summary values and parsedcomposed queries. Because the data from HBase is stored in a readily and quickly accessible format (access the key and get the data), it can be used to access chunks of data that have been computed from other jobs, stored into HBase, and used to access the summary data. For example, the summary data we generated using Hive earlier in this example could have been written into HBase to be accessed quickly to provide statistical data on the fly for a website. Using HBase data from Hive Now that we have the data in HBase, we can start querying and reporting on the information. The primary advantage of HBase is its powerful querying facilities based on the MapReduce within Hadoop. Since the data is stored internally as simple key-value combinations, it is easy to process through MapReduce. MapReduce is no solution for someone from the SQL world, but we can take advantage of the flexible nature of Hives processing model to crunch HBase data using the HQL interface. You may remember earlier I described how Hive supports processing of mapped data types this is what HBase data is: mapped key-value pairs. To use HBase data, we need to create a table within Hive that points to the HBase table and maps the key-value pairs in HBase to the column style of Hive. Listing 17. Creating a table within Hive that points to the HBase table and maps the key-value pairs in HBase to the column style of Hive The first part of this code creates a table definition identical to the one we used natively in Hive, except that we have added the row-key UUID as the first column. The STORED BY block defines the storage format. The SERDEPROPERTIES block is the mapping between the document structure and the columns. The colon separates the key name and corresponding value and how the data should be mapped to the columns, in sequence, from the table definition. The TBLPROPERTIES block defines the name of the HBase table where the data lies. Once the table has been created, the table can be queried through Hive using native SQL, just as we saw earlier. Why use this method instead of a native import The primary reason is the ease with which it can be queried (although no longer live), but also because the underlying HBase data can be updated, rather than just appended to. In an SQL-to-Hadoop architecture this advantage means we can take regular dumps of changing data from SQL and update the content. Reminder: HBase or Hive Given the information here, its worth reminding ourselves of the benefits of the two systems. Table 1. Benefits of the two systems Which one you use will depend entirely on your use case and the data you have available, and how you want to query it. Hive is great for massive processing of ever-increasing data. HBase is useful for querying data that may change over time and need to be updated. Conclusion The primary reason for moving data between SQL stores and Hadoop is usually to take advantage of the massive storage and processing capabilities to process quantities of data larger than you could hope to cope with in SQL alone. How you exchange and process that information from your SQL store into Hadoop is, therefore, important. Large quantities of long-term data that need to be queried more interactively can take advantage of the append-only and SQL nature of Hive. For data that needs to be updated and processed, it might make more sense to use HBase. HBase also makes an ideal output target from Hive because its so easy to access summary data directly by using the native key-value store. When processing, you also need to consider how to get the data back in. With Hive, the process is easy because we can run SQL and get a table that can easily be imported back to our SQL store for straightforward or live query processing. In this article, Ive covered a wide range of use cases and examples of how data can be exchanged more easily from SQL using tabular interfaces to the Hadoop and non-tabular storage underneath. Downloadable resources Related topics Check out the Chicago Traffic Tracker . Read Whats the big deal about Big SQL to learn about IBMs SQL interface to its Hadoop-based platform, InfoSphere BigInsights. Big SQL is designed to provide SQL developers with an easy on-ramp for querying data managed by Hadoop. Dig deeper in the Developing Big SQL queries to analyze big data tutorial in the InfoSphere BigInsights tutorial collection (PDF). Analyzing social media and structured data with InfoSphere BigInsights teaches the basics of using BigSheets to analyze social media and structured data collected through sample applications provided with BigInsights. Read Understanding InfoSphere BigInsights to learn more about the InfoSphere BigInsights architecture and underlying technologies. Watch the Big Data: Frequently Asked Questions for IBM InfoSphere BigInsights video to listen to Cindy Saracco discuss some of the frequently asked questions about IBMs Big Data platform and InfoSphere BigInsights. Watch Cindy Saracco demonstrate portions of the scenario described in this article in Big Data -- Analyzing Social Media for Watson . Read Exploring your InfoSphere BigInsights cluster and sample applications to learn more about the InfoSphere BigInsights web console. Learn about the IBM Watson research project. Check out Big Data University for free courses on Hadoop and big data. Order a copy of Understanding Big Data: Analytics for Enterprise Class Hadoop and Streaming Data for details on two of IBMs key big data technologies. Learn more about Apache Hadoop . Check out HadoopDB . Read Using MapReduce and load balancing on the cloud to learn how to implement the Hadoop MapReduce framework in a cloud environment and how to use virtual load balancing to improve the performance of both a single - and multiple-node system. For information on installing Hadoop using CDH4, see CDH4 Installation - Cloudera Support . Big Data Glossary , by Pete Warden, OReilly Media, ISBN 1449314597, 2011 and Hadoop: The Definitive Guide , by Tom White, OReilly Media, ISBN 1449389732, 2010, offer more information. HadoopDB: An Architectural Hybrid of MapReduce and DBMS Technologies for Analytical Workloads explores the feasibility of building a hybrid system that takes the best features from both technologies. Learn more by reading MapReduce and parallel DBMSes: friends or foes A Survey of Large Scale Data Management Approaches in Cloud Environments gives a comprehensive survey of numerous approaches and mechanisms of deploying data-intensive applications in the cloud, which are gaining a lot of momentum in both research and industrial communities. Get Hadoop 0.20.1, Hadoop MapReduce, and Hadoop HDFS from Apache. org . Find resources to help you get started with InfoSphere BigInsights. IBMs Hadoop-based offering that extends the value of open source Hadoop with features like Big SQL, text analytics, and BigSheets. Download InfoSphere BigInsights Quick Start Edition. available as a native software installation or as a VMware image. Follow these self-paced tutorials (PDF) to learn how to manage your big data environment, import data for analysis, analyze data with BigSheets, develop your first big data application, develop Big SQL queries to analyze big data, and create an extractor to derive insights from text documents with InfoSphere BigInsights. Find resources to help you get started with InfoSphere Streams. IBMs high-performance computing platform that enables user-developed applications to rapidly ingest, analyze, and correlate information as it arrives from thousands of real-time sources. Download InfoSphere Streams. available as a native software installation or as a VMware image. Use InfoSphere Streams on IBM SmartCloud Enterprise . Sign in or register to add and subscribe to comments. Hadoop Tutorial 8211 Getting Started with HDP Introduction Hello World is often used by developers to familiarize themselves with new concepts by building a simple program. This tutorial aims to achieve a similar purpose by getting practitioners started with Hadoop and HDP. We will use an Internet of Things (IoT) use case to build your first HDP application. This tutorial describes how to refine data for a Trucking IoT Data Discovery (aka IoT Discovery) use case using the Hortonworks Data Platform. The IoT Discovery use cases involves vehicles, devices and people moving across a map or similar surface. Your analysis is targeted to linking location information with your analytic data. For our tutorial we are looking at a use case where we have a truck fleet. Each truck has been equipped to log location and event data. These events are streamed back to a datacenter where we will be processing the data. The company wants to use this data to better understand risk. Here is the video of Analyzing Geolocation Data to show you what you8217ll be doing in this tutorial. Pre-Requisites: Downloaded and Installed Hortonworks Sandbox Before entering hello HDP labs, we highly recommend you go through Learning the Ropes of the Hortonworks Sandbox to become familiar with the Sandbox in a VM and the Ambari Interface. Data Set Used: Geolocation. zip Optional . Hortonworks ODBC driver installed and configured see the tutorial on installing the ODBC driver for Windows or OS X. Refer to Installing and Configuring the Hortonworks ODBC driver on Windows 7 Installing and Configuring the Hortonworks ODBC driver on Mac OS X In this tutorial, the Hortonworks Sandbox is installed on an Oracle VirtualBox virtual machine (VM) your screens may be different. Tutorial Overview In this tutorial, we will provide the collected geolocation and truck data. We will import this data into HDFS and build derived tables in Hive. Then we will process the data using Pig, Hive and Spark. The processed data is then visualized using Apache Zeppelin. To refine and analyze Geolocation data, we will: Review some Hadoop Fundamentals Download and extract the Geolocation data files. Load the captured data into the Hortonworks Sandbox. Run Hive, Pig and Spark scripts that compute truck mileage and driver risk factor. Visualize the geolocation data using Zeppelin. Goals of the Tutorial The goal of this tutorial is that you get familiar with the basics of following: Hadoop and HDP Ambari File User Views and HDFS Ambari Hive User Views and Apache Hive Ambari Pig User Views and Apache Pig Apache Spark Data Visualization with Zeppelin (Optional) Tutorial QampA and Reporting Issues If you need help or have questions with this tutorial, please first check HCC for existing Answers to questions on this tutorial using the Find Answers button. If you don8217t find your answer you can post a new HCC question for this tutorial using the Ask Questions button. Tutorial Name: Hello HDP An Introduction to Hadoop with Hive and Pig If the tutorial has multiple labs please indicate which lab your question corresponds to. Please provide any feedback related to that lab. All Hortonworks, partner and community tutorials are posted in the Hortonworks github and can be contributed via the Hortonworks Tutorial Contribution Guide. If you are certain there is an issue or bug with the tutorial, please create an issue on the repository and we will do our best to resolve it In this tutorial, we will explore important concepts that will strengthen your foundation in the Hortonworks Data Platform (HDP). Apache Hadoop is a layered structure to process and store massive amounts of data. In our case, Apache TM Hadoop will be recognized as an enterprise solution in the form of HDP. At the base of HDP exists our data storage environment known as the Hadoop Distributed File System. When data files are accessed by Hive, Pig or another coding language, YARN is the Data Operating System that enables them to analyze, manipulate or process that data. HDP includes various components that open new opportunities and efficiencies in healthcare, finance, insurance and other industries that impact people. Pre-Requisites 1st Concept: Hadoop amp HDP 1.1 Introduction In this module you will learn about Apache TM Hadoop and what makes it scale to large data sets. We will also talk about various components of the Hadoop ecosystem that make Apache Hadoop enterprise ready in the form of Hortonworks Data Platform (HDP) distribution. This module discusses Apache Hadoop and its capabilities as a data platform. The core of Hadoop and its surrounding ecosystem solution vendors provide enterprise requirements to integrate alongside Data Warehouses and other enterprise data systems. These are steps towards the implementation of a modern data architecture, and towards delivering an enterprise 8216Data Lake8217 1.2 Goals of this module Understanding Hadoop. Understanding five pillars of HDP Understanding HDP components and their purpose. 1.3 Apache Hadoop Apache Hadoop is an open source framework for distributed storage and processing of large sets of data on commodity hardware. Hadoop enables businesses to quickly gain insight from massive amounts of structured and unstructured data. Numerous Apache Software Foundation projects make up the services required by an enterprise to deploy, integrate and work with Hadoop. Refer to the blog reference below for more information on Hadoop. The base Apache Hadoop framework is composed of the following modules: Hadoop Common contains libraries and utilities needed by other Hadoop modules. Hadoop Distributed File System (HDFS) a distributed file-system that stores data on commodity machines, providing very high aggregate bandwidth across the cluster. Hadoop YARN a resource-management platform responsible for managing computing resources in clusters and using them for scheduling of users8217 applications. Hadoop MapReduce a programming model for large scale data processing. Each project has been developed to deliver an explicit function and each has its own community of developers and individual release cycles. There are five pillars to Hadoop that make it enterprise ready: Data Management Store and process vast quantities of data in a storage layer that scales linearly. Hadoop Distributed File System (HDFS) is the core technology for the efficient scale out storage layer, and is designed to run across low-cost commodity hardware. Apache Hadoop YARN is the pre-requisite for Enterprise Hadoop as it provides the resource management and pluggable architecture for enabling a wide variety of data access methods to operate on data stored in Hadoop with predictable performance and service levels. Apache Hadoop YARN Part of the core Hadoop project, YARN is a next-generation framework for Hadoop data processing extending MapReduce capabilities by supporting non-MapReduce workloads associated with other programming models. HDFS Hadoop Distributed File System (HDFS) is a Java-based file system that provides scalable and reliable data storage that is designed to span large clusters of commodity servers. Data Access Interact with your data in a wide variety of ways from batch to real-time. Apache Hive is the most widely adopted data access technology, though there are many specialized engines. For instance, Apache Pig provides scripting capabilities, Apache Storm offers real-time processing, Apache HBase offers columnar NoSQL storage and Apache Accumulo offers cell-level access control. All of these engines can work across one set of data and resources thanks to YARN and intermediate engines such as Apache Tez for interactive access and Apache Slider for long-running applications. YARN also provides flexibility for new and emerging data access methods, such as Apache Solr for search and programming frameworks such as Cascading. Apache Hive Built on the MapReduce framework, Hive is a data warehouse that enables easy data summarization and ad-hoc queries via an SQL-like interface for large datasets stored in HDFS. Apache Pig A platform for processing and analyzing large data sets. Pig consists of a high-level language (Pig Latin) for expressing data analysis programs paired with the MapReduce framework for processing these programs. MapReduce MapReduce is a framework for writing applications that process large amounts of structured and unstructured data in parallel across a cluster of thousands of machines, in a reliable and fault-tolerant manner. Apache Spark Spark is ideal for in-memory data processing. It allows data scientists to implement fast, iterative algorithms for advanced analytics such as clustering and classification of datasets. Apache Storm Storm is a distributed real-time computation system for processing fast, large streams of data adding reliable real-time data processing capabilities to Apache Hadoop 2.x Apache HBase A column-oriented NoSQL data storage system that provides random real-time readwrite access to big data for user applications. Apache Tez Tez generalizes the MapReduce paradigm to a more powerful framework for executing a complex DAG (directed acyclic graph) of tasks for near real-time big data processing. Apache Kafka Kafka is a fast and scalable publish-subscribe messaging system that is often used in place of traditional message brokers because of its higher throughput, replication, and fault tolerance. Apache HCatalog A table and metadata management service that provides a centralized way for data processing systems to understand the structure and location of the data stored within Apache Hadoop. Apache Slider A framework for deployment of long-running data access applications in Hadoop. Slider leverages YARN8217s resource management capabilities to deploy those applications, to manage their lifecycles and scale them up or down. Apache Solr Solr is the open source platform for searches of data stored in Hadoop. Solr enables powerful full-text search and near real-time indexing on many of the world8217s largest Internet sites. Apache Mahout Mahout provides scalable machine learning algorithms for Hadoop which aids with data science for clustering, classification and batch based collaborative filtering. Apache Accumulo Accumulo is a high performance data storage and retrieval system with cell-level access control. It is a scalable implementation of Google8217s Big Table design that works on top of Apache Hadoop and Apache ZooKeeper. Data Governance and Integration Quickly and easily load data, and manage according to policy. Apache Falcon provides policy-based workflows for data governance, while Apache Flume and Sqoop enable easy data ingestion, as do the NFS and WebHDFS interfaces to HDFS. Apache Falcon Falcon is a data management framework for simplifying data lifecycle management and processing pipelines on Apache Hadoop. It enables users to orchestrate data motion, pipeline processing, disaster recovery, and data retention workflows. Apache Flume Flume allows you to efficiently aggregate and move large amounts of log data from many different sources to Hadoop. Apache Sqoop Sqoop is a tool that speeds and eases movement of data in and out of Hadoop. It provides a reliable parallel load for various, popular enterprise data sources. Security Address requirements of Authentication, Authorization, Accounting and Data Protection. Security is provided at every layer of the Hadoop stack from HDFS and YARN to Hive and the other Data Access components on up through the entire perimeter of the cluster via Apache Knox. Apache Knox The Knox Gateway (8220Knox8221) provides a single point of authentication and access for Apache Hadoop services in a cluster. The goal of the project is to simplify Hadoop security for users who access the cluster data and execute jobs, and for operators who control access to the cluster. Apache Ranger Apache Ranger delivers a comprehensive approach to security for a Hadoop cluster. It provides central security policy administration across the core enterprise security requirements of authorization, accounting and data protection. Operations Provision, manage, monitor and operate Hadoop clusters at scale. Apache Ambari An open source installation lifecycle management, administration and monitoring system for Apache Hadoop clusters. Apache Oozie Oozie Java Web application used to schedule Apache Hadoop jobs. Oozie combines multiple jobs sequentially into one logical unit of work. Apache ZooKeeper A highly available system for coordinating distributed processes. Distributed applications use ZooKeeper to store and mediate updates to important configuration information. Apache Hadoop can be useful across a range of use cases spanning virtually every vertical industry. It is becoming popular anywhere that you need to store, process, and analyze large volumes of data. Examples include digital marketing automation, fraud detection and prevention, social network and relationship analysis, predictive modeling for new drugs, retail in-store behavior analysis, and mobile device location-based marketing. To learn more about Apache Hadoop, watch the following introduction: 1.4 Hortonworks Data Platform (HDP) Hortonworks Data Platform (HDP) is a packaged software Hadoop distribution that aims to ease deployment and management of Hadoop clusters. Compared with simply downloading the various Apache code bases and trying to run them together a system, HDP greatly simplifies the use of Hadoop. Architected, developed, and built completely in the open, HDP provides an enterprise ready data platform that enables organizations to adopt a Modern Data Architecture. With YARN as its architectural center it provides a data platform for multi-workload data processing across an array of processing methods from batch through interactive to real-time, supported by key capabilities required of an enterprise data platform spanning Governance, Security and Operations. The Hortonworks Sandbox is a single node implementation of HDP. It is packaged as a virtual machine to make evaluation and experimentation with HDP fast and easy. The tutorials and features in the Sandbox are oriented towards exploring how HDP can help you solve your business big data problems. The Sandbox tutorials will walk you through how to bring some sample data into HDP and how to manipulate it using the tools built into HDP. The idea is to show you how you can get started and show you how to accomplish tasks in HDP. HDP is free to download and use in your enterprise and you can download it here: Hortonworks Data Platform 1.5 Suggested Readings 2nd Concept: HDFS 2.1 Introduction A single physical machine gets saturated with its storage capacity as data grows. With this growth comes the impending need to partition your data across separate machines. This type of File system that manages storage of data across a network of machines is called a Distributed File System. HDFS is a core component of Apache Hadoop and is designed to store large files with streaming data access patterns, running on clusters of commodity hardware. With Hortonworks Data Platform HDP 2.2, HDFS is now expanded to support heterogeneous storage media within the HDFS cluster. 2.2 Goals of this module Understanding HDFS architecture Understanding Hortonworks Sandbox Amabri File User View 2.3 Hadoop Distributed File System HDFS is a distributed file system that is designed for storing large data files. HDFS is a Java-based file system that provides scalable and reliable data storage, and it was designed to span large clusters of commodity servers. HDFS has demonstrated production scalability of up to 200 PB of storage and a single cluster of 4500 servers, supporting close to a billion files and blocks. HDFS is a scalable, fault-tolerant, distributed storage system that works closely with a wide variety of concurrent data access applications, coordinated by YARN. HDFS will 8220just work8221 under a variety of physical and systemic circumstances. By distributing storage and computation across many servers, the combined storage resource can grow linearly with demand while remaining economical at every amount of storage. An HDFS cluster is comprised of a NameNode, which manages the cluster metadata, and DataNodes that store the data. Files and directories are represented on the NameNode by inodes. Inodes record attributes like permissions, modification and access times, or namespace and disk space quotas. The file content is split into large blocks (typically 128 megabytes), and each block of the file is independently replicated at multiple DataNodes. The blocks are stored on the local file system on the DataNodes. The Namenode actively monitors the number of replicas of a block. When a replica of a block is lost due to a DataNode failure or disk failure, the NameNode creates another replica of the block. The NameNode maintains the namespace tree and the mapping of blocks to DataNodes, holding the entire namespace image in RAM. The NameNode does not directly send requests to DataNodes. It sends instructions to the DataNodes by replying to heartbeats sent by those DataNodes. The instructions include commands to: replicate blocks to other nodes, remove local block replicas, re-register and send an immediate block report, or shut down the node. With the next generation HDFS data architecture that comes with HDP 2.4, HDFS has evolved to provide automated failure with a hot standby, with full stack resiliency. The video provides more clarity on HDFS. 2.3.1 Ambari Files User View on Hortonworks Sandbox Ambari Files User View Ambari Files User View provides a user friendly interface to upload, store and move data. Underlying all components in Hadoop is the Hadoop Distributed File System(HDFS ). This is the foundation of the Hadoop cluster. The HDFS file system manages how the datasets are stored in the Hadoop cluster. It is responsible for distributing the data across the datanodes, managing replication for redundancy and administrative tasks like adding, removing and recovery of data nodes. 2.4 Suggested Readings 3rd Concept: MapReduce amp YARN 3.1 Introduction Cluster computing faces several challenges such as how to store data persistently and keep it available if nodes fail or how to deal with node failures during a long running computation. Also there is network bottleneck which delays the time of processing data. MapReduce offers a solution by bring computation close to data thereby minimizing data movement. It is a simple programming model designed to process large volumes of data in parallel by dividing the job into a set of independent tasks. The biggest limitation with MapReduce programming is that map and reduce jobs are not stateless. This means that Reduce jobs have to wait for map jobs to be completed first. This limits maximum parallelism and therefore YARN was born as a generic resource management and distributed application framework. 3.2 Goals of the Module Understanding Map and Reduce jobs. Understanding YARN MapReduce is the key algorithm that the Hadoop data processing engine uses to distribute work around a cluster. A MapReduce job splits a large data set into independent chunks and organizes them into key, value pairs for parallel processing. This parallel processing improves the speed and reliability of the cluster, returning solutions more quickly and with greater reliability. The Map function divides the input into ranges by the InputFormat and creates a map task for each range in the input. The JobTracker distributes those tasks to the worker nodes. The output of each map task is partitioned into a group of key-value pairs for each reduce. map(key1,value) - gt listltkey2,value2gt The Reduce function then collects the various results and combines them to answer the larger problem that the master node needs to solve. Each reduce pulls the relevant partition from the machines where the maps executed, then writes its output back into HDFS. Thus, the reduce is able to collect the data from all of the maps for the keys and combine them to solve the problem. reduce(key2, listltvalue2gt) - gt listltvalue3gt The current Apache Hadoop MapReduce System is composed of the JobTracker, which is the master, and the per-node slaves called TaskTrackers. The JobTracker is responsible for resource management (managing the worker nodes i. e. TaskTrackers), tracking resource consumptionavailability and also job life-cycle management (scheduling individual tasks of the job, tracking progress, providing fault-tolerance for tasks etc). The TaskTracker has simple responsibilities launchteardown tasks on orders from the JobTracker and provide task-status information to the JobTracker periodically. The Apache Hadoop projects provide a series of tools designed to solve big data problems. The Hadoop cluster implements a parallel computing cluster using inexpensive commodity hardware. The cluster is partitioned across many servers to provide a near linear scalability. The philosophy of the cluster design is to bring the computing to the data. So each datanode will hold part of the overall data and be able to process the data that it holds. The overall framework for the processing software is called MapReduce. Here8217s a short video introduction to MapReduce: 3.4 Apache YARN (Yet Another Resource Negotiator) Hadoop HDFS is the data storage layer for Hadoop and MapReduce was the data-processing layer in Hadoop 1x. However, the MapReduce algorithm, by itself, isn8217t sufficient for the very wide variety of use-cases we see Hadoop being employed to solve. Hadoop 2.0 presents YARN, as a generic resource-management and distributed application framework, whereby, one can implement multiple data processing applications customized for the task at hand. The fundamental idea of YARN is to split up the two major responsibilities of the JobTracker i. e. resource management and job schedulingmonitoring, into separate daemons: a global ResourceManager and per-application ApplicationMaster (AM). The ResourceManager and per-node slave, the NodeManager (NM), form the new, and generic, system for managing applications in a distributed manner. The ResourceManager is the ultimate authority that arbitrates resources among all the applications in the system. The per-application ApplicationMaster is, in effect, a framework specific entity and is tasked with negotiating resources from the ResourceManager and working with the NodeManager(s) to execute and monitor the component tasks. ResourceManager has a pluggable Scheduler . which is responsible for allocating resources to the various running applications subject to familiar constraints of capacities, queues etc. The Scheduler is a pure scheduler in the sense that it performs no monitoring or tracking of status for the application, offering no guarantees on restarting failed tasks either due to application failure or hardware failures. The Scheduler performs its scheduling function based on the resource requirements of the applications it does so based on the abstract notion of a Resource Container which incorporates resource elements such as memory, CPU, disk, network etc. NodeManager is the per-machine slave, which is responsible for launching the applications8217 containers, monitoring their resource usage (CPU, memory, disk, network) and reporting the same to the ResourceManager. The per-application ApplicationMaster has the responsibility of negotiating appropriate resource containers from the Scheduler, tracking their status and monitoring for progress. From the system perspective, the ApplicationMaster itself runs as a normal container . Here is an architectural view of YARN: One of the crucial implementation details for MapReduce within the new YARN system that I8217d like to point out is that we have reused the existing MapReduce framework without any major surgery. This was very important to ensure compatibility for existing MapReduce applications and users. Here is a short video introduction for YARN. 3.5 Suggested Readings HDFS is one of the 4 components of Apache Hadoop the other 3 are Hadoop Common, Hadoop YARN and Hadoop MapReduce. To learn more about HDFS watch the following HDFS introduction video. To learn more about YARN watch the following YARN introduction video . 4th Concept: Hive and Pig 4.1 Introduction: Apache Hive Hive is an SQL like query language that enables those analysts familiar with SQL to run queries on large volumes of data. Hive has three main functions: data summarization, query and analysis. Hive provides tools that enable easy data extraction, transformation and loading (ETL). 4.2 Goals of the module Understanding Apache Hive Understanding Apache Tez Understanding Ambari Hiver User Views on Hortonworks Sandbox Data analysts use Hive to explore, structure and analyze that data, then turn it into business insights. Hive implements a dialect of SQL (Hive QL) that focuses on analytics and presents a rich set of SQL semantics including OLAP functions, sub-queries, common table expressions and more. Hive allows SQL developers or users with SQL tools to easily query, analyze and process data stored in Hadoop. Hive also allows programmers familiar with the MapReduce framework to plug in their custom mappers and reducers to perform more sophisticated analysis that may not be supported by the built-in capabilities of the language. Hive users have a choice of 3 runtimes when executing SQL queries. Users can choose between Apache Hadoop MapReduce, Apache Tez or Apache Spark frameworks as their execution backend. Here are some advantageous characteristics of Hive for enterprise SQL in Hadoop: As data variety and volume grows, more commodity machines can be added, without a corresponding reduction in performance 4.3.1 How Hive Works The tables in Hive are similar to tables in a relational database, and data units are organized in a taxonomy from larger to more granular units. Databases are comprised of tables, which are made up of partitions. Data can be accessed via a simple query language and Hive supports overwriting or appending data. Within a particular database, data in the tables is serialized and each table has a corresponding Hadoop Distributed File System (HDFS) directory. Each table can be sub-divided into partitions that determine how data is distributed within sub-directories of the table directory. Data within partitions can be further broken down into buckets. 4.3.2 Components of Hive HCatalog is a component of Hive. It is a table and storage management layer for Hadoop that enables users with different data processing tools including Pig and MapReduce to more easily read and write data on the grid. HCatalog holds a set of files paths and metadata about data in a Hadoop cluster. This allows scripts, MapReduce and Tez, jobs to be decoupled from data location and metadata like the schema. Additionally, since HCatalog also supports tools like Hive and Pig, the location and metadata can be shared between tools. Using the open APIs of HCatalog external tools that want to integrate, such as Teradata Aster, can also use leverage file path location and metadata in HCatalog. At one point HCatalog was its own Apache project. However, in March, 2013, HCatalog8217s project merged with Hive. HCatalog is currently released as part of Hive. WebHCat provides a service that you can use to run Hadoop MapReduce (or YARN), Pig, Hive jobs or perform Hive metadata operations using an HTTP (REST style) interface. Here is a short video introduction on Hive: Apache Tez is an extensible framework for building high performance batch and interactive data processing applications, coordinated by YARN in Apache Hadoop. Tez improves the MapReduce paradigm by dramatically improving its speed, while maintaining MapReduce8217s ability to scale to petabytes of data. Important Hadoop ecosystem projects like Apache Hive and Apache Pig use Apache Tez, as do a growing number of third party data access applications developed for the broader Hadoop ecosystem. Apache Tez provides a developer API and framework to write native YARN applications that bridge the spectrum of interactive and batch workloads. It allows those data access applications to work with petabytes of data over thousands nodes. The Apache Tez component library allows developers to create Hadoop applications that integrate natively with Apache Hadoop YARN and perform well within mixed workload clusters. Since Tez is extensible and embeddable, it provides the fit-to-purpose freedom to express highly optimized data processing applications, giving them an advantage over end-user-facing engines such as MapReduce and Apache Spark. Tez also offers a customizable execution architecture that allows users to express complex computations as dataflow graphs, permitting dynamic performance optimizations based on real information about the data and the resources required to process it. Here is a short video introduction on Tez. 4.3.4 Stinger and Stinger. next The Stinger Initiative was started to enable Hive to support an even broader range of use cases at truly Big Data scale: bringing it beyond its Batch roots to support interactive queries all with a common SQL access layer. Stinger. next is a continuation of this initiative focused on even further enhancing the speed. scale and breadth of SQL support to enable truly real-time access in Hive while also bringing support for transactional capabilities. And just as the original Stinger initiative did, this will be addressed through a familiar three-phase delivery schedule and developed completely in the open Apache Hive community. 4.3.5 Ambari Hive User Views on Hortonworks Sandbox To make it easy to interact with Hive we use a tool in the Hortonworks Sandbox called the Ambari Hive User View. Ambari Hive User View provides an interactive interface to Hive. We can create, edit, save and run queries, and have Hive evaluate them for us using a series of MapReduce jobs or Tez jobs. Let8217s now open the Ambari Hive User View and get introduced to the environment, go to the Ambari User VIew icon and select Hive : Ambari Hive User View Now let8217s take a closer look at the SQL editing capabilities in the User View: There are five tabs to interact with SQL: Query . This is the interface shown above and the primary interface to write, edit and execute new SQL statements Saved Queries . You can save your favorite queries and quickly have access to them to rerun or edit. History . This allows you to look at past queries or currently running queries to view, edit and rerun. It also allows you to see all SQL queries you have authority to view. For example, if you are an operator and an analyst needs help with a query, then the Hadoop operator can use the History feature to see the query that was sent from the reporting tool. UDF s: Allows you to define UDF interfaces and associated classes so you can access them from the SQL editor. Upload Table . Allows you to upload your hive query tables to your preferred database and appears instantly in the Query Editor for execution. Database Explorer: The Database Explorer helps you navigate your database objects. You can either search for a database object in the Search tables dialog box, or you can navigate through Database - gt Table - gt Columns in the navigation pane. The principle pane to write and edit SQL statements. This editor includes content assist via CTRL Space to help you build queries. Content assist helps you with SQL syntax and table objects. Once you have created your SQL statement you have 4 options: Execute . This runs the SQL statement. Explain . This provides you a visual plan, from the Hive optimizer, of how the SQL statement will be executed. Save as . Allows you to persist your queries into your list of saved queries. Kill Session . Terminates the SQL statement. When the query is executed you can see the Logs or the actual query results. Logs: When the query is executed you can see the logs associated with the query execution. If your query fails this is a good place to get additional information for troubleshooting. Results . You can view results in sets of 50 by default. There are six sliding views on the right hand side with the following capabilities, which are in context of the tab you are in: Query . This is the default operation, which allows you to write and edit SQL. Settings . This allows you to set properties globally or associated with an individual query. Data Visualization . Allows you to visualize your numeric data through different charts. Visual Explain . This will generate an explain for the query. This will also show the progress of the query. TEZ . If you use TEZ as the query execution engine then you can view the DAG associated with the query. This integrates the TEZ User View so you can check for correctness and helps with performance tuning by visualizing the TEZ jobs associated with a SQL query. Notifications . This is how to get feedback on query execution. The Apache Hive project provides a data warehouse view of the data in HDFS. Using a SQL dialect, HiveQL (HQL), Hive lets you create summarizations of your data and perform ad-hoc queries and analysis of large datasets in the Hadoop cluster. The overall approach with Hive is to project a table structure on the dataset and then manipulate it with SQL. The notion of projecting a table structure on a file is often referred to as Schema-On-Read. Since you are using data in HDFS, your operations can be scaled across all the datanodes and you can manipulate huge datasets. 4.4 Introduction: Apache Pig MapReduce allows allows you to specify map and reduce functions, but working out how to fit your data processing into this pattern may sometimes require you to write multiple MapReduce stages. With Pig, data structures are much richer and the transformations you can apply to data are much more powerful. 4.4.1 Goals of this Module Understanding Apache Pig Understanding Apache Pig on Tez Understanding Ambari Pig User Views on Hortonworks Sandbox Apache Pig allows Apache Hadoop users to write complex MapReduce transformations using a simple scripting language called Pig Latin. Pig translates the Pig Latin script into MapReduce so that it can be executed within YARN for access to a single dataset stored in the Hadoop Distributed File System (HDFS). Pig was designed for performing a long series of data operations, making it ideal for three categories of Big Data jobs: Whatever the use case, Pig will be: Lab 2 - Hive and Data ETL Introduction In this tutorial, you will be introduced to Apache( TM ) Hive. In the earlier section, we covered how to load data into HDFS. So now you have geolocation and trucks files stored in HDFS as csv files. In order to use this data in Hive, we will guide you on how to create a table and how to move data into a Hive warehouse, from where it can be queried. We will analyze this data using SQL queries in Hive User Views and store it as ORC. We will also walk through Apache Tez and how a DAG is created when you specify Tez as execution engine for Hive. Mari mulai. Pre-Requisites The tutorial is a part of a series of hands on tutorials to get you started on HDP using the Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial. Apache Hive Apache Hive provides SQL interface to query data stored in various databases and files systems that integrate with Hadoop. Hive enables analysts familiar with SQL to run queries on large volumes of data. Hive has three main functions: data summarization, query and analysis. Hive provides tools that enable easy data extraction, transformation and loading (ETL). Step 2.1: Become Familiar with Ambari Hive View Apache Hive presents a relational view of data in HDFS. Hive can represent data in a tabular format managed by Hive or just stored in HDFS irrespective in the file format their data is stored in. Hive can query data from RCFile format, text files, ORC, JSON, parquet, sequence files and many of other formats in a tabular view. Through the use of SQL you can view your data as a table and create queries like you would in an RDBMS. To make it easy to interact with Hive we use a tool in the Hortonworks Sandbox called the Ambari Hive View. Ambari Hive View provides an interactive interface to Hive. We can create, edit, save and run queries, and have Hive evaluate them for us using a series of MapReduce jobs or Tez jobs. Let8217s now open the Ambari Hive View and get introduced to the environment. Go to the 9 square Ambari User View icon and select Hive View: The Ambari Hive View looks like the following: Now let8217s take a closer look at the SQL editing capabilities in the Hive View: There are five tabs to interact with SQL: Query . This is the interface shown above and the primary interface to write, edit and execute new SQL statements Saved Queries . You can save your favorite queries and quickly have access to them to rerun or edit. History . This allows you to look at past queries or currently running queries to view, edit and rerun. It also allows you to see all SQL queries you have authority to view. For example, if you are an operator and an analyst needs help with a query, then the Hadoop operator can use the History feature to see the query that was sent from the reporting tool. UDFs . Allows you to define UDF interfaces and associated classes so you can access them from the SQL editor. Upload Table . Allows you to upload your hive query tables to your preferred database and appears instantly in the Query Editor for execution. Database Explorer: The Database Explorer helps you navigate your database objects. You can either search for a database object in the Search tables dialog box, or you can navigate through Database - gt Table - gt Columns in the navigation pane. Query Editor: The principal pane to write and edit SQL statements. This editor includes content assist via CTRL Space to help you build queries. Content assist helps you with SQL syntax and table objects. Once you have created your SQL statement you have 4 options: Execute . This runs the SQL statement. Explain . This provides you a visual plan, from the Hive optimizer, of how the SQL statement will be executed. Save as . Allows you to persist your queries into your list of saved queries. Kill Session . Terminates the SQL statement. When the query is executed you can see the Logs or the actual query results. Logs Tab: When the query is executed you can see the logs associated with the query execution. If your query fails this is a good place to get additional information for troubleshooting. Results Tab . You can view results in sets of 50 by default. There are five sliding views on the right hand side with the following capabilities, which are in context of the tab you are in: Query . This is the default operation, which allows you to write and edit SQL. Settings . This allows you to set properties globally or associated with an individual query. Data Visualization . Allows you to visualize your numeric data through different charts. Visual Explain . This will generate an explain for the query. This will also show the progress of the query. TEZ . If you use TEZ as the query execution engine then you can view the DAG associated with the query. This integrates the TEZ User View so you can check for correctness and helps with performance tuning by visualizing the TEZ jobs associated with a SQL query. Notifications . This is how to get feedback on query execution. Take a few minutes to explore the various Hive View features. 2.1.1 Set hive. execution. engine as Tez A feature we will configure before we run our hive queries is to set the hive execution engine as Tez. You can try map reduce if you like. We will use Tez in this tutorial. 1. Click on the gear in the sidebar referred to as number 6 in the interface above. 2. Click on the dropdown menu, choose hive. execution. engine and set the value as tez. Now we are ready to run our queries for this tutorial. Step 2.2: Define a Hive Table Now that you are familiar with the Hive View, let8217s create and load tables for the geolocation and trucks data. In this section we will learn how to use the Ambari Hive View to create two tables: geolocation and trucking using the Hive View Upload Table tab. The Upload Table tab provides the following key options: choose input file type, storage options (i. e. Apache ORC) and set first row as header. Here is a visual representation of the table and load creation process accomplish in the next few steps.: 2.2.1 Create and load Trucks table For Staging Initial Load Navigate and select the Upload Table of the Ambari Hive View. Then select the Upload from HDFS radio button, enter the HDFS path usermariadevdatatrucks. csv and click the Preview button: You should see a similar dialog: Note that the first row contains the names of the columns. Fortunately the Upload Table tab has a feature to specify the first row as a header for the column names. Press the Gear Button next to the File type pull down menu, shown above, to file type customization window. Then check the checkbox for the Is first row header and hit the close button. You should now see a similar dialog box with the names of the header columns as the names of the columns: Once you have finished setting all the various properties select the Upload Table button to start the create and load table process. Before reviewing what is happening behind the covers in the Upload Progress let8217s learn learn more about Hive File Formats. 2.2.2: Define an ORC Table in Hive Create table using Apache ORC file format Introducing Apache ORC is a fast columnar storage file format for Hadoop workloads. The Optimized Row Columnar (new Apache ORC project ) file format provides a highly efficient way to store Hive data. It was designed to overcome limitations of the other Hive file formats. Using ORC files improves performance when Hive is reading, writing, and processing data. To use the ORC format, specify ORC as the file format when creating the table. Here is an example:: Similar style create statements are used with the temporary tables used in the Upload Tables tab. 2.2.3: Review Upload Table Progress Steps Initially the trucks. csv table is created and loaded into a temporary table. The temporary table is used to create and load data in ORC format using syntax explained in previous step. Once the data is loaded into final table the temporary tables are deleted. NOTE: The temporary table names are random set of characters and not the names in the illustration above. You can review the SQL statements issued by selecting the History tab and clicking on the 4 Internal Job that were executed as a result of using the Upload Table tab. 2.2.4 Create and Load Geolocation Table Repeat the steps above with the geolocation. csv file to create and load the geolocation table using the ORC file format. 2.2.5 Hive Create Table Statement Let8217s review some aspects of the CREATE TABLE statements generated and issued above. If you have an SQL background this statement should seem very familiar except for the last 3 lines after the columns definition: The ROW FORMAT clause specifies each row is terminated by the new line character. The FIELDS TERMINATED BY clause specifies that the fields associated with the table (in our case, the two csv files) are to be delimited by a comma. The STORED AS clause specifies that the table will be stored in the TEXTFILE format. NOTE: For details on these clauses consult the Apache Hive Language Manual . 2.2.6 Verify New Tables Exist To verify the tables were defined successfully, click the refresh icon in the Database Explorer. Under Databases, click default database to expand the list of table and the new tables should appear: 2.2.7 Sample Data from the trucks table Click on the Load sample data icon to generate and execute a select SQL statement to query the table for a 100 rows. You can have multiple SQL statements within each editor worksheet, but each statement needs to be separated by a semicolon 82208221 . If you have multiple statements within a worksheet but you only want to run one of them just highlight the statement you want to run and then click the Execute button. A few additional commands to explore tables: show tables 8211 List the tables created in the database by looking up the list of tables from the metadata stored in HCatalogdescribe describe 8211 Provides a list of columns for a particular table (ie describe geolocationstage ) show create 8211 Provides the DDL to recreate a table (ie show create table geolocationstage ) describe formatted 8211 Explore additional metadata about the table. For example you can verify geolocation is an ORC Table, execute the following query: Scroll down to the bottom of the Results tab and you will see a section labeled Storage Information. The output should look like: By default, when you create a table in Hive, a directory with the same name gets created in the appshivewarehouse folder in HDFS. Using the Ambari Files View, navigate to the appshivewarehouse folder. You should see both a geolocation and trucks directory: NOTE: The definition of a Hive table and its associated metadata (i. e. the directory the data is stored in, the file format, what Hive properties are set, etc.) are stored in the Hive metastore, which on the Sandbox is a MySQL database. 2.2.8 Rename Query Editor Worksheet Notice the tab of your new Worksheet is labeled trucks sample data . Double-click on the worksheet tab to rename the label to 8220sample truck data8221. Now save this worksheet by clicking the button. 2.2.9 Command Line Approach: Populate Hive Table with Data The following Hive command can be used to LOAD data into existing table from the command line If you would run the above commands and navigate to the usermariadevdata folder. You would of notice the folder is empty The LOAD DATA INPATH command moved the trucks. csv file from the usermariadevdata folder to the appshivewarehousetrucksstage folder . 2.2.10 Beeline 8211 Command Shell If you want to try running some of these commands from the the command line you can use the Beeline Shell. Beeline uses a JDBC connection to connect to HiveServer2. Follow the following steps from your shell in the box (or putty if using Windows): i. Local Sandbox VM Open up shell in the box to ssh into HDP with iii. beeline Starts Beeline shell and now you can enter commands and SQL iv. quit Exits out of the Beeline shell. What did you notice about performance after running hive queries from shell Queries using the shell run faster because hive runs the query directory in hadoop whereas in Ambari Hive View, the query must be accepted by a rest server before it can submitted to hadoop. You can get more information on the Beeline from the Hive Wiki . Beeline is based on SQLLine . Step 2.3: Explore Hive Settings on Ambari Dashboard 2.3.1 Open Ambari Dashboard in New Tab Click on the Dashboard tab to start exploring the Ambari Dashboard. 2.3.2 Become Familiar with Hive Settings Go to the Hive page then select the Configs tab then click on Settings tab : Once you click on the Hive page you should see a page similar to above: Scroll down to the Optimization Settings : In the above screenshot we can see: Tez is set as the optimization engine Cost Based Optimizer (CBO) is turned on This shows the HDP 2.5 Ambari Smart Configurations . which simplifies setting configurations Hadoop is configured by a collection of XML files . In early versions of Hadoop, operators would need to do XML editing to change settings . There was no default versioning. Early Ambari interfaces made it easier to change values by showing the settings page with dialog boxes for the various settings and allowing you to edit them. However, you needed to know what needed to go into the field and understand the range of values. Now with Smart Configurations you can toggle binary features and use the slider bars with settings that have ranges. By default the key configurations are displayed on the first page. If the setting you are looking for is not on this page you can find additional settings in the Advanced tab: For example, if we wanted to improve SQL performance . we can use the new Hive vectorization features . These settings can be found and enabled by following these steps: Click on the Advanced tab and scroll to find the property Or, start typing in the property into the property search field and then this would filter the setting you scroll for. As you can see from the green circle above, the Enable Vectorization and Map Vectorization is turned on already. Some key resources to learn more about vectorization and some of the key settings in Hive tuning: Step 2.4: Analyze the Trucks Data Next we will be using Hive, Pig and Zeppelin to analyze derived data from the geolocation and trucks tables. The business objective is to better understand the risk the company is under from fatigue of drivers, over-used trucks, and the impact of various trucking events on risk. In order to accomplish this, we will apply a series of transformations to the source data, mostly though SQL, and use Pig or Spark to calculate risk. In the last lab on Data Visualization, we will be using Zeppelin to generate a series of charts to better understand risk . Let8217s get started with the first transformation. We want to calculate the miles per gallon for each truck . We will start with our truck data table . We need to sum up all the miles and gas columns on a per truck basis . Hive has a series of functions that can be used to reformat a table. The keyword LATERAL VIEW is how we invoke things. The stack function allows us to restructure the data into 3 columns labeled rdate, gas and mile (ex: 8216june138217, june13miles, june13gas) that make up a maximum of 54 rows. We pick truckid, driverid, rdate, miles, gas from our original table and add a calculated column for mpg (milesgas). And then we will calculate average mileage . 2.4.1 Create Table truckmileage From Existing Trucking Data Using the Ambari Hive User View, execute the following query: 2.4.2 Explore a sampling of the data in the truckmileage table To view the data generated by the script, click Load Sample Data icon in the Database Explorer next to truckmileage. After clicking the next button once, you should see a table that lists each trip made by a truck and driver : 2.4.3 Use the Content Assist to build a query 1. Create a new SQL Worksheet . 2. Start typing in the SELECT SQL command . but only enter the first two letters: 3. Press Ctrlspace to view the following content assist pop-up dialog window: NOTE: Notice content assist shows you some options that start with an 8220SE8221. These shortcuts will be great for when you write a lot of custom query code. 4. Type in the following query, using Ctrlspace throughout your typing so that you can get an idea of what content assist can do and how it works: 5. Click the 8220 Save as 8221 button to save the query as 8220 average mpg 8220: 6. Notice your query now shows up in the list of 8220 Saved Queries 8220, which is one of the tabs at the top of the Hive User View. 7. Execute the 8220 average mpg 8221 query and view its results. 2.4.4 Explore Explain Features of the Hive Query Editor 1. Now let8217s explore the various explain features to better understand the execution of a query . Text Explain, Visual Explain and Tez Explain. Click on the Explain button: 2. You shall receive similar image as below. The following output displays the flow of the resulting Tez job: 3. To see the Visual Explain, click on the Visual Explain icon on the right tabs. This is a much more readable summary of the explain plan: 2.4.5 Explore TEZ 1. If you click on TEZ View from Ambari Views at the top, you can see DAG details associated with the previous hive and pig jobs. 2. Select the first DAG as it represents the last job that was executed. 3. There are seven tabs at the top left please take a few minutes to explore the various tabs and then click on the Graphical View tab and hover over one of the nodes with your cursor to get more details on the processing in that node. 4. Let8217s also view Vertex Swimlane . This feature helps with troubleshooting of TEZ jobs. As you will see in the image there is a graph for Map 1 and Reduce 2. These graphs are timelines for when events happened. Hover over red or blue line to view a event tooltip. Bubble represents an event Vertex represents the solid line, timeline of events For map1, the tooltip shows that the events vertex started and vertex initialize occur simultaneously: For Reducer 2, the tooltip shows that the events vertex started and initialize share 1 second difference on execution time. When you look at the tasks started for and finished (thick line) for Map1 compared to Reducer2 in the graph, what do you notice Map1 starts and completes before Reducer2. 5. Go back to the Hive View and save the query by clicking the Save as button. 2.4.6 Create Table truck avgmileage From Existing trucksmileage Data Note: Verify that the hive. execution. engine is under tez . Persist these results into a table . this is a fairly common pattern in Hive and it is called Create Table As Select (CTAS ). Paste the following script into a new Worksheet, then click the Execute button: 2.4.7 Load Sample Data of avgmileage To view the data generated by the script, click Load sample data icon in the Database Explorer next to avgmileage. You see our table is now a list of each trip made by a truck. Step 2.5: Define Table Schema Now we have refined the truck data to get the average mpg for each truck ( avgmileage table ). The next task is to compute the risk factor for each driver which is the total miles drivenabnormal events . We can get the event information from the geolocation table. If we look at the truckmileage table, we have the driverid and the number of miles for each trip. To get the total miles for each driver, we can group those records by driverid and then sum the miles. 2.5.1 Create Table DriverMileage from Existing truckmileage Data We will start by creating a table named drivermileage that is created from a query of the columns we want from truckmileage. The following query groups the records by driverid and sums the miles in the select statement. Execute the query below in a new Worksheet: Note: This table is essential for both Pig Latin and Spark jobs. 2.5.2 View Data Generated by Query To view data, click the Load sample data icon in the Database Explorer next to drivermileage. The results should look like: 2.5.3 Explore Hive Data Visualization This tool enables us to transform our hive data into a visualization that makes data easier to understand. Let8217s explore the Hive data explorer to see a variety of different data visualizations. We8217ll use these examples to build a custom visualization, which will show the user 1. Issue a query by (1)clicking on the geolocation Load sample data icon and then (2) select the Hive View visualization tab 2. Click on Data Explorer tab and quickly explore the distribution of the data from the query. 3. You can also explore some custom Data Visualizations by click the tab and then dragging 2 columns into the Positional fields. Note that you can not save these graphs. Explore the following HCC article for more info. Congratulations Let8217s summarize some Hive commands we learned to process, filter and manipulate the geolocation and trucks data. We now can create Hive tables with CREATE TABLE and load data into them using the LOAD DATA INPATH command. Additionally, we learned how to change the file format of the tables to ORC, so hive is more efficient at reading, writing and processing this data. We learned to grab parameters from our existing table using SELECT FROM to create a new filtered table. Suggested Readings Augment your hive foundation with the following resources: Tutorial QampA and Reporting Issues If you need help or have questions with this tutorial, please first check HCC for existing Answers to questions on this tutorial using the Find Answers button. If you don8217t find your answer you can post a new HCC question for this tutorial using the Ask Questions button. Tutorial Name: Hello HDP An Introduction to Hadoop with Hive and Pig If the tutorial has multiple labs please indicate which lab your question corresponds to. Please provide any feedback related to that lab. All Hortonworks, partner and community tutorials are posted in the Hortonworks github and can be contributed via the Hortonworks Tutorial Contribution Guide. If you are certain there is an issue or bug with the tutorial, please create an issue on the repository and we will do our best to resolve it Lab 3 - Pig Risk Factor Analysis Introduction In this tutorial, you will be introduced to Apache Pig. In the earlier section of lab, you learned how to load data into HDFS and then manipulate it using Hive. We are using the Truck sensor data to better understand risk associated with every driver. This section will teach you to compute risk using Apache Pig . Pre-Requisites The tutorial is a part of series of hands on tutorial to get you started on HDP using Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial. Hortonworks Sandbox Learning the Ropes of the Hortonworks Sandbox Lab 1: Load sensor data into HDFS Lab 2: Data Manipulation with Apache Hive Allow yourself around one hour to complete this tutorial. Pig Basics Pig is a high-level scripting language used with Apache Hadoop. Pig enables data workers to write complex data transformations without knowing Java. Pig8217s simple SQL-like scripting language is called Pig Latin, and appeals to developers already familiar with scripting languages and SQL. Pig is complete, so you can do all required data manipulations in Apache Hadoop with Pig. Through the User Defined Functions (UDF) facility in Pig, Pig can invoke code in many languages like JRuby, Jython and Java . You can also embed Pig scripts in other languages. The result is that you can use Pig as a component to build larger and more complex applications that tackle real business problems. Pig works with data from many sources, including structured and unstructured data . and store the results into the Hadoop Data File System. Pig scripts are translated into a series of MapReduce jobs that are run on the Apache Hadoop cluster . Create Table riskfactor from Existing trucksmileage Data Next, you will use Pig to compute the risk factor of each driver. Before we can run the Pig code . the table must already exist in Hive to satisfy one of the requirements for the HCatStorer() class . The Pig code expects the following structure for a table named riskfactor . Execute the following DDL command: Verify Table riskfactor was Created Successfully Verify the riskfactor table was created successfully. It will be empty now, but you will populate it from a Pig script. You are now ready to compute the risk factor using Pig. Let8217s take a look at Pig and how to execute Pig scripts from within Ambari. Step 3.1: Create Pig Script In this phase of the tutorial, we create and run a Pig script. We will use the Ambari Pig View. Let8217s get started 3.1.1 Log in to Ambari Pig User Views To get to the Ambari Pig View, click on the Ambari Views icon at top right and select Pig : This will bring up the Ambari Pig User View interface. Your Pig View does not have any scripts to display, so it will look like the following: On the left is a list of your scripts, and on the right is a composition box for writing scripts. A special interface feature is the Pig helper located below the name of your script file. The Pig helper provides us with templates for the statements, functions, IO statements, HCatLoader() and Python user defined functions. At the very bottom are status areas that will show the results of our script and log files. The following screenshot shows and describes the various components and features of the Pig View: 3.1.2 Create a New Script Let8217s enter a Pig script. Click the New Script button in the upper-right corner of the view: Name the script riskfactor. pig . then click the Create button: 3.1.3 Load Data in Pig using Hcatalog We will use HCatalog to load data into Pig . HCatalog allows us to share schema across tools and users within our Hadoop environment. It also allows us to factor out schema and location information from our queries and scripts and centralize them in a common repository . Since it is in HCatalog we can use the HCatLoader() function . Pig allows us to give the table a name or alias and not have to worry about allocating space and defining the structure. We just have to worry about how we are processing the table. We can use the Pig helper located below the name of your script file to give us a template for the line. Click on Pig helper - gt HCatalog-gtload template The entry TABLE is highlighted in red for us. Type the name of the table which is geolocation. Remember to add the a before the template. This saves the results into a. Note the 82168217 has to have a space before and after it. Our completed line of code will look like: The script above loads data, in our case, from a file named geolocation using the HCatLoader() function. Copy-and-paste the above Pig code into the riskfactor. pig window. 3.1.4 Filter your data set The next step is to select a subset of the records . so we have the records of drivers for which the event is not normal . To do this in Pig we use the Filter operator . We instruct Pig to Filter our table and keep all records where event 8221normal8221 and store this in b. With this one simple statement, Pig will look at each record in the table and filter out all the ones that do not meet our criteria. We can use Pig Help again by clicking on Pig helper-gtRelational Operators-gtFILTER template We can replace VAR with 8220a8221 (hint: tab jumps you to the next field) Our COND is 8220 event 8217normal8217 8221 (note: single quotes are needed around normal and don8217t forget the trailing semi-colon) Complete line of code will look like: Copy-and-paste the above Pig code into the riskfactor. pig window. 3.1.5 Iterate your data set Since we have the right set of records, let8217s iterate through them. We use the 8220foreach8221 operator on the grouped data to iterate through all the records. We would also like to know the number of non normal events associated with a driver . so to achieve this we add 821618217 to every row in the data set. Pig helper - gtRelational Operators-gtFOREACH template will get us the code Our DATA is b and the second NEWDATA is 8220 driverid, event,(int) 821618217 as occurance 8220 Complete line of code will look like: Copy-and-paste the above Pig code into the riskfactor. pig window: 3.1.6 Calculate the total non normal events for each driver The group statement is important because it groups the records by one or more relations . In our case, we want to group by driver id and iterate over each row again to sum the non normal events. Pig helper - gtRelational Operators-gtGROUP VAR BY VAR template will get us the code First VAR takes 8220c8221 and second VAR takes 8220 driverid 8220 Complete line of code will look like: Copy-and-paste the above Pig code into the riskfactor. pig window. Next use Foreach statement again to add the occurance. 3.1.7 Load drivermileage Table and Perform a Join Operation In this section, we will load drivermileage table into Pig using Hcatlog and perform a join operation on driverid. The resulting data set will give us total miles and total non normal events for a particular driver. Load drivermileage using HcatLoader() Pig helper - gtRelational Operators-gtJOIN VAR BY template will get us the code Replace VAR by 8216 e 8216 and after BY put 8216 driverid, g by driverid 8216 Complete line of code will look like: Copy-and-paste the above two Pig codes into the riskfactor. pig window. 3.1.8 Compute Driver Risk factor In this section, we will associate a driver risk factor with every driver. To calculate driver risk factor . divide total miles travelled by non normal event occurrences . We will use Foreach statement again to compute driver risk factor for each driver. Use the following code and paste it into your Pig script. As a final step, store the data into a table using Hcatalog . Here is the final code and what it will look like once you paste it into the editor. Geolocation has data stored in ORC format Save the file riskfactor. pig by clicking the Save button in the left-hand column. Step 3.2: Quick Recap Before we execute the code, let8217s review the code again: The line a loads the geolocation table from HCatalog. The line b filters out all the rows where the event is not 8216Normal8217. Then we add a column called occurrence and assign it a value of 1. We then group the records by driverid and sum up the occurrences for each driver. At this point we need the miles driven by each driver, so we load the table we created using Hive. To get our final result, we join by the driverid the count of events in e with the mileage data in g. Now it is real simple to calculate the risk factor by dividing the miles driven by the number of events You need to configure the Pig Editor to use HCatalog so that the Pig script can load the proper libraries. In the Pig arguments text box, enter - useHCatalog and click the Add button: Note this argument is case sensitive . It should be typed exactly 8220-useHCatalog8221. Step 3.3: Execute Pig Script on Tez 3.3.1 Execute Pig Script Click Execute on Tez checkbox and finally hit the blue Execute button to submit the job. Pig job will be submitted to the cluster. This will generate a new tab with a status of the running of the Pig job and at the top you will find a progress bar that shows the job status. 3.3.2 View Results Section Wait for the job to complete. The output of the job is displayed in the Results section. Notice your script does not output any result it stores the result into a Hive table so your Results section will be empty. Click on the Logs dropdown menu to see what happened when your script ran. Errors will appear here. 3.3.3 View Logs section (Debugging Practice) Why are Logs important The logs section is helpful when debugging code after expected output does not happen. For instance, say in the next section, we load the sample data from our riskfactor table and nothing appears. Logs will tell us why the job failed. A common issue that could happen is that pig does not successfully read data from the geolocation table or drivermileage table. Therefore, we can effectively address the issue. Let8217s verify pig read from these tables successfully and stored the data into our riskfactor table. You should receive similar output: What results do our logs show us about our Pig Script Read 8000 records from our geolocation table Read 100 records from our drivermileage table Stored 99 records into our riskfactor table Can you think of scenarios in which these results if different would help us debug our script For example, say 0 records were read from the geolocation table, how would you solve the problem 3.3.4 Verify Pig Script Successfully Populated Hive Table Go back to the Ambari Hive User View and browse the data in the riskfactor table to verify that your Pig job successfully populated this table. Here is what is should look like: At this point we now have our truck miles per gallon table and our risk factor table. The next step is to pull this data into Excel to create the charts for the visualization step. Congratulations Let8217s summarize the Pig commands we learned in this tutorial to compute risk factor analysis on the geolocation and truck data. We learned to use Pig to access the data from Hive using the LOAD HCatLoader() script. Therefore, we were able to perform the filter . foreach . Kelompok. join . and store HCatStorer() scripts to manipulate, transform and process this data. To review these bold pig latin operators, view the Pig Latin Basics. which contains documentation on each operator. Suggested Readings Strengthen your foundation of pig latin and reinforce why this scripting platform is benficial for processing and analyzing massive data sets with these resources: Tutorial QampA and Reporting Issues If you need help or have questions with this tutorial, please first check HCC for existing Answers to questions on this tutorial using the Find Answers button. If you don8217t find your answer you can post a new HCC question for this tutorial using the Ask Questions button. Tutorial Name: Hello HDP An Introduction to Hadoop with Hive and Pig If the tutorial has multiple labs please indicate which lab your question corresponds to. Please provide any feedback related to that lab. All Hortonworks, partner and community tutorials are posted in the Hortonworks github and can be contributed via the Hortonworks Tutorial Contribution Guide. If you are certain there is an issue or bug with the tutorial, please create an issue on the repository and we will do our best to resolve it Using Apache Spark to compute Driver Risk Factor Note: This lab is optional and produces the same result as in Lab 3. You may continue on to the next lab if you wish. Introduction In this tutorial we will introduce Apache Spark. In the earlier section of the lab you have learned how to load data into HDFS and then manipulate it using Hive. We are using the Truck sensor data to better understand risk associated with every driver. This section will teach you how to compute risk using Apache spark. Pre-Requisites This tutorial is a part of a series of hands on tutorials to get you started on HDP using the Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial. Hortonworks Sandbox Learning the Ropes of the Hortonworks Sandbox Lab 1: Loading sensor data into HDFS Lab 2: Data Manipulation with Apache Hive Allow yourself around one hour to complete this tutorial. Background MapReduce has been useful, but the amount of time it takes for the jobs to run can at times be exhaustive. Also, MapReduce jobs only work for a specific set of use cases. There is a need for computing framework that works for a wider set of use cases. Apache Spark was designed to be a fast, general-purpose, easy-to-use computing platform. It extends the MapReduce model and takes it to a whole other level. The speed comes from the in-memory computations. Applications running in memory allow for much faster processing and response. Apache Spark Apache Spark is a fast, in-memory data processing engine with elegant and expressive development APIs in Scala, Java. and Python and R that allow data workers to efficiently execute machine learning algorithms that require fast iterative access to datasets. Spark on Apache Hadoop YARN enables deep integration with Hadoop and other YARN enabled workloads in the enterprise. You can run batch application such as MapReduce types jobs or iterative algorithms that build upon each other. You can also run interactive queries and process streaming data with your application. Spark also provides a number of libraries which you can easily use to expand beyond the basic Spark capabilities such as Machine Learning algorithms, SQL, streaming, and graph processing. Spark runs on Hadoop clusters such as Hadoop YARN or Apache Mesos, or even in a Standalone Mode with its own scheduler. The Sandbox includes both Spark 1.6 and Spark 2.0. Let8217s get started Step 4.1: Configure Spark services using Ambari 1. Log on to Ambari Dashboard as mariadev. At the bottom left corner of the services column, check that Spark and Zeppelin are running. Note: If these services are disabled, start these services. For HDP 2.5 Sandbox Users Activate Livy Server Livy Server is a new feature added to the latest Sandbox HDP Platform and it adds extra security while running our spark jobs from Zeppelin Notebook. For this lab, users that have HDP 2.5 Sandbox can use Livy. 2. Now verify the Spark livy server is running: 3. As you can see our server is down. We need to start it before running spark jobs in Zeppelin. Click on Livy Server. then click on sandbox. hortonworks . Now we let8217s scroll down to livy server. press on the Stopped button and start the server. Press the OK button in the Confirmation window. Livy Server Started: 4. Go back into the Spark Service. Click on Service Actions - gt Turn Off Maintenance Mode . Log out of Ambari. 5. Access Zeppelin at sandbox. hortonworks:9995 through its port number: Refer to Learning the Ropes of Hortonworks Sandbox if you need assistance figuring out your hostname. You should see a Zeppelin Welcome Page: Optionally, if you want to find out how to access the Spark shell to run code on Spark refer to Appendix A . 6. Create a Zeppelin Notebook Click on a Notebook tab at the top left and hit Create new note . Name your notebook Compute Riskfactor with Spark. By the default, the notebook will load Spark Scala API. Step 4.2: Create a HiveContext For improved Hive integration, HDP 2.5 offers ORC file support for Spark. This allows Spark to read data stored in ORC files. Spark can leverage ORC file8217s more efficient columnar storage and predicate pushdown capability for even faster in-memory processing. HiveContext is an instance of the Spark SQL execution engine that integrates with data stored in Hive. The more basic SQLContext provides a subset of the Spark SQL support that does not depend on Hive. It reads the configuration for Hive from hive-site. xml on the classpath. Import sql libraries: If you have gone through Pig section, you have to drop the table riskfactor so that you can populate it again using Spark. Copy and paste the following code into your Zeppelin notebook, then click the play button. Alternatively, press shiftenter to run the code. We will see that there is a table called riskfactor. let us drop that: To verify, let us do show tables again: Now create it back with the same DDL that we executed in the Pig section, Write the following query: We can either run the original spark interpreter or the livy spark interpreter to run spark code. The difference is that livy comes with more security. The default interpreter for spark jobs is spark . Instantiate HiveContext sc stands for Spark Context . SparkContext is the main entry point to everything Spark. It can be used to create RDDs and shared variables on the cluster. When you start up the Spark Shell, the SparkContext is automatically initialized for you with the variable sc . Step 4.3: Create a RDD from HiveContext Spark8217s primary core abstraction is called a Resilient Distributed Dataset or RDD. It is a distributed collection of elements that is parallelized across the cluster. In other words, a RDD is an immutable collection of objects that is partitioned and distributed across multiple physical nodes of a YARN cluster and that can be operated in parallel. There are three methods for creating a RDD: Parallelize an existing collection. This means that the data already resides within Spark and can now be operated on in parallel. Create a RDD by referencing a dataset. This dataset can come from any storage source supported by Hadoop such as HDFS, Cassandra, HBase etc. Create a RDD by transforming an existing RDD to create a new RDD. We will be using the later two methods in our tutorial. RDD Transformations and Actions Typically, RDDs are instantiated by loading data from a shared filesystem, HDFS, HBase, or any data source offering a Hadoop InputFormat on a YARN cluster. Once a RDD is instantiated, you can apply a series of operations. All operations fall into one of two types: transformations or actions . Transformation operations, as the name suggests, create new datasets from an existing RDD and build out the processing DAG that can then be applied on the partitioned dataset across the YARN cluster. Transformations do not return a value. In fact, nothing is evaluated during the definition of these transformation statements. Spark just creates these Direct Acyclic Graphs or DAG, which will only be evaluated at runtime. We call this lazy evaluation. An Action operation, on the other hand, executes a DAG and returns a value. 4.3.1 View List of Tables in Hive Warehouse Use a simple show command to see the list of tables in Hive warehouse. Note: false indicates whether the column requires data. You will notice that the geolocation table and the driver mileage table that we created earlier in an tutorial are already listed in Hive metastore and can be directly queried upon. 4.3.2 Query Tables To Build Spark RDD We will do a simple select query to fetch data from geolocation and drivermileage tables to a spark variable. Getting data into Spark this way also allows to copy table schema to RDD. 4.4 Querying Against a Table 4.4.1 Registering a Temporary Table Now let8217s register a temporary table and use SQL syntax to query against that table. Next, we will perform an iteration and a filter operation. First, we need to filter drivers that have non-normal events associated with them and then count the number for non-normal events for each driver. As stated earlier about RDD transformations, select operation is a RDD transformation and therefore does not return anything. The resulting table will have a count of total non-normal events associated with each driver. Register this filtered table as a temporary table so that subsequent SQL queries can be applied to it. You can view the result by executing an action operation on the RDD. 4.4.2 Perform join Operation In this section we will perform a join operation geolocationtemp2 table has details of drivers and count of their respective non-normal events. drivermileagetemp1 table has details of total miles travelled by each driver. We will join two tables on common column, which in our case is driverid . The resulting data set will give us total miles and total non-normal events for a particular driver. Register this filtered table as a temporary table so that subsequent SQL queries can be applied to it. You can view the result by executing action operation on RDD. 4.4.3 Compute Driver Risk Factor In this section we will associate a driver risk factor with every driver. Driver risk factor will be calculated by dividing total miles travelled by non-normal event occurrences. The resulting data set will give us total miles and total non normal events and what is a risk for a particular driver. Register this filtered table as a temporary table so that subsequent SQL queries can be applied to it. Step 4.5: Load and Save Data into Hive as ORC In this section we store data in a smart ORC (Optimized Row Columnar) format using Spark. ORC is a self-describing type-aware columnar file format designed for Hadoop workloads. It is optimized for large streaming reads and with integrated support for finding required rows fast. Storing data in a columnar format lets the reader read, decompress, and process only the values required for the current query. Because ORC files are type aware, the writer chooses the most appropriate encoding for the type and builds an internal index as the file is persisted. Predicate pushdown uses those indexes to determine which stripes in a file need to be read for a particular query and the row indexes can narrow the search to a particular set of 10,000 rows. ORC supports the complete set of types in Hive, including the complex types: structs, lists, maps, and unions. 4.5.1 Create an ORC table Create a table and store it as ORC. Specifying as orc at the end of the SQL statement below ensures that the Hive table is stored in the ORC format. Note: toDF() creates a DataFrame with columns driverid String, occurance bigin, etc. 4.5.2 Convert data into ORC table Before we load the data into hive table that we created above, we will have to convert our data file into ORC format too. Note: For Spark 1.4.1 and higher, use If you used the above script, skip the following instruction and move to 4.5.3. Note: For Spark 1.3.1, use 4.5.3 Load the data into Hive table using load data command 4.5.4 Create the final table Riskfactor using CTAS 4.5.5 Verify Data Successfully Populated Hive Table in Hive (Check 2) Execute a select query to verify your table has been successfully stored. You can go to Ambari Hive user view to check whether the Hive table you created has the data populated in it. Hive riskfactor table populated Did both tables have the same data up to 10 rows Full Spark Code Review for Lab Import hive and sql libraries Shows tables in the default hive database Select all rows and columns from tables, stores hive script into variable and registers variables as RDD Load first 10 rows from geolocationtemp2, which is the data from drivermileage table Create joined to join 2 tables by the same driverid and register joined as a RDD Load first 10 rows and columns in joined Initialize riskfactorspark and register as an RDD Print the first 10 lines from the riskfactorspark table Create table finalresults in Hive, save it as ORC, load data into it, and then create the final table called riskfactor using CTAS Appendix A: Run Spark Code in the Spark Interactive Shell 1) Open your terminal or putty. SSH into the Sandbox using root as login and hadoop as password. Optionally, if you don8217t have an SSH client installed and configured you can use the built-in web client which can be accessed from here: host:4200 (use the same username and password provided above) 2) Let8217s enter the Spark interactive shell (spark repl). Type the command This will load the default Spark Scala API. Note: Hive comes preconfigured with HDP Sandbox. The coding exercise we just went through can be also completed using a Spark shell. Just as we did in Zeppelin, you can copy and paste the code. Congratulations Let8217s summarize the spark coding skills and knowledge we acquired to compute risk factor associated with every driver. Apache Spark is efficient for computation because of its in-memory data processing engine . We learned how to integrate hive with spark by creating a Hive Context . We used our existing data from Hive to create an RDD . We learned to perform RDD transformations and actions to create new datasets from existing RDDs. These new datasets include filtered, manipulated and processed data. After we computed risk factor . we learned to load and save data into Hive as ORC . Suggested Readings Tutorial QampA and Reporting Issues If you need help or have questions with this tutorial, please first check HCC for existing Answers to questions on this tutorial using the Find Answers button. If you don8217t find your answer you can post a new HCC question for this tutorial using the Ask Questions button. Tutorial Name: Hello HDP An Introduction to Hadoop with Hive and Pig If the tutorial has multiple labs please indicate which lab your question corresponds to. Please provide any feedback related to that lab. All Hortonworks, partner and community tutorials are posted in the Hortonworks github and can be contributed via the Hortonworks Tutorial Contribution Guide. If you are certain there is an issue or bug with the tutorial, please create an issue on the repository and we will do our best to resolve it Lab 5 - Data Reporting With Zeppelin Introduction In this tutorial you will be introduced to Apache Zeppelin. In the earlier section of lab, you learned how to perform data visualization using Excel. This section will teach you to visualize data using Zeppelin. Prerequisites The tutorial is a part of series of hands on tutorial to get you started on HDP using the Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial. Hortonworks Sandbox Learning the Ropes of the Hortonworks Sandbox Lab 1: Load sensor data into HDFS Lab 2: Data Manipulation with Apache Hive Lab 3: Use Pig to compute Driver Risk Factor Lab 4: Use Spark to compute Driver Risk Factor Working Zeppelin installation Allow yourself approximately one hour to complete this tutorial. Apache Zeppelin Apache Zeppelin provides a powerful web-based notebook platform for data analysis and discovery. Behind the scenes it supports Spark distributed contexts as well as other language bindings on top of Spark. In this tutorial we will be using Apache Zeppelin to run SQL queries on our geolocation, trucks, and riskfactor data that we8217ve collected earlier and visualize the result through graphs and charts. NOTE: We can also run queries via various interpreters for the following (but not limited to) spark, hawq and postgresql. Step 5.1: Create a Zeppelin Notebook 5.1.1 Navigate to Zeppelin Notebook 1) Navigate to sandbox. hortonworks:9995 directly to open the Zeppelin interface. 2) Click on create note, name the notebook Driver Risk Factor and a new notebook shall get started. Step 5.2: Execute a Hive Query 5.2.1 Visualize finalresults Data in Tabular Format In the previous Spark and Pig tutorials you already created a table finalresults or riskfactor which gives the risk factor associated with every driver. We will use the data we generated in this table to visualize which drivers have the highest risk factor. We will use the jdbc hive interpreter to write queries in Zeppelin. jdbc by default runs hive. 1) Copy and paste the code below into your Zeppelin note. 2) Click the play button next to 8220ready8221 or 8220finished8221 to run the query in the Zeppelin notebook. Alternative way to run query is 8220shiftenter.8221 Initially, the query will produce the data in tabular format as shown in the screenshot. Step 5.3: Build Charts using Zeppelin 5.3.1 Visualize finalresults Data in Chart Format 1. Iterate through each of the tabs that appear underneath the query. Each one will display a different type of chart depending on the data that is returned in the query. 2. After clicking on a chart, we can view extra advanced settings to tailor the view of the data we want 3. Click settings to open the advanced chart features. 4. To make a chart with riskfactor. driverid and riskfactor. riskfactor SUM. drag the table relations into the boxes as shown in the image below. 5. You should now see an image like the one below. 6. If you hover on the peaks, each will give the driverid and riskfactor. 7. Try experimenting with the different types of charts as well as dragging and dropping the different table fields to see what kind of results you can obtain. 8. Let8217 try a different query to find which cities and states contain the drivers with the highest riskfactors. 9. Run the query above using the keyboard shortcut ShiftEnter. You should eventually end up with the results in a table below. 10. After changing a few of the settings we can figure out which of the cities have the high risk factors. Try changing the chart settings by clicking the scatterplot icon. Then make sure that the keys a. driverid is within the xAxis field, a. riskfactor is in the yAxis field, and b. city is in the group field. The chart should look similar to the following. The graph shows that driver id number A39 has a high risk factor of 652417 and drives in Santa Maria. Now that we know how to use Apache Zeppelin to obtain and visualize our data, we can use the skills we8217ve learned from our Hive, Pig, and Spark labs, as well and apply them to new kinds of data to try to make better sense and meaning from the numbers Suggested Readings Tutorial QampA and Reporting Issues If you need help or have questions with this tutorial, please first check HCC for existing Answers to questions on this tutorial using the Find Answers button. If you don8217t find your answer you can post a new HCC question for this tutorial using the Ask Questions button. Tutorial Name: Hello HDP An Introduction to Hadoop with Hive and Pig If the tutorial has multiple labs please indicate which lab your question corresponds to. Please provide any feedback related to that lab. All Hortonworks, partner and community tutorials are posted in the Hortonworks github and can be contributed via the Hortonworks Tutorial Contribution Guide. If you are certain there is an issue or bug with the tutorial, please create an issue on the repository and we will do our best to resolve it Lab 6: Data Reporting with Excel Introduction This step is optional as it requires you to have Excel and Power View, however feel free to connect from any reporting tool to do a similar exercise. In this section, we will use Microsoft Excel Professional Plus 2013 to access the refined data. We will be using the ODBC connection. Prerequisites The tutorial is a part of series of hands on tutorial to get you started on HDP using Hortonworks sandbox. Please ensure you complete the prerequisites before proceeding with this tutorial. Lab 0: (Hortonworks sandbox set up) Lab 1: Loading sensor data into HDFS Lab 2: Data Manipulation with Apache Hive Lab 3: Use Pig to compute Driver Risk Factor Lab 4: Use Spark to compute Driver Risk Factor Please configure ODBC drivers on your system with the help of following tutorial: Installing and Configuring the Hortonworks ODBC driver on Windows 7 Allow yourself around half an hour to complete this tutorial. Step 6.b.1: Access the Refined Data with Microsoft Excel The Hive ODBC driver can be found at the Hortonworks Add-on page. For Windows ODBC driver setup follow these instructions. Open the ODBC connection manager and open the connection you setup up. It should look like this. 1) Open a new blank workbook. Select Data gt From Other Sources gt From Microsoft Query . 2) On the Choose Data Source pop-up, select the Hortonworks ODBC data source you installed previously, then click OK . The Hortonworks ODBC driver enables you to access Hortonworks data with Excel and other Business Intelligence (BI) applications that support ODBC. We will import the avgmileage table. 3) Accept the defaults for everything and click through till you hit the Finish button. After you click on Finish, Excel will send the data request over to Hadoop. It will take awhile for this to happen. When the data is returned it will ask you to place the data in the workbook. We want to be in cell A1 like this. 4) The data is placed you will see the avgmileage table imported into your spreadsheet. Step 6.b.2: Visualize Data with Microsoft Excel 1) So now we are going to insert a Power View report. Follow this link to set up the Power View Report if you do not have it. This will create a new tab in your workbook with the data inserted in the Power View page. 2) Select the design tab at the top and then select a column chart and use the stacked column version in the drop down menu. This will give you a bar chart. Grab the lower right of the chart and stretch it out to the full pane. Close the filter tab and the chart will expand and look like this. 3) So to finish off the tutorial I am going to create a map of the events reported in the geolocation table. I will show you how you can build up the queries and create a map of the data on an ad hoc basis. 4) For a map we need location information and a data point. Looking at the geolocation table I will simply plot the location of each of the events. I will need the driverid, city and state columns from this table. We know that the select statement will let me extract these columns. So to start off I can just create the select query in the Query Editor. 5) Query subset of geolocation columns 6) After I execute the query I see what results are returned. In a more complex query you can easily make changes to the query at this point till you get the right results. So the results I get back look like this. 7) Since my results look fine I now need to capture the result in a table. So I will use the select statement as part of my CTAS (create table select as) pattern. I will call the table events and the query now looks like this. Create table avgmileage from existing trucksmileage data 8) I can execute the query and the table events gets created. As we saw earlier I can go to Excel and import the table into a blank worksheet. The imported data will look like this. 9) Now I can insert the PowerView tab in the Excel workbook. To get a map I just select the Design tab at the top and select the Map button in the menu bar. 10) Make sure you have a network connection because Power View using Bing to do the geocoding which translates the city and state columns into map coordinates. If we just want to see where events took place we can uncheck the driverid. The finished map looks like this. We8217ve shown how the Hortonworks Data Platform (HDP) can store and analyze geolocation data. In addition I have shown you a few techniques on building your own queries. You can easily plot risk factor and miles per gallon as bar charts. I showed you the basics of creating maps. A good next step is to only plot certain types of events. Using the pattern I gave you it is pretty straightforward to extract the data and visualize it in Excel. Next Steps: Try These Congratulations on finishing a comprehensive series on Hadoop and HDP. By now you should have a good understanding on fundamentals of Hadoop and its related ecosystem such as Map Reduce, YARN, HDFS, Hive, Pig and Spark. As a Hadoop practitioner you can choose three basic personas to build upon your skill: Case Studies: Learn more about Hadoop through these case studies: Suggested Readings Tutorial QampA and Reporting Issues If you need help or have questions with this tutorial, please first check HCC for existing Answers to questions on this tutorial using the Find Answers button. If you don8217t find your answer you can post a new HCC question for this tutorial using the Ask Questions button. Tutorial Name: Hello HDP An Introduction to Hadoop with Hive and Pig If the tutorial has multiple labs please indicate which lab your question corresponds to. Please provide any feedback related to that lab. All Hortonworks, partner and community tutorials are posted in the Hortonworks github and can be contributed via the Hortonworks Tutorial Contribution Guide. If you are certain there is an issue or bug with the tutorial, please create an issue on the repository and we will do our best to resolve it

5 comments: