PageRenderTime 64ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/src/docs/src/documentation/content/xdocs/perf.xml

https://github.com/dorefiend/pig
XML | 1232 lines | 941 code | 220 blank | 71 comment | 0 complexity | d8ae3790281da410d45eb76b129992ea MD5 | raw file
Possible License(s): Apache-2.0, CPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!--
  3. Licensed to the Apache Software Foundation (ASF) under one or more
  4. contributor license agreements. See the NOTICE file distributed with
  5. this work for additional information regarding copyright ownership.
  6. The ASF licenses this file to You under the Apache License, Version 2.0
  7. (the "License"); you may not use this file except in compliance with
  8. the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. -->
  16. <!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
  17. <document>
  18. <header>
  19. <title>Performance and Efficiency</title>
  20. </header>
  21. <body>
  22. <section id="profiling">
  23. <title>Timing your UDFs</title>
  24. <p>The first step to improving performance and efficiency is measuring where the time is going. Pig provides a light-weight method for approximately measuring how much time is spent in different user-defined functions (UDFs) and Loaders. Simply set the pig.udf.profile property to true. This will cause new counters to be tracked for all Map-Reduce jobs generated by your script: approx_microsecs measures the approximate amount of time spent in a UDF, and approx_invocations measures the approximate number of times the UDF was invoked. Note that this may produce a large number of counters (two per UDF). Excessive amounts of counters can lead to poor JobTracker performance, so use this feature carefully, and preferably on a test cluster.</p>
  25. </section>
  26. <!-- ================================================================== -->
  27. <!-- COMBINER -->
  28. <section id="combiner">
  29. <title>Combiner</title>
  30. <p>The Pig combiner is an optimizer that is invoked when the statements in your scripts are arranged in certain ways. The examples below demonstrate when the combiner is used and not used. Whenever possible, make sure the combiner is used as it frequently yields an order of magnitude improvement in performance. </p>
  31. <section>
  32. <title>When the Combiner is Used</title>
  33. <p>The combiner is generally used in the case of non-nested foreach where all projections are either expressions on the group column or expressions on algebraic UDFs (see <a href="#Algebraic-interface">Make Your UDFs Algebraic</a>).</p>
  34. <p>Example:</p>
  35. <source>
  36. A = load 'studenttab10k' as (name, age, gpa);
  37. B = group A by age;
  38. C = foreach B generate ABS(SUM(A.gpa)), COUNT(org.apache.pig.builtin.Distinct(A.name)), (MIN(A.gpa) + MAX(A.gpa))/2, group.age;
  39. explain C;
  40. </source>
  41. <p></p>
  42. <p>In the above example:</p>
  43. <ul>
  44. <li>The GROUP statement can be referred to as a whole or by accessing individual fields (as in the example). </li>
  45. <li>The GROUP statement and its elements can appear anywhere in the projection. </li>
  46. </ul>
  47. <p>In the above example, a variety of expressions can be applied to algebraic functions including:</p>
  48. <ul>
  49. <li>A column transformation function such as ABS can be applied to an algebraic function SUM.</li>
  50. <li>An algebraic function (COUNT) can be applied to another algebraic function (Distinct), but only the inner function is computed using the combiner. </li>
  51. <li>A mathematical expression can be applied to one or more algebraic functions. </li>
  52. </ul>
  53. <p></p>
  54. <p>You can check if the combiner is used for your query by running <a href="test.html#EXPLAIN">EXPLAIN</a> on the FOREACH alias as shown above. You should see the combine section in the MapReduce part of the plan:</p>
  55. <source>
  56. .....
  57. Combine Plan
  58. B: Local Rearrange[tuple]{bytearray}(false) - scope-42
  59. | |
  60. | Project[bytearray][0] - scope-43
  61. |
  62. |---C: New For Each(false,false,false)[bag] - scope-28
  63. | |
  64. | Project[bytearray][0] - scope-29
  65. | |
  66. | POUserFunc(org.apache.pig.builtin.SUM$Intermediate)[tuple] - scope-30
  67. | |
  68. | |---Project[bag][1] - scope-31
  69. | |
  70. | POUserFunc(org.apache.pig.builtin.Distinct$Intermediate)[tuple] - scope-32
  71. | |
  72. | |---Project[bag][2] - scope-33
  73. |
  74. |---POCombinerPackage[tuple]{bytearray} - scope-36--------
  75. .....
  76. </source>
  77. <p>The combiner is also used with a nested foreach as long as the only nested operation used is DISTINCT
  78. (see <a href="basic.html#FOREACH">FOREACH</a> and <a href="basic.html#nestedblock">Example: Nested Block</a>).
  79. </p>
  80. <source>
  81. A = load 'studenttab10k' as (name, age, gpa);
  82. B = group A by age;
  83. C = foreach B { D = distinct (A.name); generate group, COUNT(D);}
  84. </source>
  85. <p></p>
  86. <p>Finally, use of the combiner is influenced by the surrounding environment of the GROUP and FOREACH statements.</p>
  87. </section>
  88. <section>
  89. <title>When the Combiner is Not Used</title>
  90. <p>The combiner is generally not used if there is any operator that comes between the GROUP and FOREACH statements in the execution plan. Even if the statements are next to each other in your script, the optimizer might rearrange them. In this example, the optimizer will push FILTER above FOREACH which will prevent the use of the combiner:</p>
  91. <source>
  92. A = load 'studenttab10k' as (name, age, gpa);
  93. B = group A by age;
  94. C = foreach B generate group, COUNT (A);
  95. D = filter C by group.age &lt;30;
  96. </source>
  97. <p></p>
  98. <p>Please note that the script above can be made more efficient by performing filtering before the GROUP statement:</p>
  99. <source>
  100. A = load 'studenttab10k' as (name, age, gpa);
  101. B = filter A by age &lt;30;
  102. C = group B by age;
  103. D = foreach C generate group, COUNT (B);
  104. </source>
  105. <p></p>
  106. <p><strong>Note:</strong> One exception to the above rule is LIMIT. Starting with Pig 0.9, even if LIMIT comes between GROUP and FOREACH, the combiner will still be used. In this example, the optimizer will push LIMIT above FOREACH but this will not prevent the use of the combiner.</p>
  107. <source>
  108. A = load 'studenttab10k' as (name, age, gpa);
  109. B = group A by age;
  110. C = foreach B generate group, COUNT (A);
  111. D = limit C 20;
  112. </source>
  113. <p></p>
  114. <p>The combiner is also not used in the case where multiple FOREACH statements are associated with the same GROUP:</p>
  115. <source>
  116. A = load 'studenttab10k' as (name, age, gpa);
  117. B = group A by age;
  118. C = foreach B generate group, COUNT (A);
  119. D = foreach B generate group, MIN (A.gpa). MAX(A.gpa);
  120. .....
  121. </source>
  122. <p>Depending on your use case, it might be more efficient (improve performance) to split your script into multiple scripts.</p>
  123. </section>
  124. </section>
  125. <!-- ================================================================== -->
  126. <!-- HASH-BASED AGGREGATION IN MAP TASK-->
  127. <section id="hash-based-aggregation">
  128. <title>Hash-based Aggregation in Map Task</title>
  129. <p> To improve performance, hash-based aggregation will aggregate records in the map task before sending them to the combiner. This optimization reduces the serializing/deserializing costs of the combiner by sending it fewer records.</p>
  130. <p><strong>Turning On Off</strong></p>
  131. <p>Hash-based aggregation has been shown to improve the speed of group-by operations by up to 50%. However, since this is a very new feature, it is currently turned OFF by default. To turn it ON, set the property pig.exec.mapPartAgg to true.</p>
  132. <p><strong>Configuring</strong></p>
  133. <p>If the group-by keys used for grouping don't result in a sufficient reduction in the number of records, the performance might be worse with this feature turned ON. To prevent this from happening, the feature turns itself off if the reduction in records sent to combiner is not more than a configurable threshold. This threshold can be set using the property pig.exec.mapPartAgg.minReduction. It is set to a default value of 10, which means that the number of records that get sent to the combiner should be reduced by a factor of 10 or more.</p>
  134. </section>
  135. <!-- ================================================================== -->
  136. <!-- MEMORY MANAGEMENT -->
  137. <section id="memory-management">
  138. <title>Memory Management</title>
  139. <p>Pig allocates a fix amount of memory to store bags and spills to disk as soon as the memory limit is reached. This is very similar to how Hadoop decides when to spill data accumulated by the combiner. </p>
  140. <p id="memory-bags">The amount of memory allocated to bags is determined by pig.cachedbag.memusage; the default is set to 20% (0.2) of available memory. Note that this memory is shared across all large bags used by the application.</p>
  141. </section>
  142. <!-- ================================================================== -->
  143. <!-- REDUCER ESTIMATION -->
  144. <section id="reducer-estimation">
  145. <title>Reducer Estimation</title>
  146. <p>
  147. By default Pig determines the number of reducers to use for a given job based on the size of the
  148. input to the map phase. The input data size is divided by the
  149. pig.exec.reducers.bytes.per.reducer parameter value (default 1GB) to determine the number of
  150. reducers. The maximum number of reducers for a job is limited by the pig.exec.reducers.max parameter
  151. (default 999).
  152. </p>
  153. <p>
  154. The default reducer estimation algorithm described above can be overridden by setting the
  155. pig.exec.reducer.estimator parameter to the fully qualified class name of an implementation of
  156. <a href="http://svn.apache.org/repos/asf/pig/trunk/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer/PigReducerEstimator.java">org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigReducerEstimator</a>.
  157. The class must exist on the classpath of the process submitting the Pig job. If the
  158. pig.exec.reducer.estimator.arg parameter is set, the value will be passed to a constructor
  159. of the implementing class that takes a single String.
  160. </p>
  161. <p>
  162. </p>
  163. </section>
  164. <!-- ==================================================================== -->
  165. <!-- MULTI-QUERY EXECUTION-->
  166. <section id="multi-query-execution">
  167. <title>Multi-Query Execution</title>
  168. <p>With multi-query execution Pig processes an entire script or a batch of statements at once.</p>
  169. <section>
  170. <title>Turning it On or Off</title>
  171. <p>Multi-query execution is turned on by default.
  172. To turn it off and revert to Pig's "execute-on-dump/store" behavior, use the "-M" or "-no_multiquery" options. </p>
  173. <p>To run script "myscript.pig" without the optimization, execute Pig as follows: </p>
  174. <source>
  175. $ pig -M myscript.pig
  176. or
  177. $ pig -no_multiquery myscript.pig
  178. </source>
  179. </section>
  180. <section>
  181. <title>How it Works</title>
  182. <p>Multi-query execution introduces some changes:</p>
  183. <ul>
  184. <li>
  185. <p>For batch mode execution, the entire script is first parsed to determine if intermediate tasks
  186. can be combined to reduce the overall amount of work that needs to be done; execution starts only after the parsing is completed
  187. (see the <a href="test.html#EXPLAIN">EXPLAIN</a> operator and the <a href="cmds.html#run">run</a> and <a href="cmds.html#exec">exec</a> commands). </p>
  188. </li>
  189. <li>
  190. <p>Two run scenarios are optimized, as explained below: explicit and implicit splits, and storing intermediate results.</p>
  191. </li>
  192. </ul>
  193. <section id="splits">
  194. <title>Explicit and Implicit Splits</title>
  195. <p>There might be cases in which you want different processing on separate parts of the same data stream.</p>
  196. <p>Example 1:</p>
  197. <source>
  198. A = LOAD ...
  199. ...
  200. SPLIT A' INTO B IF ..., C IF ...
  201. ...
  202. STORE B' ...
  203. STORE C' ...
  204. </source>
  205. <p>Example 2:</p>
  206. <source>
  207. A = LOAD ...
  208. ...
  209. B = FILTER A' ...
  210. C = FILTER A' ...
  211. ...
  212. STORE B' ...
  213. STORE C' ...
  214. </source>
  215. <p>In prior Pig releases, Example 1 will dump A' to disk and then start jobs for B' and C'.
  216. Example 2 will execute all the dependencies of B' and store it and then execute all the dependencies of C' and store it.
  217. Both are equivalent, but the performance will be different. </p>
  218. <p>Here's what the multi-query execution does to increase the performance: </p>
  219. <ul>
  220. <li><p>For Example 2, adds an implicit split to transform the query to Example 1.
  221. This eliminates the processing of A' multiple times.</p></li>
  222. <li><p>Makes the split non-blocking and allows processing to continue.
  223. This helps reduce the amount of data that has to be stored right at the split. </p></li>
  224. <li><p>Allows multiple outputs from a job. This way some results can be stored as a side-effect of the main job.
  225. This is also necessary to make the previous item work. </p></li>
  226. <li><p>Allows multiple split branches to be carried on to the combiner/reducer.
  227. This reduces the amount of IO again in the case where multiple branches in the split can benefit from a combiner run. </p></li>
  228. </ul>
  229. </section>
  230. <section id="data-store-performance">
  231. <title>Storing Intermediate Results</title>
  232. <p>Sometimes it is necessary to store intermediate results. </p>
  233. <source>
  234. A = LOAD ...
  235. ...
  236. STORE A'
  237. ...
  238. STORE A''
  239. </source>
  240. <p>If the script doesn't re-load A' for the processing of A the steps above A' will be duplicated.
  241. This is a special case of Example 2 above, so the same steps are recommended.
  242. With multi-query execution, the script will process A and dump A' as a side-effect.</p>
  243. </section>
  244. </section>
  245. <!-- ++++++++++++++++++++++++++++++++++++++++++ -->
  246. <section id="store-dump">
  247. <title>Store vs. Dump</title>
  248. <p>With multi-query exection, you want to use <a href="basic.html#STORE">STORE</a> to save (persist) your results.
  249. You do not want to use <a href="test.html#DUMP">DUMP</a> as it will disable multi-query execution and is likely to slow down execution. (If you have included DUMP statements in your scripts for debugging purposes, you should remove them.) </p>
  250. <p>DUMP Example: In this script, because the DUMP command is interactive, the multi-query execution will be disabled and two separate jobs will be created to execute this script. The first job will execute A > B > DUMP while the second job will execute A > B > C > STORE.</p>
  251. <source>
  252. A = LOAD 'input' AS (x, y, z);
  253. B = FILTER A BY x > 5;
  254. DUMP B;
  255. C = FOREACH B GENERATE y, z;
  256. STORE C INTO 'output';
  257. </source>
  258. <p>STORE Example: In this script, multi-query optimization will kick in allowing the entire script to be executed as a single job. Two outputs are produced: output1 and output2.</p>
  259. <source>
  260. A = LOAD 'input' AS (x, y, z);
  261. B = FILTER A BY x > 5;
  262. STORE B INTO 'output1';
  263. C = FOREACH B GENERATE y, z;
  264. STORE C INTO 'output2';
  265. </source>
  266. </section>
  267. <!-- ++++++++++++++++++++++++++++++++++++++++++ -->
  268. <section id="error-handling">
  269. <title>Error Handling</title>
  270. <p>With multi-query execution Pig processes an entire script or a batch of statements at once.
  271. By default Pig tries to run all the jobs that result from that, regardless of whether some jobs fail during execution.
  272. To check which jobs have succeeded or failed use one of these options. </p>
  273. <p>First, Pig logs all successful and failed store commands. Store commands are identified by output path.
  274. At the end of execution a summary line indicates success, partial failure or failure of all store commands. </p>
  275. <p>Second, Pig returns different code upon completion for these scenarios:</p>
  276. <ul>
  277. <li><p>Return code 0: All jobs succeeded</p></li>
  278. <li><p>Return code 1: <em>Used for retrievable errors</em> </p></li>
  279. <li><p>Return code 2: All jobs have failed </p></li>
  280. <li><p>Return code 3: Some jobs have failed </p></li>
  281. </ul>
  282. <p></p>
  283. <p>In some cases it might be desirable to fail the entire script upon detecting the first failed job.
  284. This can be achieved with the "-F" or "-stop_on_failure" command line flag.
  285. If used, Pig will stop execution when the first failed job is detected and discontinue further processing.
  286. This also means that file commands that come after a failed store in the script will not be executed (this can be used to create "done" files). </p>
  287. <p>This is how the flag is used: </p>
  288. <source>
  289. $ pig -F myscript.pig
  290. or
  291. $ pig -stop_on_failure myscript.pig
  292. </source>
  293. </section>
  294. <!-- ++++++++++++++++++++++++++++++++++++++++++ -->
  295. <section id="backward-compatibility">
  296. <title>Backward Compatibility</title>
  297. <p>Most existing Pig scripts will produce the same result with or without the multi-query execution.
  298. There are cases though where this is not true. Path names and schemes are discussed here.</p>
  299. <p>Any script is parsed in it's entirety before it is sent to execution. Since the current directory can change
  300. throughout the script any path used in LOAD or STORE statement is translated to a fully qualified and absolute path.</p>
  301. <p>In map-reduce mode, the following script will load from "hdfs://&lt;host&gt;:&lt;port&gt;/data1" and store into "hdfs://&lt;host&gt;:&lt;port&gt;/tmp/out1". </p>
  302. <source>
  303. cd /;
  304. A = LOAD 'data1';
  305. cd tmp;
  306. STORE A INTO 'out1';
  307. </source>
  308. <p>These expanded paths will be passed to any LoadFunc or Slicer implementation.
  309. In some cases this can cause problems, especially when a LoadFunc/Slicer is not used to read from a dfs file or path
  310. (for example, loading from an SQL database). </p>
  311. <p>Solutions are to either: </p>
  312. <ul>
  313. <li><p>Specify "-M" or "-no_multiquery" to revert to the old names</p></li>
  314. <li><p>Specify a custom scheme for the LoadFunc/Slicer </p></li>
  315. </ul>
  316. <p>Arguments used in a LOAD statement that have a scheme other than "hdfs" or "file" will not be expanded and passed to the LoadFunc/Slicer unchanged.</p>
  317. <p>In the SQL case, the SQLLoader function is invoked with 'sql://mytable'. </p>
  318. <source>
  319. A = LOAD 'sql://mytable' USING SQLLoader();
  320. </source>
  321. </section>
  322. <section id="Implicit-Dependencies">
  323. <title>Implicit Dependencies</title>
  324. <p>If a script has dependencies on the execution order outside of what Pig knows about, execution may fail. </p>
  325. <section>
  326. <title>Example</title>
  327. <p>In this script, MYUDF might try to read from out1, a file that A was just stored into.
  328. However, Pig does not know that MYUDF depends on the out1 file and might submit the jobs
  329. producing the out2 and out1 files at the same time.</p>
  330. <source>
  331. ...
  332. STORE A INTO 'out1';
  333. B = LOAD 'data2';
  334. C = FOREACH B GENERATE MYUDF($0,'out1');
  335. STORE C INTO 'out2';
  336. </source>
  337. <p>To make the script work (to ensure that the right execution order is enforced) add the exec statement.
  338. The exec statement will trigger the execution of the statements that produce the out1 file. </p>
  339. <source>
  340. ...
  341. STORE A INTO 'out1';
  342. EXEC;
  343. B = LOAD 'data2';
  344. C = FOREACH B GENERATE MYUDF($0,'out1');
  345. STORE C INTO 'out2';
  346. </source>
  347. </section>
  348. <section>
  349. <title>Example</title>
  350. <p>In this script, the STORE/LOAD operators have different file paths; however, the LOAD operator depends on the STORE operator.</p>
  351. <source>
  352. A = LOAD '/user/xxx/firstinput' USING PigStorage();
  353. B = group ....
  354. C = .... agrregation function
  355. STORE C INTO '/user/vxj/firstinputtempresult/days1';
  356. ..
  357. Atab = LOAD '/user/xxx/secondinput' USING PigStorage();
  358. Btab = group ....
  359. Ctab = .... agrregation function
  360. STORE Ctab INTO '/user/vxj/secondinputtempresult/days1';
  361. ..
  362. E = LOAD '/user/vxj/firstinputtempresult/' USING PigStorage();
  363. F = group ....
  364. G = .... aggregation function
  365. STORE G INTO '/user/vxj/finalresult1';
  366. Etab =LOAD '/user/vxj/secondinputtempresult/' USING PigStorage();
  367. Ftab = group ....
  368. Gtab = .... aggregation function
  369. STORE Gtab INTO '/user/vxj/finalresult2';
  370. </source>
  371. <p>To make the script works, add the exec statement. </p>
  372. <source>
  373. A = LOAD '/user/xxx/firstinput' USING PigStorage();
  374. B = group ....
  375. C = .... agrregation function
  376. STORE C INTO '/user/vxj/firstinputtempresult/days1';
  377. ..
  378. Atab = LOAD '/user/xxx/secondinput' USING PigStorage();
  379. Btab = group ....
  380. Ctab = .... agrregation function
  381. STORE Ctab INTO '/user/vxj/secondinputtempresult/days1';
  382. EXEC;
  383. E = LOAD '/user/vxj/firstinputtempresult/' USING PigStorage();
  384. F = group ....
  385. G = .... aggregation function
  386. STORE G INTO '/user/vxj/finalresult1';
  387. ..
  388. Etab =LOAD '/user/vxj/secondinputtempresult/' USING PigStorage();
  389. Ftab = group ....
  390. Gtab = .... aggregation function
  391. STORE Gtab INTO '/user/vxj/finalresult2';
  392. </source>
  393. </section>
  394. </section>
  395. </section>
  396. <!-- ==================================================================== -->
  397. <!-- OPTIMIZATION RULES -->
  398. <section id="optimization-rules">
  399. <title>Optimization Rules</title>
  400. <p>Pig supports various optimization rules. By default optimization, and all optimization rules, are turned on.
  401. To turn off optimiztion, use:</p>
  402. <source>
  403. pig -optimizer_off [opt_rule | all ]
  404. </source>
  405. <p>Note that some rules are mandatory and cannot be turned off.</p>
  406. <!-- +++++++++++++++++++++++++++++++ -->
  407. <section id="FilterLogicExpressionSimplifier">
  408. <title>FilterLogicExpressionSimplifier</title>
  409. <p>This rule simplifies the expression in filter statement.</p>
  410. <source>
  411. 1) Constant pre-calculation
  412. B = FILTER A BY a0 &gt; 5+7;
  413. is simplified to
  414. B = FILTER A BY a0 &gt; 12;
  415. 2) Elimination of negations
  416. B = FILTER A BY NOT (NOT(a0 &gt; 5) OR a &gt; 10);
  417. is simplified to
  418. B = FILTER A BY a0 &gt; 5 AND a &lt;= 10;
  419. 3) Elimination of logical implied expression in AND
  420. B = FILTER A BY (a0 &gt; 5 AND a0 &gt; 7);
  421. is simplified to
  422. B = FILTER A BY a0 &gt; 7;
  423. 4) Elimination of logical implied expression in OR
  424. B = FILTER A BY ((a0 &gt; 5) OR (a0 &gt; 6 AND a1 &gt; 15);
  425. is simplified to
  426. B = FILTER C BY a0 &gt; 5;
  427. 5) Equivalence elimination
  428. B = FILTER A BY (a0 v 5 AND a0 &gt; 5);
  429. is simplified to
  430. B = FILTER A BY a0 &gt; 5;
  431. 6) Elimination of complementary expressions in OR
  432. B = FILTER A BY (a0 &gt; 5 OR a0 &lt;= 5);
  433. is simplified to non-filtering
  434. 7) Elimination of naive TRUE expression
  435. B = FILTER A BY 1==1;
  436. is simplified to non-filtering
  437. </source>
  438. </section>
  439. <!-- +++++++++++++++++++++++++++++++ -->
  440. <section id="SplitFilter">
  441. <title>SplitFilter</title>
  442. <p>Split filter conditions so that we can push filter more aggressively.</p>
  443. <source>
  444. A = LOAD 'input1' as (a0, a1);
  445. B = LOAD 'input2' as (b0, b1);
  446. C = JOIN A by a0, B by b0;
  447. D = FILTER C BY a1&gt;0 and b1&gt;0;
  448. </source>
  449. <p>Here D will be splitted into:</p>
  450. <source>
  451. X = FILTER C BY a1&gt;0;
  452. D = FILTER X BY b1&gt;0;
  453. </source>
  454. <p>So "a1&gt;0" and "b1&gt;0" can be pushed up individually.</p>
  455. </section>
  456. <!-- +++++++++++++++++++++++++++++++ -->
  457. <section id="PushUpFilter">
  458. <title>PushUpFilter</title>
  459. <p>The objective of this rule is to push the FILTER operators up the data flow graph. As a result, the number of records that flow through the pipeline is reduced. </p>
  460. <source>
  461. A = LOAD 'input';
  462. B = GROUP A BY $0;
  463. C = FILTER B BY $0 &lt; 10;
  464. </source>
  465. </section>
  466. <!-- +++++++++++++++++++++++++++++++ -->
  467. <section id="MergeFilter">
  468. <title>MergeFilter</title>
  469. <p>Merge filter conditions after PushUpFilter rule to decrease the number of filter statements.</p>
  470. </section>
  471. <!-- +++++++++++++++++++++++++++++++ -->
  472. <section id="PushDownForEachFlatten">
  473. <title>PushDownForEachFlatten</title>
  474. <p>The objective of this rule is to reduce the number of records that flow through the pipeline by moving FOREACH operators with a FLATTEN down the data flow graph. In the example shown below, it would be more efficient to move the foreach after the join to reduce the cost of the join operation.</p>
  475. <source>
  476. A = LOAD 'input' AS (a, b, c);
  477. B = LOAD 'input2' AS (x, y, z);
  478. C = FOREACH A GENERATE FLATTEN($0), B, C;
  479. D = JOIN C BY $1, B BY $1;
  480. </source>
  481. </section>
  482. <!-- +++++++++++++++++++++++++++++++ -->
  483. <section id="LimitOptimizer">
  484. <title>LimitOptimizer</title>
  485. <p>The objective of this rule is to push the LIMIT operator up the data flow graph (or down the tree for database folks). In addition, for top-k (ORDER BY followed by a LIMIT) the LIMIT is pushed into the ORDER BY.</p>
  486. <source>
  487. A = LOAD 'input';
  488. B = ORDER A BY $0;
  489. C = LIMIT B 10;
  490. </source>
  491. </section>
  492. <!-- +++++++++++++++++++++++++++++++ -->
  493. <section id="ColumnMapKeyPrune">
  494. <title>ColumnMapKeyPrune</title>
  495. <p>Prune the loader to only load necessary columns. The performance gain is more significant if the corresponding loader support column pruning and only load necessary columns (See LoadPushDown.pushProjection). Otherwise, ColumnMapKeyPrune will insert a ForEach statement right after loader.</p>
  496. <source>
  497. A = load 'input' as (a0, a1, a2);
  498. B = ORDER A by a0;
  499. C = FOREACH B GENERATE a0, a1;
  500. </source>
  501. <p>a2 is irrelevant in this query, so we can prune it earlier. The loader in this query is PigStorage and it supports column pruning. So we only load a0 and a1 from the input file.</p>
  502. <p>ColumnMapKeyPrune also prunes unused map keys:</p>
  503. <source>
  504. A = load 'input' as (a0:map[]);
  505. B = FOREACH A generate a0#'key1';
  506. </source>
  507. </section>
  508. <!-- +++++++++++++++++++++++++++++++ -->
  509. <section id="AddForEach">
  510. <title>AddForEach</title>
  511. <p>Prune unused column as soon as possible. In addition to prune the loader in ColumnMapKeyPrune, we can prune a column as soon as it is not used in the rest of the script</p>
  512. <source>
  513. -- Original code:
  514. A = LOAD 'input' AS (a0, a1, a2);
  515. B = ORDER A BY a0;
  516. C = FILTER B BY a1&gt;0;
  517. </source>
  518. <p>We can only prune a2 from the loader. However, a0 is never used after "ORDER BY". So we can drop a0 right after "ORDER BY" statement.</p>
  519. <source>
  520. -- Optimized code:
  521. A = LOAD 'input' AS (a0, a1, a2);
  522. B = ORDER A BY a0;
  523. B1 = FOREACH B GENERATE a1; -- drop a0
  524. C = FILTER B1 BY a1&gt;0;
  525. </source>
  526. </section>
  527. <!-- +++++++++++++++++++++++++++++++ -->
  528. <section id="MergeForEach">
  529. <title>MergeForEach</title>
  530. <p>The objective of this rule is to merge together two feach statements, if these preconditions are met:</p>
  531. <ul>
  532. <li>The foreach statements are consecutive.</li>
  533. <li>The first foreach statement does not contain flatten.</li>
  534. <li>The second foreach is not nested.</li>
  535. </ul>
  536. <source>
  537. -- Original code:
  538. A = LOAD 'file.txt' AS (a, b, c);
  539. B = FOREACH A GENERATE a+b AS u, c-b AS v;
  540. C = FOREACH B GENERATE $0+5, v;
  541. -- Optimized code:
  542. A = LOAD 'file.txt' AS (a, b, c);
  543. C = FOREACH A GENERATE a+b+5, c-b;
  544. </source>
  545. </section>
  546. <!-- +++++++++++++++++++++++++++++++ -->
  547. <section id="GroupByConstParallelSetter">
  548. <title>GroupByConstParallelSetter</title>
  549. <p>Force parallel "1" for "group all" statement. That's because even if we set parallel to N, only 1 reducer will be used in this case and all other reducer produce empty result.</p>
  550. <source>
  551. A = LOAD 'input';
  552. B = GROUP A all PARALLEL 10;
  553. </source>
  554. </section>
  555. </section>
  556. <!-- ==================================================================== -->
  557. <!-- PERFORMANCE ENHANCERS-->
  558. <section id="performance-enhancers">
  559. <title>Performance Enhancers</title>
  560. <section>
  561. <title>Use Optimization</title>
  562. <p>Pig supports various <a href="perf.html#Optimization-Rules">optimization rules</a> which are turned on by default.
  563. Become familiar with these rules.</p>
  564. </section>
  565. <!-- +++++++++++++++++++++++++++++++ -->
  566. <section id="types">
  567. <title>Use Types</title>
  568. <p>If types are not specified in the load statement, Pig assumes the type of =double= for numeric computations.
  569. A lot of the time, your data would be much smaller, maybe, integer or long. Specifying the real type will help with
  570. speed of arithmetic computation. It has an additional advantage of early error detection. </p>
  571. <source>
  572. --Query 1
  573. A = load 'myfile' as (t, u, v);
  574. B = foreach A generate t + u;
  575. --Query 2
  576. A = load 'myfile' as (t: int, u: int, v);
  577. B = foreach A generate t + u;
  578. </source>
  579. <p>The second query will run more efficiently than the first. In some of our queries with see 2x speedup. </p>
  580. </section>
  581. <!-- +++++++++++++++++++++++++++++++ -->
  582. <section id="projection">
  583. <title>Project Early and Often </title>
  584. <p>Pig does not (yet) determine when a field is no longer needed and drop the field from the row. For example, say you have a query like: </p>
  585. <source>
  586. A = load 'myfile' as (t, u, v);
  587. B = load 'myotherfile' as (x, y, z);
  588. C = join A by t, B by x;
  589. D = group C by u;
  590. E = foreach D generate group, COUNT($1);
  591. </source>
  592. <p>There is no need for v, y, or z to participate in this query. And there is no need to carry both t and x past the join, just one will suffice. Changing the query above to the query below will greatly reduce the amount of data being carried through the map and reduce phases by pig. </p>
  593. <source>
  594. A = load 'myfile' as (t, u, v);
  595. A1 = foreach A generate t, u;
  596. B = load 'myotherfile' as (x, y, z);
  597. B1 = foreach B generate x;
  598. C = join A1 by t, B1 by x;
  599. C1 = foreach C generate t, u;
  600. D = group C1 by u;
  601. E = foreach D generate group, COUNT($1);
  602. </source>
  603. <p>Depending on your data, this can produce significant time savings. In queries similar to the example shown here we have seen total time drop by 50%.</p>
  604. </section>
  605. <!-- +++++++++++++++++++++++++++++++ -->
  606. <section id="filter">
  607. <title>Filter Early and Often</title>
  608. <p>As with early projection, in most cases it is beneficial to apply filters as early as possible to reduce the amount of data flowing through the pipeline. </p>
  609. <source>
  610. -- Query 1
  611. A = load 'myfile' as (t, u, v);
  612. B = load 'myotherfile' as (x, y, z);
  613. C = filter A by t == 1;
  614. D = join C by t, B by x;
  615. E = group D by u;
  616. F = foreach E generate group, COUNT($1);
  617. -- Query 2
  618. A = load 'myfile' as (t, u, v);
  619. B = load 'myotherfile' as (x, y, z);
  620. C = join A by t, B by x;
  621. D = group C by u;
  622. E = foreach D generate group, COUNT($1);
  623. F = filter E by C.t == 1;
  624. </source>
  625. <p>The first query is clearly more efficient than the second one because it reduces the amount of data going into the join. </p>
  626. <p>One case where pushing filters up might not be a good idea is if the cost of applying filter is very high and only a small amount of data is filtered out. </p>
  627. </section>
  628. <!-- +++++++++++++++++++++++++++++++ -->
  629. <section id="pipeline">
  630. <title>Reduce Your Operator Pipeline</title>
  631. <p>For clarity of your script, you might choose to split your projects into several steps for instance: </p>
  632. <source>
  633. A = load 'data' as (in: map[]);
  634. -- get key out of the map
  635. B = foreach A generate in#'k1' as k1, in#'k2' as k2;
  636. -- concatenate the keys
  637. C = foreach B generate CONCAT(k1, k2);
  638. .......
  639. </source>
  640. <p>While the example above is easier to read, you might want to consider combining the two foreach statements to improve your query performance: </p>
  641. <source>
  642. A = load 'data' as (in: map[]);
  643. -- concatenate the keys from the map
  644. B = foreach A generate CONCAT(in#'k1', in#'k2');
  645. ....
  646. </source>
  647. <p>The same goes for filters. </p>
  648. </section>
  649. <!-- +++++++++++++++++++++++++++++++ -->
  650. <section id="algebraic-interface">
  651. <title>Make Your UDFs Algebraic</title>
  652. <p>Queries that can take advantage of the combiner generally ran much faster (sometimes several times faster) than the versions that don't. The latest code significantly improves combiner usage; however, you need to make sure you do your part. If you have a UDF that works on grouped data and is, by nature, algebraic (meaning their computation can be decomposed into multiple steps) make sure you implement it as such. For details on how to write algebraic UDFs, see <a href="udf.html#algebraic-interface">Algebraic Interface</a>.</p>
  653. <source>
  654. A = load 'data' as (x, y, z)
  655. B = group A by x;
  656. C = foreach B generate group, MyUDF(A);
  657. ....
  658. </source>
  659. <p>If <code>MyUDF</code> is algebraic, the query will use combiner and run much faster. You can run <code>explain</code> command on your query to make sure that combiner is used. </p>
  660. </section>
  661. <!-- +++++++++++++++++++++++++++++++ -->
  662. <section id="accumulator-interface">
  663. <title>Use the Accumulator Interface</title>
  664. <p>
  665. If your UDF can't be made Algebraic but is able to deal with getting input in chunks rather than all at once, consider implementing the Accumulator interface to reduce the amount of memory used by your script. If your function <em>is</em> Algebraic and can be used on conjunction with Accumulator functions, you will need to implement the Accumulator interface as well as the Algebraic interface. For more information, see <a href="udf.html#Accumulator-Interface">Accumulator Interface</a>.</p>
  666. <p><strong>Note:</strong> Pig automatically chooses the interface that it expects to provide the best performance: Algebraic &gt; Accumulator &gt; Default. </p>
  667. </section>
  668. <!-- +++++++++++++++++++++++++++++++ -->
  669. <section id="nulls">
  670. <title>Drop Nulls Before a Join</title>
  671. <p>With the introduction of nulls, join and cogroup semantics were altered to work with nulls. The semantic for cogrouping with nulls is that nulls from a given input are grouped together, but nulls across inputs are not grouped together. This preserves the semantics of grouping (nulls are collected together from a single input to be passed to aggregate functions like COUNT) and the semantics of join (nulls are not joined across inputs). Since flattening an empty bag results in an empty row (and no output), in a standard join the rows with a null key will always be dropped. </p>
  672. <p>This join</p>
  673. <source>
  674. A = load 'myfile' as (t, u, v);
  675. B = load 'myotherfile' as (x, y, z);
  676. C = join A by t, B by x;
  677. </source>
  678. <p>is rewritten by Pig to </p>
  679. <source>
  680. A = load 'myfile' as (t, u, v);
  681. B = load 'myotherfile' as (x, y, z);
  682. C1 = cogroup A by t INNER, B by x INNER;
  683. C = foreach C1 generate flatten(A), flatten(B);
  684. </source>
  685. <p>Since the nulls from A and B won't be collected together, when the nulls are flattened we're guaranteed to have an empty bag, which will result in no output. So the null keys will be dropped. But they will not be dropped until the last possible moment. </p>
  686. <p>If the query is rewritten to </p>
  687. <source>
  688. A = load 'myfile' as (t, u, v);
  689. B = load 'myotherfile' as (x, y, z);
  690. A1 = filter A by t is not null;
  691. B1 = filter B by x is not null;
  692. C = join A1 by t, B1 by x;
  693. </source>
  694. <p>then the nulls will be dropped before the join. Since all null keys go to a single reducer, if your key is null even a small percentage of the time the gain can be significant. In one test where the key was null 7% of the time and the data was spread across 200 reducers, we saw a about a 10x speed up in the query by adding the early filters. </p>
  695. </section>
  696. <!-- +++++++++++++++++++++++++++++++ -->
  697. <section id="join-optimizations">
  698. <title>Take Advantage of Join Optimizations</title>
  699. <p><strong>Regular Join Optimizations</strong></p>
  700. <p>Optimization for regular joins ensures that the last table in the join is not brought into memory but streamed through instead. Optimization reduces the amount of memory used which means you can avoid spilling the data and also should be able to scale your query to larger data volumes. </p>
  701. <p>To take advantage of this optimization, make sure that the table with the largest number of tuples per key is the last table in your query.
  702. In some of our tests we saw 10x performance improvement as the result of this optimization.</p>
  703. <source>
  704. small = load 'small_file' as (t, u, v);
  705. large = load 'large_file' as (x, y, z);
  706. C = join small by t, large by x;
  707. </source>
  708. <p><strong>Specialized Join Optimizations</strong></p>
  709. <p>Optimization can also be achieved using fragment replicate joins, skewed joins, and merge joins.
  710. For more information see <a href="perf.html#Specialized-Joins">Specialized Joins</a>.</p>
  711. </section>
  712. <!-- +++++++++++++++++++++++++++++++ -->
  713. <section id="parallel">
  714. <title>Use the Parallel Features</title>
  715. <p>You can set the number of reduce tasks for the MapReduce jobs generated by Pig using two parallel features.
  716. (The parallel features only affect the number of reduce tasks. Map parallelism is determined by the input file, one map for each HDFS block.)</p>
  717. <p><strong>You Set the Number of Reducers</strong></p>
  718. <p>Use the <a href="cmds.html#set">set default parallel</a> command to set the number of reducers at the script level.</p>
  719. <p>Alternatively, use the PARALLEL clause to set the number of reducers at the operator level.
  720. (In a script, the value set via the PARALLEL clause will override any value set via "set default parallel.")
  721. You can include the PARALLEL clause with any operator that starts a reduce phase:
  722. <a href="basic.html#COGROUP">COGROUP</a>,
  723. <a href="basic.html#CROSS">CROSS</a>,
  724. <a href="basic.html#DISTINCT">DISTINCT</a>,
  725. <a href="basic.html#GROUP">GROUP</a>,
  726. <a href="basic.html#JOIN-inner">JOIN (inner)</a>,
  727. <a href="basic.html#JOIN-outer">JOIN (outer)</a>, and
  728. <a href="basic.html#ORDER-BY">ORDER BY</a>.
  729. </p>
  730. <p>The number of reducers you need for a particular construct in Pig that forms a MapReduce boundary depends entirely on (1) your data and the number of intermediate keys you are generating in your mappers and (2) the partitioner and distribution of map (combiner) output keys. In the best cases we have seen that a reducer processing about 1 GB of data behaves efficiently.</p>
  731. <p><strong>Let Pig Set the Number of Reducers</strong></p>
  732. <p>If neither "set default parallel" nor the PARALLEL clause are used, Pig sets the number of reducers using a heuristic based on the size of the input data. You can set the values for these properties:</p>
  733. <ul>
  734. <li>pig.exec.reducers.bytes.per.reducer - Defines the number of input bytes per reduce; default value is 1000*1000*1000 (1GB).</li>
  735. <li>pig.exec.reducers.max - Defines the upper bound on the number of reducers; default is 999. </li>
  736. </ul>
  737. <p></p>
  738. <p>The formula, shown below, is very simple and will improve over time. The computed value takes all inputs within the script into account and applies the computed value to all the jobs within Pig script.</p>
  739. <p><code>#reducers = MIN (pig.exec.reducers.max, total input size (in bytes) / bytes per reducer) </code></p>
  740. <p><strong>Examples</strong></p>
  741. <p>In this example PARALLEL is used with the GROUP operator. </p>
  742. <source>
  743. A = LOAD 'myfile' AS (t, u, v);
  744. B = GROUP A BY t PARALLEL 18;
  745. ...
  746. </source>
  747. <p>In this example all the MapReduce jobs that get launched use 20 reducers.</p>
  748. <source>
  749. SET default_parallel 20;
  750. A = LOAD myfile.txt USING PigStorage() AS (t, u, v);
  751. B = GROUP A BY t;
  752. C = FOREACH B GENERATE group, COUNT(A.t) as mycount;
  753. D = ORDER C BY mycount;
  754. STORE D INTO mysortedcount USING PigStorage();
  755. </source>
  756. </section>
  757. <!-- +++++++++++++++++++++++++++++++ -->
  758. <section id="limit">
  759. <title>Use the LIMIT Operator</title>
  760. <p>Often you are not interested in the entire output but rather a sample or top results. In such cases, using LIMIT can yield a much better performance as we push the limit as high as possible to minimize the amount of data travelling through the pipeline. </p>
  761. <p>Sample:
  762. </p>
  763. <source>
  764. A = load 'myfile' as (t, u, v);
  765. B = limit A 500;
  766. </source>
  767. <p>Top results: </p>
  768. <source>
  769. A = load 'myfile' as (t, u, v);
  770. B = order A by t;
  771. C = limit B 500;
  772. </source>
  773. </section>
  774. <!-- +++++++++++++++++++++++++++++++ -->
  775. <section id="distinct">
  776. <title>Prefer DISTINCT over GROUP BY/GENERATE</title>
  777. <p>To extract unique values from a column in a relation you can use DISTINCT or GROUP BY/GENERATE. DISTINCT is the preferred method; it is faster and more efficient.</p>
  778. <p>Example using GROUP BY - GENERATE:</p>
  779. <source>
  780. A = load 'myfile' as (t, u, v);
  781. B = foreach A generate u;
  782. C = group B by u;
  783. D = foreach C generate group as uniquekey;
  784. dump D;
  785. </source>
  786. <p>Example using DISTINCT:</p>
  787. <source>
  788. A = load 'myfile' as (t, u, v);
  789. B = foreach A generate u;
  790. C = distinct B;
  791. dump C;
  792. </source>
  793. </section>
  794. <!-- +++++++++++++++++++++++++++++++ -->
  795. <section id="compression">
  796. <title>Compress the Results of Intermediate Jobs</title>
  797. <p>If your Pig script generates a sequence of MapReduce jobs, you can compress the output of the intermediate jobs using LZO compression. (Use the <a href="test.html#EXPLAIN">EXPLAIN</a> operator to determine if your script produces multiple MapReduce Jobs.)</p>
  798. <p>By doing this, you will save HDFS space used to store the intermediate data used by PIG and potentially improve query execution speed. In general, the more intermediate data that is generated, the more benefits in storage and speed that result.</p>
  799. <p>You can set the value for these properties:</p>
  800. <ul>
  801. <li>pig.tmpfilecompression - Determines if the temporary files should be compressed or not (set to false by default).</li>
  802. <li>pig.tmpfilecompression.codec - Specifies which compression codec to use. Currently, Pig accepts "gz" and "lzo" as possible values. However, because LZO is under GPL license (and disabled by default) you will need to configure your cluster to use the LZO codec to take advantage of this feature. For details, see http://code.google.com/p/hadoop-gpl-compression/wiki/FAQ.</li>
  803. </ul>
  804. <p></p>
  805. <p>On the non-trivial queries (one ran longer than a couple of minutes) we saw significant improvements both in terms of query latency and space usage. For some queries we saw up to 96% disk saving and up to 4x query speed up. Of course, the performance characteristics are very much query and data dependent and testing needs to be done to determine gains. We did not see any slowdown in the tests we peformed which means that you are at least saving on space while using compression.</p>
  806. <p>With gzip we saw a better compression (96-99%) but at a cost of 4% slowdown. Thus, we don't recommend using gzip. </p>
  807. <p><strong>Example</strong></p>
  808. <source>
  809. -- launch Pig script using lzo compression
  810. java -cp $PIG_HOME/pig.jar
  811. -Djava.library.path=&lt;path to the lzo library&gt;
  812. -Dpig.tmpfilecompression=true
  813. -Dpig.tmpfilecompression.codec=lzo org.apache.pig.Main myscript.pig
  814. </source>
  815. </section>
  816. <!-- +++++++++++++++++++++++++++++++ -->
  817. <section id="combine-files">
  818. <title>Combine Small Input Files</title>
  819. <p>Processing input (either user input or intermediate input) from multiple small files can be inefficient because a separate map has to be created for each file. Pig can now combined small files so that they are processed as a single map.</p>
  820. <p>You can set the values for these properties:</p>
  821. <ul>
  822. <li>pig.maxCombinedSplitSize Specifies the size, in bytes, of data to be processed by a single map. Smaller files are combined untill this size is reached. </li>
  823. <li>pig.splitCombination Turns combine split files on or off (set to true by default).</li>
  824. </ul>
  825. <p></p>
  826. <p>This feature works with <a href="func.html#PigStorage">PigStorage</a>. However, if you are using a custom loader, please note the following:</p>
  827. <ul>
  828. <li>If your loader implementation makes use of the PigSplit object passed through the prepareToRead method, then you may need to rebuild the loader since the definition of PigSplit has been modified. </li>
  829. <li>The loader must be stateless across the invocations to the prepareToRead method. That is, the method should reset any internal states that are not affected by the RecordReader argument.</li>
  830. <li>If a loader implements IndexableLoadFunc, or implements OrderedLoadFunc and CollectableLoadFunc, its input splits won't be subject to possible combinations.</li>
  831. </ul>
  832. <p></p>
  833. </section>
  834. </section>
  835. <!-- ==================================================================== -->
  836. <!-- SPECIALIZED JOINS-->
  837. <section id="specialized-joins">
  838. <title>Specialized Joins</title>
  839. <!-- FRAGMENT REPLICATE JOINS-->
  840. <!-- +++++++++++++++++++++++++++++++ -->
  841. <section id="replicated-joins">
  842. <title>Replicated Joins</title>
  843. <p>Fragment replicate join is a special type of join that works well if one or more relations are small enough to fit into main memory.
  844. In such cases, Pig can perform a very efficient join because all of the hadoop work is done on the map side. In this type of join the
  845. large relation is followed by one or more small relations. The small relations must be small enough to fit into main memory; if they
  846. don't, the process fails and an error is generated.</p>
  847. <section>
  848. <title>Usage</title>
  849. <p>Perform a replicated join with the USING clause (see <a href="basic.html#JOIN-inner">JOIN (inner)</a> and <a href="basic.html#JOIN-outer">JOIN (outer)</a>).
  850. In this example, a large relation is joined with two smaller relations. Note that the large relation comes first followed by the smaller relations;
  851. and, all small relations together must fit into main memory, otherwise an error is generated. </p>
  852. <source>
  853. big = LOAD 'big_data' AS (b1,b2,b3);
  854. tiny = LOAD 'tiny_data' AS (t1,t2,t3);
  855. mini = LOAD 'mini_data' AS (m1,m2,m3);
  856. C = JOIN big BY b1, tiny BY t1, mini BY m1 USING 'replicated';
  857. </source>
  858. </section>
  859. <section>
  860. <title>Conditions</title>
  861. <p>Fragment replicate joins are experimental; we don't have a strong sense of how small the small relation must be to fit
  862. into memory. In our tests with a simple query that involves just a JOIN, a relation of up to 100 M can be used if the process overall
  863. gets 1 GB of memory. Please share your observations and experience with us.</p>
  864. </section>
  865. </section>
  866. <!-- END FRAGMENT REPLICATE JOINS-->
  867. <!-- +++++++++++++++++++++++++++++++ -->
  868. <!-- SKEWED JOINS-->
  869. <section id="skewed-joins">
  870. <title>Skewed Joins</title>
  871. <p>
  872. Parallel joins are vulnerable to the presence of skew in the underlying data.
  873. If the underlying data is sufficiently skewed, load imbalances will swamp any of the parallelism gains.
  874. In order to counteract this problem, skewed join computes a histogram of the key space and uses this
  875. data to allocate reducers for a given key. Skewed join does not place a restriction on the size of the input keys.
  876. It accomplishes this by splitting the left input on the join predicate and streaming the right input. The left input is
  877. sampled to create the histogram.
  878. </p>
  879. <p>
  880. Skewed join can be used when the underlying data is sufficiently skewed and you need a finer
  881. control over the allocation of reducers to counteract the skew. It should also be used when the data
  882. associated with a given key is too large to fit in memory.
  883. </p>
  884. <section>
  885. <title>Usage</title>
  886. <p>Perform a skewed join with the USING clause (see <a href="basic.html#JOIN-inner">JOIN (inner)</a> and <a href="basic.html#JOIN-outer">JOIN (outer)</a>). </p>
  887. <source>
  888. big = LOAD 'big_data' AS (b1,b2,b3);
  889. massive = LOAD 'massive_data' AS (m1,m2,m3);
  890. C = JOIN big BY b1, massive BY m1 USING 'skewed';
  891. </source>
  892. </section>
  893. <section>
  894. <title>Conditions</title>
  895. <p>
  896. Skewed join will only work under these conditions:
  897. </p>
  898. <ul>
  899. <li>Skewed join works with two-table inner join. Currently we do not support more than two tables for skewed join.
  900. Specifying three-way (or more) joins will fail validation. For such joins, we rely on you to break them up into two-way joins.</li>
  901. <li>The pig.skewedjoin.reduce.memusage Java parameter specifies the fraction of heap available for the
  902. reducer to perform the join. A low fraction forces Pig to use more reducers but increases
  903. copying cost. We have seen good performance when we set this value
  904. in the range 0.1 - 0.4. However, note that this is hardly an accurate range. Its value
  905. depends on the amount of heap available for the operation, the number of columns
  906. in the input and the skew. An appropriate value is best obtained by conducting experiments to achieve
  907. a good performance. The default value is 0.5. </li>
  908. <li>Skewed join does not address (balance) uneven data distribution across reducers.
  909. However, in most cases, skewed join ensures that the join will finish (however slowly) rather than fail.
  910. </li>
  911. </ul>
  912. </section>
  913. </section><!-- END SKEWED JOINS-->
  914. <!-- +++++++++++++++++++++++++++++++ -->
  915. <!-- MERGE JOIN-->
  916. <section id="merge-joins">
  917. <title>Merge Joins</title>
  918. <p>
  919. Often user data is stored such that both inputs are already sorted on the join key.
  920. In this case, it is possible to join the data in the map phase of a MapReduce job.
  921. This provides a significant performance improvement compared to passing all of the data through
  922. unneeded sort and shuffle phases.
  923. </p>
  924. <p>
  925. Pig has implemented a merge join algorithm, or sort-merge join. It works on pre-sorted data, and does not
  926. sort data for you. See Conditions, below, for restrictions that apply when using this join algorithm.
  927. Pig implements the merge join algorithm by selecting the left input of the join to be the input file for the map phase,
  928. and the right input of the join to be the side file. It then samples records from the right input to build an
  929. index that contains, for each sampled record, the key(s) the filename and the offset into the file the record
  930. begins at. This sampling is done in the first MapReduce job. A second MapReduce job is then initiated,
  931. with the left input as its input. Each map uses the index to seek to the appropriate record in the right
  932. input and begin doing the join.
  933. </p>
  934. <section>
  935. <title>Usage</title>
  936. <p>Perform a merge join with the USING clause (see <a href="basic.html#JOIN-inner">JOIN (inner)</a> and <a href="basic.html#JOIN-outer">JOIN (outer)</a>). </p>
  937. <source>
  938. C = JOIN A BY a1, B BY b1, C BY c1 USING 'merge';
  939. </source>
  940. </section>
  941. <section>
  942. <title>Conditions</title>
  943. <p><strong>Condition A</strong></p>
  944. <p>Inner merge join (between two tables) will only work under these conditions: </p>
  945. <ul>
  946. <li>Data must come directly from either a Load or an Order statement.</li>
  947. <li>There may be filter statements and foreach statements between the sorted data source and the join statement. The foreach statement should meet the following conditions:
  948. <ul>
  949. <li>There should be no UDFs in the foreach statement. </li>
  950. <li>The foreach statement should not change the position of the join keys. </li>
  951. <li>There should be no transformation on the join keys which will change the sort order. </li>
  952. </ul>
  953. </li>
  954. <li>Data must be sorted on join keys in ascending (ASC) order on both sides.</li>
  955. <li>If sort is provided by the loader, rather than an explicit Order operation, the right-side loader must implement either the {OrderedLoadFunc} interface or {IndexableLoadFunc} interface.</li>
  956. <li>Type information must be provided for the join key in the schema.</li>
  957. </ul>
  958. <p></p>
  959. <p>The PigStorage loader satisfies all of these conditions.</p>
  960. <p></p>
  961. <p><strong>Condition B</strong></p>
  962. <p>Outer merge join (between two tables) and inner merge join (between three or more tables) will only work under these conditions: </p>
  963. <ul>
  964. <li>No other operations can be done between the load and join statements. </li>
  965. <li>Data must be sorted on join keys in ascending (ASC) order on both sides. </li>
  966. <li>Left-most loader must implement {CollectableLoader} interface as well as {OrderedLoadFunc}. </li>
  967. <li>All other loaders…

Large files files are truncated, but you can click here to view the full file