Главная » Просмотр файлов » Tom White - Hadoop The Definitive Guide_ 4 edition - 2015

Tom White - Hadoop The Definitive Guide_ 4 edition - 2015 (811394), страница 93

Файл №811394 Tom White - Hadoop The Definitive Guide_ 4 edition - 2015 (Tom White - Hadoop The Definitive Guide_ 4 edition - 2015.pdf) 93 страницаTom White - Hadoop The Definitive Guide_ 4 edition - 2015 (811394) страница 932020-08-25СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 93)

For example,PigStorage, which loads data from delimited text files, can store data in the sameformat.Pig comes with a collection of built-in functions, a selection of which are listed inTable 16-7. The complete list of built-in functions, which includes a large number ofstandard math, string, date/time, and collection functions, can be found in the docu‐mentation for each Pig release.Table 16-7. A selection of Pig’s built-in functionsCategoryFunctionDescriptionEvalAVGCalculates the average (mean) value of entries in a bag.CONCATConcatenates byte arrays or character arrays together.COUNTCalculates the number of non-null entries in a bag.COUNT_STARCalculates the number of entries in a bag, including those that are null.DIFFCalculates the set difference of two bags.

If the two arguments are not bags,returns a bag containing both if they are equal; otherwise, returns an emptybag.MAXCalculates the maximum value of entries in a bag.MINCalculates the minimum value of entries in a bag.SIZECalculates the size of a type. The size of numeric types is always 1; for characterarrays, it is the number of characters; for byte arrays, the number of bytes; andfor containers (tuple, bag, map), it is the number of entries.SUMCalculates the sum of the values of entries in a bag.TOBAGConverts one or more expressions to individual tuples, which are then put in abag.

A synonym for ().TOKENIZETokenizes a character array into a bag of its constituent words.TOMAPConverts an even number of expressions to a map of key-value pairs. A synonymfor [].TOPCalculates the top n tuples in a bag.TOTUPLEConverts one or more expressions to a tuple. A synonym for {}.IsEmptyTests whether a bag or map is empty.FilterLoad/Store PigStorageLoads or stores relations using a field-delimited text format. Each line is brokeninto fields using a configurable field delimiter (defaults to a tab character) to bestored in the tuple’s fields.

It is the default storage when none is specified.aTextLoaderLoads relations from a plain-text format. Each line corresponds to a tuple whosesingle field is the line of text.446|Chapter 16: PigCategoryFunctionDescriptionJsonLoader, JsonStorageLoads or stores relations from or to a (Pig-defined) JSON format. Each tuple isstored on one line.AvroStorageLoads or stores relations from or to Avro datafiles.ParquetLoader, ParquetStorerLoads or stores relations from or to Parquet files.OrcStorageLoads or stores relations from or to Hive ORCFiles.HBaseStorageLoads or stores relations from or to HBase tables.a The default storage can be changed by setting pig.default.load.func and pig.default.store.func to thefully qualified load and store function classnames.Other librariesIf the function you need is not available, you can write your own user-defined function(or UDF for short), as explained in “User-Defined Functions” on page 448.

Before you dothat, however, have a look in the Piggy Bank, a library of Pig functions shared by thePig community and distributed as a part of Pig. For example, there are load and storefunctions in the Piggy Bank for CSV files, Hive RCFiles, sequence files, and XML files.The Piggy Bank JAR file comes with Pig, and you can use it with no further configura‐tion. Pig’s API documentation includes a list of functions provided by the Piggy Bank.Apache DataFu is another rich library of Pig UDFs.

In addition to general utility func‐tions, it includes functions for computing basic statistics, performing sampling andestimation, hashing, and working with web data (sessionization, link analysis).MacrosMacros provide a way to package reusable pieces of Pig Latin code from within Pig Latinitself. For example, we can extract the part of our Pig Latin program that performsgrouping on a relation and then finds the maximum value in each group by defining amacro as follows:DEFINE max_by_group(X, group_key, max_field) RETURNS Y {A = GROUP $X by $group_key;$Y = FOREACH A GENERATE group, MAX($X.$max_field);};The macro, called max_by_group, takes three parameters: a relation, X, and two fieldnames, group_key and max_field. It returns a single relation, Y. Within the macro body,parameters and return aliases are referenced with a $ prefix, such as $X.The macro is used as follows:records = LOAD 'input/ncdc/micro-tab/sample.txt'AS (year:chararray, temperature:int, quality:int);filtered_records = FILTER records BY temperature != 9999 ANDPig Latin|447quality IN (0, 1, 4, 5, 9);max_temp = max_by_group(filtered_records, year, temperature);DUMP max_tempAt runtime, Pig will expand the macro using the macro definition.

After expansion, theprogram looks like the following, with the expanded section in bold:records = LOAD 'input/ncdc/micro-tab/sample.txt'AS (year:chararray, temperature:int, quality:int);filtered_records = FILTER records BY temperature != 9999 ANDquality IN (0, 1, 4, 5, 9);macro_max_by_group_A_0 = GROUP filtered_records by (year);max_temp = FOREACH macro_max_by_group_A_0 GENERATE group,MAX(filtered_records.(temperature));DUMP max_tempNormally you don’t see the expanded form, because Pig creates it internally; however,in some cases it is useful to see it when writing and debugging macros.

You can get Pigto perform macro expansion only (without executing the script) by passing the -dryrunargument to pig.Notice that the parameters that were passed to the macro (filtered_records, year,and temperature) have been substituted for the names in the macro definition. Aliasesin the macro definition that don’t have a $ prefix, such as A in this example, are local tothe macro definition and are rewritten at expansion time to avoid conflicts with aliasesin other parts of the program. In this case, A becomes macro_max_by_group_A_0 in theexpanded form.To foster reuse, macros can be defined in separate files to Pig scripts, in which case theyneed to be imported into any script that uses them.

An import statement looks like this:IMPORT './ch16-pig/src/main/pig/max_temp.macro';User-Defined FunctionsPig’s designers realized that the ability to plug in custom code is crucial for all but themost trivial data processing jobs. For this reason, they made it easy to define and useuser-defined functions. We only cover Java UDFs in this section, but be aware that youcan also write UDFs in Python, JavaScript, Ruby, or Groovy, all of which are run usingthe Java Scripting API.A Filter UDFLet’s demonstrate by writing a filter function for filtering out weather records that donot have a temperature quality reading of satisfactory (or better). The idea is to changethis line:filtered_records = FILTER records BY temperature != 9999 ANDquality IN (0, 1, 4, 5, 9);448|Chapter 16: Pigto:filtered_records = FILTER records BY temperature != 9999 AND isGood(quality);This achieves two things: it makes the Pig script a little more concise, and it encapsulatesthe logic in one place so that it can be easily reused in other scripts.

If we were justwriting an ad hoc query, we probably wouldn’t bother to write a UDF. It’s when you startdoing the same kind of processing over and over again that you see opportunities forreusable UDFs.Filter UDFs are all subclasses of FilterFunc, which itself is a subclass of EvalFunc. We’lllook at EvalFunc in more detail later, but for the moment just note that, in essence,EvalFunc looks like the following class:public abstract class EvalFunc<T> {public abstract T exec(Tuple input) throws IOException;}EvalFunc’s only abstract method, exec(), takes a tuple and returns a single value, the(parameterized) type T. The fields in the input tuple consist of the expressions passedto the function—in this case, a single integer. For FilterFunc, T is Boolean, so themethod should return true only for those tuples that should not be filtered out.For the quality filter, we write a class, IsGoodQuality, that extends FilterFunc andimplements the exec() method (see Example 16-1).

The Tuple class is essentially a listof objects with associated types. Here we are concerned only with the first field (sincethe function only has a single argument), which we extract by index using the get()method on Tuple. The field is an integer, so if it’s not null, we cast it and check whetherthe value is one that signifies the temperature was a good reading, returning the ap‐propriate value, true or false.Example 16-1. A FilterFunc UDF to remove records with unsatisfactory temperaturequality readingspackage com.hadoopbook.pig;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.apache.pig.FilterFunc;importimportimportimportorg.apache.pig.backend.executionengine.ExecException;org.apache.pig.data.DataType;org.apache.pig.data.Tuple;org.apache.pig.impl.logicalLayer.FrontendException;public class IsGoodQuality extends FilterFunc {@OverrideUser-Defined Functions|449public Boolean exec(Tuple tuple) throws IOException {if (tuple == null || tuple.size() == 0) {return false;}try {Object object = tuple.get(0);if (object == null) {return false;}int i = (Integer) object;return i == 0 || i == 1 || i == 4 || i == 5 || i == 9;} catch (ExecException e) {throw new IOException(e);}}}To use the new function, we first compile it and package it in a JAR file (the examplecode that accompanies this book comes with build instructions for how to do this).

Thenwe tell Pig about the JAR file with the REGISTER operator, which is given the local pathto the filename (and is not enclosed in quotes):grunt> REGISTER pig-examples.jar;Finally, we can invoke the function:grunt> filtered_records = FILTER records BY temperature != 9999 AND>>com.hadoopbook.pig.IsGoodQuality(quality);Pig resolves function calls by treating the function’s name as a Java classname and at‐tempting to load a class of that name.

Характеристики

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6517
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее