├── .gitignore ├── .travis.yml ├── LICENSE ├── README.markdown ├── lib ├── snakeyaml-1.11.jar └── ua_parser │ └── ua-parser │ └── 1.2.2-LS │ ├── ua-parser-1.2.2-LS.jar │ └── ua-parser-1.2.2-LS.pom ├── pom.xml └── src └── main └── java └── com └── livingsocial └── hive ├── Base32.java ├── Utils.java ├── udf ├── AESDecrypt.java ├── ConcatArray.java ├── CurDate.java ├── CurDateTime.java ├── DayOfWeek.java ├── GenericUDFLeast.java ├── GenericUDFLeastNonNull.java ├── Hash.java ├── ILike.java ├── InArray.java ├── IndexOf.java ├── IndexOfMaxElem.java ├── IsoYearWeek.java ├── MaxDate.java ├── Md5.java ├── MinDate.java ├── Rank.java ├── SMax.java ├── SMin.java ├── ScriptedUDAF.java ├── ScriptedUDF.java ├── Sha1.java ├── StripHTML.java ├── Tokenize.java ├── UDFQuarter.java ├── URLDecode.java ├── UnixLiberalTimestamp.java ├── UserAgentParser.java ├── ZTest.java └── gpsDistanceFrom.java ├── udtf ├── BinCase.java ├── FirstN.java └── Intervals.java └── utils ├── KISSInspector.java └── ScriptingHelper.java /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | dist 3 | bin 4 | target 5 | .* 6 | dependency-reduced-pom.xml 7 | 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk7 4 | - openjdk6 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | # HiveSwarm: User Defined Functions for Hive 2 | 3 | [Hive](http://hive.apache.org/) provides a number of [useful user defined functions](http://wiki.apache.org/hadoop/Hive/LanguageManual/UDF), but there is certainly room for more. HiveSwarm provides a collection of additional useful functions. 4 | HiveSwarm has been tested with mrv1 on cdh4 and YARN on cdh5 5 | 6 | ## Installation 7 | Assuming you have Hadoop and Hive set up (along with your HADOOP_HOME and HIVE_HOME environment variables set correctly), run the following: 8 | 9 | Download and install Maven http://maven.apache.org/download.cgi 10 | git clone git://github.com/livingsocial/HiveSwarm.git 11 | cd HiveSwarm 12 | mvn package 13 | 14 | You should now have a jar file in your *target* folder named **HiveSwarm.jar**. 15 | 16 | ## Usage 17 | Each of the following methods assumes you have first run the following in your hive session: 18 | 19 | add jar /path/to/HiveSwarm.jar; 20 | 21 | After you do that, you can create temporary functions as needed. 22 | 23 | ### max_date(date string, ...) 24 | Run: 25 | 26 | create temporary function max_date as 'com.livingsocial.hive.udf.MaxDate' 27 | 28 | *max_date* takes any number of date ('2011-01-10') or date time ('2011-01-10 10:01:00') or null arguments. The max date among non-null arguments is returned. 29 | 30 | ### min_date(date string, ...) 31 | Same as *max_date*, but returns min. 32 | 33 | ### intervals(group column, interval column) 34 | Run: 35 | 36 | create temporary function intervals as 'com.livingsocial.hive.udtf.Intervals'; 37 | 38 | *intervals* takes a group column argument and an interval argument and returns a two column table with the intervals between the rows per group. The interval column can be a numerical or date/datetime (string) column. 39 | 40 | ### smax(column) / smin(column) 41 | Run: 42 | 43 | create temporary function smin as 'com.livingsocial.hive.udf.SMin'; 44 | 45 | *smin* and *smax* act just like *min* and *max* but treat string columns like timestamps. 46 | 47 | 48 | ### ilike(colname, pattern) 49 | Same as regular Hive like but is case irrespective (just like MySQL's like). Use is like: 50 | 51 | create temporary function ilike as 'com.livingsocial.hive.udf.ILike'; 52 | select city_name, count from city_counts where ilike(city_name, "%baltimore%"); 53 | 54 | ### first_n(group column, value column, count) 55 | Table generating function that returns up to count rows per group column of the group and value columns. 56 | 57 | create temporary function first_n as 'com.livingsocial.hive.udtf.FirstN'; 58 | select first_n(person_id, value, 20) as (one, two) from person_values; 59 | 60 | This will output the first 20 rows (by person_id) of (person_id, value). 61 | 62 | ### unix_liberal_timestamp(datetimestring) 63 | Same as regular Hive unix_timestamp but can handle "yyyy-MM-dd HH:mm:ss" as well as "yyyy-MM-dd". Use is like: 64 | 65 | create temporary function unix_liberal_timestamp as 'com.livingsocial.hive.udf.UnixLiberalTimestamp'; 66 | select city_name, unix_liberal_timestsamp(created_at) from cities; 67 | 68 | 69 | ### index_of(needle, haystack[, startIndex]) 70 | Get first index of string needle in string haystack (optionally, starting search from startIndex). Returns -1 if not found. 71 | 72 | create temporary function index_of as 'com.livingsocial.hive.udf.IndexOf'; 73 | select email from users where index_of('@', email) > -1; 74 | 75 | 76 | ### in_array(needle, haystack) 77 | Returns true if needle (primitive) is in haystack (array of primitives) and if needle is not null. Returns false otherwise. 78 | 79 | create temporary function in_array as 'com.livingsocial.hive.udf.InArray'; 80 | select in_array(user_id, array(1,2,3,4)) from users; 81 | 82 | 83 | ### dayofweek(date) 84 | Get day of week (as integer) from date (of format "yyyy-mm-dd"). Sunday is 1, Monday 2, etc. 85 | 86 | create temporary function dayofweek as 'com.livingsocial.hive.udf.DayOfWeek'; 87 | select dayofweek(to_date(created_at)) from src; 88 | 89 | 90 | ### bin_case(long, array(names)) 91 | Get representations of bits in a bitfield (it's like the bin UDF and a long case statement - hence, bin_case). If long represents a (big endian) bit field, bin_case will generate a single column table with a row for each positive bit containing the corresponding value in names. For instance, here are some examples: 92 | 93 | create temporary function bin_case as 'com.livingsocial.hive.udtf.BinCase'; 94 | select bin_case(1, array("foo", "bar", "baz")) as c from source; 95 | > foo 96 | select bin_case(2, array("foo", "bar", "baz")) as c from source; 97 | > bar 98 | select bin_case(3, array("foo", "bar", "baz")) as c from source; 99 | > foo 100 | > bar 101 | select bin_case(4, array("foo", "bar", "baz")) as c from source; 102 | > baz 103 | select bin_case(5, array("foo", "bar", "baz")) as c from source; 104 | > foo 105 | > baz 106 | select bin_case(7, array("foo", "bar", "baz")) as c from source; 107 | > foo 108 | > bar 109 | > baz 110 | ... 111 | 112 | 113 | ### aes_decrypt(encrypted_string, key) 114 | AES decrypt the given string (which should be Base32 hex encoded) with the given key. 115 | 116 | create temporary function aes_decrypt as 'com.livingsocial.hive.udf.AESDecrypt'; 117 | select aes_decrypt(encrypted_data, "textkey") from secure_storage; 118 | 119 | This will require downloading 120 | [this file](http://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/VerifyItem-Start/jce_policy-6.zip?BundledLineItemUUID=ahKJ_hCvnkoAAAEx4CEpHj3B&OrderID=6N.J_hCvGj4AAAEx1iEpHj3B&ProductID=33bACUFBf50AAAEYiO45AXuH&FileName=/jce_policy-6.zip) 121 | from Sun and installing to /usr/java/jdk1.6.0_22/jre/lib/security (due to cryptographic export controls). 122 | 123 | ### gps_distance_from(latitude1 double, longitude1 double, latitude2 double, longitude2 double [, Text options]) 124 | Calculate the distance between two gps coordinates, return result in miles (default). Options accepts a parameter of 'km' - returns result in km 125 | 126 | create temporary function gps_distance_from as 'com.livingsocial.hive.udf.gpsDistanceFrom' 127 | hive -e "select gps_distance_from(38, -97, 37.33181, -122.02955) from test_coordinates" 128 | > 1365.5982379566033 129 | hive -e "select gps_distance_from(38, -97, 37.33181, -122.02955, 'km') from test_coordinates" 130 | > 2197.717330666032 131 | 132 | Coordinates are entered as doubles, and a double is returned. If any of the latitude or longitude values are passed in as null, null is returned 133 | 134 | ### index_of_max_elem(array) 135 | Return the index of an element greater than or equal to all of the other elements. In case of equality earlier elements will be preferred. 136 | 137 | create temporary function index_of_max_elem as 'com.livingsocial.hive.udf.IndexOfMaxElem'; 138 | select index_of_max_elem(array(3,5,9,2)) from some_table; 139 | > 2 140 | 141 | ### user_agent_parser(user_agent string [, options string]) 142 | Parses a user agent string into something a little more legible. By default (without the options field entered), returns a json parameter with all parsed data. 143 | 144 | Accepts any of the following entered as a string, as user options 145 | 146 | os, os_family, os_major, os_minor, ua, ua_family, ua_major, ua_minor, device 147 | 148 | os and ua will return json, with _family, _major and _minor returned as well; other options will return a string. 149 | 150 | Note: the underlying parser library is somewhat tuned to LivingSocial's interests; It includes some email clients, and reports AOL windows as AOL (as opposed to MSIE). This library builds off of http://github.com/p5k6/ua-parser. Tobie's ua-parser can be dropped in if needed/desired (http://github.com/tobie/ua-parser) 151 | 152 | create temporary function user_agent_parser as 'com.livingsocial.hive.udf.UserAgentParser'; 153 | 154 | select user_agent_parser(user_agent) from some_table; 155 | > {user_agent: {family: "Firefox", major: "12", minor: "0", patch: null}, os: {family: "Windows", major: "7", minor: null, patch: null, patch_minor: null}, device: {family: null}} 156 | 157 | select user_agent_parser(user_agent, 'os') from some_table; 158 | > {family: "Windows", major: "7", minor: null, patch: null, patch_minor: null} 159 | 160 | select user_agent_parser(user_agent, 'os_family') from some_table; 161 | > "Windows" 162 | 163 | ### curdate() 164 | Returns the current date in the form 'YYYY-MM-DD' 165 | 166 | create temporary function curdate as 'com.livingsocial.hive.udf.Curdate'; 167 | select curdate() from some_table; 168 | > 2012-12-26 169 | 170 | ### curdatetime() 171 | Returns the current date and time in the form 'YYYY-MM-DD HH:mm:ss' 172 | 173 | create temporary function curdatetime as 'com.livingsocial.hive.udf.CurDateTime'; 174 | select curdatetime() from some_table; 175 | > 2012-12-26 13:26:25 176 | 177 | ### iso_year_of_week(some_date string) 178 | Returns the year of an ISO week number. Same as unix date's %G. Used in conjunction with week_of_year. Ensures that each week/year combination has 7 days. Accepts input in the form 'YYYY-MM-DD' and 'YYYY-MM-DD HH:mm:ss'. 179 | 180 | create temporary function iso_year_of_week as 'com.livingsocial.hive.udf.IsoYearWeek'; 181 | select iso_year_of_week('2012-01-01') from some_table; 182 | > 2011 183 | 184 | ### md5(string_to_hash string) 185 | Returns an md5 hash of the string passed in 186 | Fork of datamine's md5 hash function; originally found at https://gist.github.com/1050002 187 | 188 | create temporary function md5 as 'com.livingsocial.hive.udf.Md5'; 189 | select md5('test data') from some_table; 190 | > eb733a00c0c9d336e65691a37ab54293 191 | 192 | ### sha1(string_to_hash string) 193 | Returns the sha1 hash of the string passed in 194 | 195 | create temporary function sha1 as 'com.livingsocial.hive.udf.Sha1'; 196 | select sha1('test data') from some_table; 197 | > f48dd853820860816c75d54d0f584dc863327a7c 198 | 199 | ### ls_hash(something_to_hash string, [some_salt string, [debug string]] 200 | Returns a deterministic 'random' number based on the sha1 has of the passed 201 | in string and salt. This is intended to be used in place of many rand() 202 | uses. It has the benefit of being repeatable, consistent, and easily 203 | implementable by any system. An id for a row is required as the first 204 | input. An optional string salt can be passed in as the second argument. 205 | A third string can be passed in and the output will change to a string 206 | output showing internal debugging information. 207 | 208 | This implementation can be used in other systems so the same samples can 209 | be shared by only sharing the logic and the salt. The pseudo-code logic 210 | for this is: 211 | 212 | to_hash = something_to_hash + some_salt 213 | sha1_hash = sha1(to_hash.to_utf8_bytes()) 214 | hex = sha1.substring(0,14) 215 | return Long.parse_hex(hex) / (2^56) 216 | 217 | Examples: 218 | 219 | -- simple example to extract a 10% sample 220 | select * from some_table where ls_hash(id, 'my salt') < 0.1; 221 | 222 | -- Label 2 non-overlapping groups A and B with 50% in each 223 | select if(ls_hash(id, 'some other salt')<=0.5, 'A', 'B') as group_label, id, name from some_table; 224 | 225 | ### p_rank(column1, column2....) 226 | Returns a ranking of each row within a group of rows 227 | 228 | Forked from Edward Capriolo's branch - https://github.com/edwardcapriolo/hive-rank/. Wanted to fit the function into LivingSocial's Hive UDF implementation. 229 | original copyright: "Copyright 2012 m6d Media6degrees" 230 | 231 | ``` 232 | create temporary function p_rank as 'com.livingsocial.hive.udf.Rank'; 233 | 234 | SELECT 235 | category,country,product,sales,rank 236 | FROM ( 237 | SELECT 238 | category,country,product,sales, 239 | p_rank(category, country) rank 240 | FROM ( 241 | SELECT 242 | category,country,product, 243 | sales 244 | FROM p_rank_demo 245 | DISTRIBUTE BY 246 | category,country 247 | SORT BY 248 | category,country,sales desc) t1) t2 249 | 250 | > movies gb Star Wars iv 300 1 251 | > movies gb Star Wars iii 200 2 252 | > movies gb spiderman 150 3 253 | > movies gb Goldfinger 100 4 254 | > movies us Star Wars v 300 1 255 | > movies us Star Wars iii 200 2 256 | > movies us Star Wars iv 150 3 257 | > movies us casablanca 100 4 258 | ``` 259 | 260 | ### concat_array(delimiter string, array) 261 | Concatenates the elements of the array separated by the delimiter. Note: This duplicates the functionality of 262 | the built in concat_ws UDF, but handles any primitive types in the array instead of only strings. 263 | 264 | create temporary function concat_array as 'com.livingsocial.hive.udf.ConcatArray'; 265 | -- Generate a comma separated list of products in a category 266 | select category, concat_array(',', collect_set(product)) from products group by category; 267 | 268 | ### least(column1, column2.....) 269 | returns the lowest value amongst several columns 270 | 271 | nulls are considered to be the lowest value (which fits how the oracle function least() works). 272 | 273 | Inspired by NexR's 'greatest' function (https://github.com/nexr/hive-udf) 274 | 275 | create temporary function least as 'com.livingsocial.hive.udf.GenericUDFLeast'; 276 | select least('2013-05-24','2012-05-09','1004-67-83') from test limit 1 277 | > 1004-67-83 278 | select least(0,1,3,4,65) from test limit 1 279 | > 0 280 | 281 | ### least_non_null(column1, column2.....) 282 | returns the lowest value amongst several columns, excluding nulls. 283 | 284 | create temporary function least_non_null as 'com.livingsocial.hive.udf.GenericUDFLeastNonNull'; 285 | select least('2013-05-24','2012-05-09','1004-67-83',null) from test limit 1 286 | > 1004-67-83 287 | select least(0,1,3,4,65) from test limit 1 288 | > 0 289 | 290 | 291 | ### z_test(double controlAvg, double controlStddev, long controlSize, double treatmentAvg, double treatmentStddev, long treatmentSize) 292 | Performs a Z-test to compare the mean of the control group vs. the mean of the treatment group. 293 | Returns the two sided p-value for the given Z-test. 294 | 295 | create temporary function z_test as 'com.livingsocial.hive.udf.ZTest'; 296 | SELECT z_test(avg(if(control=1, revenue, 0)), stddev_pop(if(control=1, revenue, 0)), sum(if(control=1, 1, 0)), 297 | avg(if(control=0, revenue, 0)), stddev_pop(if(control=0, revenue, 0)), sum(if(control=0, 1, 0))) 298 | FROM revenue_table; 299 | 300 | Alternate form: 301 | 302 | z_test(critical_value) -- This skips the rest and just does a normal dist lookup" 303 | 304 | 305 | 306 | ### strip_html(string html) 307 | Strips HTML tags and elements from a string using the jsoup parser. 308 | 309 | create temporary function strip_html as 'com.livingsocial.hive.udf.StripHTML'; 310 | select strip_html("Hello World!
") from test limit 1; 311 | > Hello World! 312 | 313 | 314 | ### tokenize(string text) 315 | Tokenizes a string of natural language text into an array of stemmed lower-case words. 316 | 317 | Common english stop-words such as "a" and "the" will be removed. 318 | 319 | Stemming is performed by the 320 | [KStemFilter](https://lucene.apache.org/core/4_5_1/analyzers-common/org/apache/lucene/analysis/en/KStemFilter.html) 321 | from Apache Lucene, which is less aggressive than the Porter stemmer, and results in stems that are still dictionary words. 322 | 323 | This function also strips out HTML and converts accented characters to their ASCII equivalents. 324 | 325 | create temporary function tokenize as 'com.livingsocial.hive.udf.Tokenize'; 326 | select tokenize("The horses jumped with élan") from test limit 1; 327 | > [horse, jump, elan] 328 | 329 | ### scriptedUDF(script_to_run, language, return_type, script_arg1, script_arg_2, ....) 330 | 331 | This will run a javax.script based UDF that can be defined as a literal script in the UDF call or as a file in HDFS. 332 | 333 | Function descriptions in the script: 334 | 335 | * evaluate receives all the extra script_arguments passed in the scriptedUDF call and returns an object adhering to the defined return_type 336 | 337 | Language is the javax.script engine name. Additional languages can be added by adding the jar implementing the scripting engine ('add jar groovy-all.jar;' or similar) 338 | Return_type is a hive style data definition ('string', 'bigint', 'array>', ...) 339 | 340 | Example: 341 | 342 | ```sql 343 | create temporary function scriptedUDF as 'com.livingsocial.hive.udf.ScriptedUDF'; 344 | -- Gather complex data combining groups and individual rows without joins 345 | select person_id, purchase_data['time'], purchase_data['diff'], 346 | purchase_data['product'], purchase_data['purchase_count'] as pc, 347 | purchase_data['blah'] 348 | from ( 349 | select person_id, scriptedUDF(' 350 | require "json" 351 | def evaluate(data) 352 | # This gathers all the data about purchases by person in one place so complex infromation can be gathered while avoiding complex joins 353 | # Note: In order for this to work all the data passed into scriptedUDF for a row needs to fit into memory 354 | tmp = [] # convert things over to a ruby array 355 | tmp.concat(data) 356 | tmp.sort_by! { |a| a.get("time") } # for the time differences 357 | last=0 358 | tmp.map{ |row| 359 | # Compute the time difference between purchases and add the total purchase count per person 360 | t = row["time"] 361 | # The parts that would be much more difficult to generate with SQL 362 | row["diff"] = t - last 363 | row["purchase_count"] = tmp.length 364 | row["first_purchase"] = tmp[0]["time"] 365 | row["last_purchase"] = tmp[-1]["time"] 366 | # This shows that built-in libraries are available 367 | row["blah"] = JSON.generate({"id" => row["id"]}) 368 | last = t 369 | row 370 | } 371 | end', 'ruby', 'array>', 372 | -- gather all the data about purchases by people so it can all be passed into the evaluate function 373 | bh_collect(map( -- Note, bh_collect is from Klouts Brickhouse and allows collecting any type, see https://github.com/klout/brickhouse/ 374 | 'time', unix_liberal_timestamp(purchase_time), 375 | 'product', product_id)) ) as all_data 376 | from purchases 377 | group by person_id 378 | ) foo 379 | -- explode the data back out so it is available in flattened form 380 | lateral view explode(all_data) bar as purchase_data 381 | ``` 382 | 383 | 384 | Alternate syntax: 385 | ```sql 386 | create temporary function scriptedUDF as 'com.livingsocial.hive.udf.ScriptedUDF'; 387 | SELECT scriptedUDF('/my_scripts/reusable.rb', 'ruby', 'map', val1, val2) FROM src_table; 388 | ``` 389 | This will load the script from the location in HDFS and will invoke the evaluate function. This function needs to return a map of strings keys and int values. 390 | 391 | 392 | 393 | ## Code Status 394 | [![Build Status](https://travis-ci.org/livingsocial/HiveSwarm.png)](https://travis-ci.org/livingsocial/HiveSwarm) 395 | 396 | ## Bugs / Contact 397 | Any bugs / request can be submited via tickets on [Github](https://github.com/livingsocial/HiveSwarm). 398 | 399 | -------------------------------------------------------------------------------- /lib/snakeyaml-1.11.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/livingsocial/HiveSwarm/8345130e3da37555c0ca36da538bfd4f4ee3c834/lib/snakeyaml-1.11.jar -------------------------------------------------------------------------------- /lib/ua_parser/ua-parser/1.2.2-LS/ua-parser-1.2.2-LS.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/livingsocial/HiveSwarm/8345130e3da37555c0ca36da538bfd4f4ee3c834/lib/ua_parser/ua-parser/1.2.2-LS/ua-parser-1.2.2-LS.jar -------------------------------------------------------------------------------- /lib/ua_parser/ua-parser/1.2.2-LS/ua-parser-1.2.2-LS.pom: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | ua_parser 5 | ua-parser 6 | jar 7 | 1.2.2-LS 8 | ua-parser 9 | https://github.com/p5k6/ua-parser/ 10 | 11 | UTF-8 12 | 13 | 14 | 15 | 16 | ua_parser 17 | ${basedir}/.. 18 | 19 | regexes.yaml 20 | 21 | 22 | 23 | 24 | 25 | ua_parser 26 | ${basedir}/../test_resources 27 | 28 | *.yaml 29 | 30 | 31 | 32 | 33 | 34 | 35 | org.yaml 36 | snakeyaml 37 | 1.10 38 | 39 | 40 | junit 41 | junit 42 | 4.10 43 | test 44 | 45 | 46 | org.hamcrest 47 | hamcrest-all 48 | 1.1 49 | test 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.livingsocial.hive.udf 5 | HiveSwarm 6 | jar 7 | 1.0-SNAPSHOT 8 | HiveSwarm 9 | https://github.com/livingsocial/HiveSwarm 10 | 11 | 12 | 13 | 14 | 15 | 16 | org.apache.maven.plugins 17 | maven-shade-plugin 18 | 2.1 19 | 20 | 21 | 22 | ua_parser:ua-parser 23 | org.yaml:snakeyaml 24 | org.jsoup:jsoup 25 | org.apache.lucene:lucene-analyzers-common 26 | org.apache.lucene:lucene-core 27 | org.jruby:jruby-complete 28 | org.apache.commons:commons-math 29 | 30 | 31 | 32 | 33 | 34 | package 35 | 36 | shade 37 | 38 | 39 | 40 | 41 | 42 | maven-compiler-plugin 43 | 2.0.2 44 | 45 | 1.6 46 | 1.6 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | Cloudera 4 repo 57 | https://repository.cloudera.com/artifactory/cloudera-repos/ 58 | 59 | 60 | 61 | in-project 62 | In Project Repo 63 | file://${project.basedir}/lib 64 | 65 | 66 | 67 | 68 | 69 | 76 | 77 | 78 | 79 | org.apache.hadoop 80 | hadoop-client 81 | 2.3.0-cdh5.1.2 82 | provided 83 | 84 | 85 | org.apache.hive 86 | hive-serde 87 | 0.12.0-cdh5.1.2 88 | provided 89 | 90 | 91 | org.apache.hive 92 | hive-exec 93 | 0.12.0-cdh5.1.2 94 | provided 95 | 96 | 97 | org.apache.hadoop 98 | hadoop-core 99 | 2.3.0-mr1-cdh5.1.2 100 | provided 101 | 102 | 103 | org.apache.hadoop 104 | hadoop-common 105 | 2.3.0-cdh5.1.2 106 | provided 107 | 108 | 109 | org.apache.hive 110 | hive-common 111 | 0.12.0-cdh5.1.2 112 | provided 113 | 114 | 115 | 116 | org.apache.commons 117 | commons-math 118 | 2.2 119 | compile 120 | 121 | 122 | 123 | org.apache.lucene 124 | lucene-core 125 | 4.5.1 126 | 127 | 128 | org.apache.lucene 129 | lucene-analyzers-common 130 | 4.5.1 131 | 132 | 133 | 134 | org.jsoup 135 | jsoup 136 | 1.7.2 137 | 138 | 139 | 140 | ua_parser 141 | ua-parser 142 | 1.2.2-LS 143 | 144 | 145 | org.yaml 146 | snakeyaml 147 | 1.10 148 | 149 | 150 | 151 | 152 | org.jruby 153 | jruby-complete 154 | 1.7.5 155 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/Base32.java: -------------------------------------------------------------------------------- 1 | /* Adapted from: 2 | * (PD) 2001 The Bitzi Corporation 3 | * Please see http://bitzi.com/publicdomain for more info. 4 | */ 5 | 6 | package com.livingsocial.hive; 7 | 8 | public class Base32 { 9 | private static final String base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; 10 | private static final int[] base32Lookup = { 11 | 0xFF,0xFF,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, // '0', '1', '2', '3', '4', '5', '6', '7' 12 | 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, // '8', '9', ':', ';', '<', '=', '>', '?' 13 | 0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G' 14 | 0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O' 15 | 0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W' 16 | 0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF, // 'X', 'Y', 'Z', '[', '\', ']', '^', '_' 17 | 0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06, // '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g' 18 | 0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o' 19 | 0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' 20 | 0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF // 'x', 'y', 'z', '{', '|', '}', '~', 'DEL' 21 | }; 22 | 23 | static public byte[] decode(final String base32) { 24 | int i, index, lookup, offset, digit; 25 | byte[] bytes = new byte[base32.length() * 5 / 8]; 26 | 27 | for(i = 0, index = 0, offset = 0; i < base32.length(); i++) { 28 | lookup = base32.charAt(i) - '0'; 29 | 30 | /* Skip chars outside the lookup table */ 31 | if ( lookup < 0 || lookup >= base32Lookup.length) { 32 | continue; 33 | } 34 | 35 | digit = base32Lookup[lookup]; 36 | 37 | /* If this digit is not in the table, ignore it */ 38 | if (digit == 0xFF) { 39 | continue; 40 | } 41 | 42 | if (index <= 3) { 43 | index = (index + 5) % 8; 44 | if (index == 0) { 45 | bytes[offset] |= digit; 46 | offset++; 47 | if(offset>=bytes.length) break; 48 | } else { 49 | bytes[offset] |= digit << (8 - index); 50 | } 51 | } else { 52 | index = (index + 5) % 8; 53 | bytes[offset] |= (digit >>> index); 54 | offset++; 55 | 56 | if(offset>=bytes.length) break; 57 | bytes[offset] |= digit << (8 - index); 58 | } 59 | } 60 | return bytes; 61 | } 62 | 63 | 64 | static public byte[] hexdecode(final String base32hex) { 65 | String values = "0123456789ABCDEFGHIJKLMNOPQRSTUV"; 66 | String hexvalues = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; 67 | String base32 = ""; 68 | String base32hexuc = base32hex.toUpperCase(); 69 | for(int i=0; i -1) 72 | base32 += Character.toString(hexvalues.charAt(index)); 73 | } 74 | return decode(base32); 75 | } 76 | } -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/Utils.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | 6 | 7 | public class Utils { 8 | 9 | private Utils() {} 10 | 11 | // Returns -1 if date can't be parsed 12 | public static long stringToTimestamp(String date) { 13 | long time = -1L; 14 | if(date.indexOf(" ") == -1) { 15 | try { 16 | time = (new SimpleDateFormat("yyyy-MM-dd")).parse(date).getTime() / 1000; 17 | } catch(ParseException pe) {} 18 | } else { 19 | try { 20 | time = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(date).getTime() / 1000; 21 | } catch(ParseException pe) {} 22 | } 23 | return time; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/AESDecrypt.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import com.livingsocial.hive.Base32; 4 | 5 | import org.apache.hadoop.hive.ql.exec.UDF; 6 | import org.apache.hadoop.hive.ql.exec.Description; 7 | import org.apache.hadoop.io.Text; 8 | 9 | import javax.crypto.spec.SecretKeySpec; 10 | import javax.crypto.Cipher; 11 | 12 | 13 | @Description( 14 | name = "aesdecrypt", 15 | value = "_FUNC_(str, key) - Returns unencrypted string based on AES key. Str must be base32hex encoded.", 16 | extended = "Example:\n" + 17 | " > SELECT aesdecrypt(credit_card_number, 'asd0fjas0df9asjfd09asjdf') FROM credit_cards;\n" + 18 | " 123456789456468466" 19 | ) 20 | public class AESDecrypt extends UDF { 21 | public Text evaluate(Text encrypted, Text key) { 22 | Text unencrypted = new Text(encrypted); 23 | if(encrypted != null && key != null) { 24 | try { 25 | SecretKeySpec skeySpec = new SecretKeySpec(key.toString().getBytes(), "AES"); 26 | Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); 27 | cipher.init(Cipher.DECRYPT_MODE, skeySpec); 28 | byte[] original = cipher.doFinal(Base32.hexdecode(encrypted.toString())); 29 | unencrypted.set(original); 30 | } catch (Exception e) {}; 31 | } 32 | return unencrypted; 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/ConcatArray.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.apache.hadoop.hive.ql.exec.Description; 6 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 7 | import org.apache.hadoop.hive.ql.metadata.HiveException; 8 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 9 | import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; 10 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 11 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 12 | 13 | import com.livingsocial.hive.utils.KISSInspector; 14 | 15 | @Description(name = "concat_array", value = "_FUNC_(sep, arr) - Returns a string with each element in the array arr with sep as the delimiter between elements") 16 | public class ConcatArray extends GenericUDF { 17 | public static final String FUNC = "concat_array"; 18 | private ListObjectInspector array_inspector; 19 | private KISSInspector element_inspector; 20 | 21 | static final Log LOG = LogFactory.getLog(InArray.class.getName()); 22 | 23 | @Override 24 | public ObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException { 25 | if(args.length != 2 || !KISSInspector.isPrimitive(args[0]) || !KISSInspector.isList(args[1])) 26 | throw new UDFArgumentException(FUNC + "() takes two arguments: a primitive and an array"); 27 | element_inspector = new KISSInspector(args[0]); 28 | array_inspector = (ListObjectInspector) args[1]; 29 | return PrimitiveObjectInspectorFactory.javaStringObjectInspector; 30 | } 31 | 32 | @Override 33 | public String evaluate(DeferredObject[] arguments) throws HiveException { 34 | StringBuilder out = new StringBuilder(); 35 | 36 | if(arguments[0].get() == null || arguments[1].get() == null) 37 | return null; 38 | 39 | Object element = arguments[0].get(); 40 | String sep = element_inspector.get(element).toString(); 41 | 42 | Object elist = arguments[1].get(); 43 | boolean first = true; 44 | int len = array_inspector.getListLength(elist); 45 | for(int i=0; i SELECT _FUNC_() FROM src LIMIT 1;\n" 20 | + " 2012-08-10\n" 21 | ) 22 | 23 | public class CurDate extends UDF { 24 | 25 | /** 26 | * returns the current date in fomrat 'yyyy-mm-dd' 27 | * 28 | * @return today's date in format 'yyyy-mm-dd' 29 | * string. 30 | */ 31 | 32 | private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 33 | 34 | private Text result = new Text(); 35 | static final Log LOG = LogFactory.getLog(CurDate.class.getName()); 36 | 37 | // private Text lastFormat = new Text(); 38 | 39 | // private Text defaultFormat = new Text("yyyy-MM-dd"); 40 | 41 | public Text evaluate() { 42 | Date date = new java.sql.Date(System.currentTimeMillis()); 43 | result.set(formatter.format(date)); 44 | return result; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/CurDateTime.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import java.util.Date; 4 | 5 | import org.apache.hadoop.hive.ql.exec.Description; 6 | import org.apache.hadoop.hive.ql.exec.UDF; 7 | import org.apache.hadoop.io.Text; 8 | import java.text.SimpleDateFormat; 9 | 10 | import com.livingsocial.hive.Utils; 11 | 12 | import org.apache.commons.logging.Log; 13 | import org.apache.commons.logging.LogFactory; 14 | 15 | @Description( 16 | name = "curdatetime", 17 | value = "_FUNC_() - Returns current date/time in format 'yyyy-mm-dd HH:MM:SS'", 18 | extended = "Examples:\n" 19 | + " > SELECT _FUNC_() FROM src LIMIT 1;\n" 20 | + " 2012-08-10 12:00:00\n" 21 | ) 22 | 23 | public class CurDateTime extends UDF { 24 | 25 | /** 26 | * returns the current date/time in fomrat 'yyyy-mm-dd' 27 | * 28 | * @return today's date in format 'yyyy-mm-dd' 29 | * string. 30 | */ 31 | 32 | private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 33 | 34 | private Text result = new Text(); 35 | static final Log LOG = LogFactory.getLog(CurDateTime.class.getName()); 36 | 37 | public Text evaluate() { 38 | Date date = new java.sql.Date(System.currentTimeMillis()); 39 | result.set(formatter.format(date)); 40 | return result; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/DayOfWeek.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | 8 | import org.apache.hadoop.hive.ql.exec.Description; 9 | import org.apache.hadoop.hive.ql.exec.UDF; 10 | import org.apache.hadoop.io.IntWritable; 11 | import org.apache.hadoop.io.Text; 12 | 13 | @Description(name = "dayofweek", 14 | value = "_FUNC_(date) - Returns the day of the week", 15 | extended = "Examples:\n" 16 | + " > SELECT _FUNC_('2011-08-29') FROM src LIMIT 1;\n" 17 | + " 1\n") 18 | public class DayOfWeek extends UDF { 19 | private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 20 | private final Calendar calendar = Calendar.getInstance(); 21 | 22 | private IntWritable result = new IntWritable(); 23 | 24 | public DayOfWeek() { 25 | calendar.setFirstDayOfWeek(Calendar.MONDAY); 26 | } 27 | 28 | /** 29 | * Get the day of week from a date string. 30 | * 31 | * @param dateString 32 | * the dateString in the format of "yyyy-MM-dd" 33 | * @return an int from 1 to 7. null if the dateString is not a valid date 34 | * string. 35 | */ 36 | public IntWritable evaluate(Text dateString) { 37 | if (dateString == null) { 38 | return null; 39 | } 40 | try { 41 | Date date = formatter.parse(dateString.toString()); 42 | calendar.setTime(date); 43 | result.set(calendar.get(Calendar.DAY_OF_WEEK)); 44 | return result; 45 | } catch (ParseException e) { 46 | return null; 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/GenericUDFLeast.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | * 18 | * Mostly a "Least" version of NexR's Greatest function. 19 | */ 20 | package com.livingsocial.hive.udf; 21 | 22 | import org.apache.hadoop.hive.ql.exec.Description; 23 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 24 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 25 | import org.apache.hadoop.hive.ql.metadata.HiveException; 26 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 27 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDFUtils; 28 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 29 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; 30 | 31 | /** 32 | * GenericUDF Class for SQL construct "least(value1, value2, value3, ....)". 33 | * Oracle's CREATEST returns the least of the list of one or more expressions. 34 | * 35 | */ 36 | @Description(name = "least", value = "_FUNC_(value1, value2, value3, ....) " + 37 | "- Returns the least value in the list.", 38 | extended = "Example:\n" + " > SELECT _FUNC_(2, 5, 12, 3) FROM src;\n 2") 39 | 40 | public class GenericUDFLeast extends GenericUDF { 41 | 42 | private ObjectInspector[] argumentOIs; 43 | private GenericUDFUtils.ReturnObjectInspectorResolver returnOIResolver; 44 | 45 | @Override 46 | public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { 47 | 48 | for (int i = 0; i < arguments.length; i++) { 49 | if (arguments[i].getCategory() != ObjectInspector.Category.PRIMITIVE) { 50 | throw new UDFArgumentTypeException(i, "Only primitive type arguments are accepted but " 51 | + arguments[i].getTypeName() + " is passed."); 52 | } 53 | } 54 | 55 | argumentOIs = arguments; 56 | returnOIResolver = new GenericUDFUtils.ReturnObjectInspectorResolver(true); 57 | for (int i = 0; i < arguments.length; i++) { 58 | if (!returnOIResolver.update(arguments[i])) { 59 | throw new UDFArgumentTypeException(i, "The value of return should have the same type: \"" 60 | + returnOIResolver.get().getTypeName() + 61 | "\" is expected but \"" + arguments[i].getTypeName() 62 | + "\" is found"); 63 | } 64 | } 65 | 66 | return returnOIResolver.get(); 67 | } 68 | 69 | @Override 70 | public Object evaluate(DeferredObject[] fields) throws HiveException { 71 | Object leastObject = null; 72 | ObjectInspector leastOI = null; 73 | 74 | for (int i = 0; i < fields.length; i++) { 75 | Object fieldObject = fields[i].get(); 76 | if (leastObject == null) { 77 | leastObject = fieldObject; 78 | leastOI = argumentOIs[i]; 79 | continue; 80 | } 81 | 82 | if (ObjectInspectorUtils.compare(leastObject, leastOI, fieldObject, argumentOIs[i]) >= 0) { 83 | leastObject = fieldObject; 84 | leastOI = argumentOIs[i]; 85 | } 86 | } 87 | 88 | return returnOIResolver.convertIfNecessary(leastObject, leastOI); 89 | } 90 | 91 | @Override 92 | public String getDisplayString(String[] children) { 93 | StringBuilder sb = new StringBuilder(); 94 | sb.append("least ("); 95 | for (int i = 0; i < children.length - 1; i++) { 96 | sb.append(children[i]).append(", "); 97 | } 98 | sb.append(children[children.length - 1]).append(")"); 99 | return sb.toString(); 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/GenericUDFLeastNonNull.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | * 18 | * Mostly a "Least" version of NexR's Greatest function, which does not consider 'null' to be least 19 | */ 20 | package com.livingsocial.hive.udf; 21 | 22 | import org.apache.hadoop.hive.ql.exec.Description; 23 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 24 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 25 | import org.apache.hadoop.hive.ql.metadata.HiveException; 26 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 27 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDFUtils; 28 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 29 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; 30 | 31 | /** 32 | * GenericUDF Class for SQL construct "least(value1, value2, value3, ....)". 33 | * Oracle's CREATEST returns the least of the list of one or more expressions. 34 | * 35 | */ 36 | @Description(name = "least_non_null", value = "_FUNC_(value1, value2, value3, ....) " + 37 | "- Returns the least value in the list. Nulls are not considered 'least'. Only returns null if all arguments are null", 38 | extended = "Example:\n" + " > SELECT _FUNC_(2, 5, 12, null) FROM src;\n 2") 39 | 40 | public class GenericUDFLeastNonNull extends GenericUDF { 41 | 42 | private ObjectInspector[] argumentOIs; 43 | private GenericUDFUtils.ReturnObjectInspectorResolver returnOIResolver; 44 | 45 | @Override 46 | public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { 47 | 48 | for (int i = 0; i < arguments.length; i++) { 49 | if (arguments[i].getCategory() != ObjectInspector.Category.PRIMITIVE) { 50 | throw new UDFArgumentTypeException(i, "Only primitive type arguments are accepted but " 51 | + arguments[i].getTypeName() + " is passed."); 52 | } 53 | } 54 | 55 | argumentOIs = arguments; 56 | returnOIResolver = new GenericUDFUtils.ReturnObjectInspectorResolver(true); 57 | for (int i = 0; i < arguments.length; i++) { 58 | if (!returnOIResolver.update(arguments[i])) { 59 | throw new UDFArgumentTypeException(i, "The value of return should have the same type: \"" 60 | + returnOIResolver.get().getTypeName() + 61 | "\" is expected but \"" + arguments[i].getTypeName() 62 | + "\" is found"); 63 | } 64 | } 65 | 66 | return returnOIResolver.get(); 67 | } 68 | 69 | @Override 70 | public Object evaluate(DeferredObject[] fields) throws HiveException { 71 | Object leastObject = null; 72 | ObjectInspector leastOI = null; 73 | 74 | for (int i = 0; i < fields.length; i++) { 75 | Object fieldObject = fields[i].get(); 76 | if (leastObject == null && fieldObject != null) { 77 | leastObject = fieldObject; 78 | leastOI = argumentOIs[i]; 79 | continue; 80 | } 81 | 82 | if (ObjectInspectorUtils.compare(leastObject, leastOI, fieldObject, argumentOIs[i]) >= 0 && fieldObject != null) { 83 | leastObject = fieldObject; 84 | leastOI = argumentOIs[i]; 85 | } 86 | } 87 | 88 | return returnOIResolver.convertIfNecessary(leastObject, leastOI); 89 | } 90 | 91 | @Override 92 | public String getDisplayString(String[] children) { 93 | StringBuilder sb = new StringBuilder(); 94 | sb.append("least ("); 95 | for (int i = 0; i < children.length - 1; i++) { 96 | sb.append(children[i]).append(", "); 97 | } 98 | sb.append(children[children.length - 1]).append(")"); 99 | return sb.toString(); 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/Hash.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import java.nio.charset.Charset; 4 | import java.security.MessageDigest; 5 | import java.security.NoSuchAlgorithmException; 6 | import java.util.Collection; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | import org.apache.commons.codec.binary.Hex; 11 | import org.apache.hadoop.hive.ql.exec.Description; 12 | import org.apache.hadoop.hive.ql.exec.UDF; 13 | import org.apache.hadoop.io.Text; 14 | 15 | @Description( 16 | name = "ls_hash", 17 | value = "_FUNC_(some_id, [some_salt, ['debug']]) - Generate a consistent hash based 'random' number between 0 and 1 mixing in the id and salt.", 18 | extended = "Generates a consistent 'random' number based on the passed in id and salt. \n" + 19 | " Normally this would be used to create a percentage based sample of a group with a query like:\n" + 20 | " select * from some_table_to_sample where _FUNC_(id, 'my_salt') < 0.10; -- extract a 10% random sample" 21 | ) 22 | public final class Hash extends UDF { 23 | 24 | private static final Text EMPTY = new Text(""); 25 | private static final int CHARS_TO_USE = 14; 26 | private static final double MAX_SIZE = Math.pow(2, CHARS_TO_USE*4); 27 | 28 | private Map mapOut = new HashMap(); 29 | private Charset charset = Charset.forName("UTF8"); 30 | 31 | public Double evaluate(final Text id) { 32 | return evaluate(id, EMPTY); 33 | } 34 | 35 | public Double evaluate(Text id, Text salt) { 36 | Double tmp = (Double) hashIt(id, salt).get("output"); 37 | return tmp; 38 | } 39 | 40 | 41 | public Text evaluate(Text id, Text salt, Text debug) { 42 | Map map = hashIt(id, salt); 43 | StringBuilder builder = new StringBuilder(); 44 | for(Map.Entry entry: (Collection>)map.entrySet()) { 45 | builder.append(entry.getKey() + "=" + entry.getValue() + ","); 46 | } 47 | return new Text(builder.toString()); 48 | } 49 | 50 | private Map hashIt(Text id, Text salt) { 51 | mapOut.clear(); 52 | if (id == null) { 53 | return mapOut; 54 | } 55 | 56 | if(salt == null) { 57 | salt = EMPTY; 58 | } 59 | 60 | String toHash = id.toString() + salt; 61 | 62 | try { 63 | MessageDigest md = MessageDigest.getInstance("SHA1"); 64 | md.update(toHash.getBytes(charset)); 65 | byte[] hash = md.digest(); 66 | String hexHash = Hex.encodeHexString(hash); 67 | String finalHash = hexHash.substring(0, CHARS_TO_USE); 68 | long hashNum = Long.parseLong(finalHash, 16); 69 | double value = hashNum / MAX_SIZE; 70 | 71 | // Slightly hacky way to expose the internals of this 72 | mapOut.put("hexHash", hexHash); 73 | mapOut.put("finalHash", finalHash); 74 | mapOut.put("hashNum", hashNum); 75 | mapOut.put("toHash", toHash); 76 | mapOut.put("output", value); 77 | 78 | return mapOut; 79 | } catch (NoSuchAlgorithmException nsae) { 80 | throw new IllegalArgumentException("SHA1 is not setup"); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/ILike.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import org.apache.hadoop.hive.ql.udf.UDFLike; 4 | 5 | import org.apache.hadoop.hive.ql.exec.UDF; 6 | import org.apache.hadoop.hive.ql.exec.Description; 7 | import org.apache.hadoop.io.BooleanWritable; 8 | import org.apache.hadoop.io.Text; 9 | 10 | @Description( 11 | name = "ilike", 12 | value = "_FUNC_(str, pattern) - Checks if str matches pattern", 13 | extended = "Example:\n" + 14 | " > SELECT a.* FROM srcpart a WHERE a.hr _FUNC_ '%2' LIMIT 1;\n" + 15 | " 27 val_27 2008-04-08 12" 16 | ) 17 | public class ILike extends UDFLike { 18 | public BooleanWritable evaluate(Text s, Text likePattern) { 19 | if(s != null && likePattern != null) { 20 | s.set(s.toString().toLowerCase()); 21 | likePattern.set(likePattern.toString().toLowerCase()); 22 | } 23 | return super.evaluate(s, likePattern); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/InArray.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import com.livingsocial.hive.utils.KISSInspector; 4 | 5 | import org.apache.hadoop.hive.ql.exec.Description; 6 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 7 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 8 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 9 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 10 | import org.apache.hadoop.hive.ql.metadata.HiveException; 11 | import org.apache.hadoop.hive.serde.Constants; 12 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 13 | import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; 14 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; 15 | import org.apache.hadoop.io.BooleanWritable; 16 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 17 | 18 | import org.apache.commons.logging.Log; 19 | import org.apache.commons.logging.LogFactory; 20 | 21 | @Description(name = "in_array", value = "_FUNC_(x, a) - Returns true if x is in the array a") 22 | public class InArray extends GenericUDF { 23 | private ListObjectInspector array_inspector; 24 | private KISSInspector element_inspector; 25 | 26 | static final Log LOG = LogFactory.getLog(InArray.class.getName()); 27 | 28 | @Override 29 | public ObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException { 30 | if(args.length != 2 || !KISSInspector.isPrimitive(args[0]) || !KISSInspector.isList(args[1])) 31 | throw new UDFArgumentException("in_array() takes two arguments: a primitive and an array"); 32 | element_inspector = new KISSInspector(args[0]); 33 | array_inspector = (ListObjectInspector) args[1]; 34 | return PrimitiveObjectInspectorFactory.writableBooleanObjectInspector; 35 | } 36 | 37 | @Override 38 | public BooleanWritable evaluate(DeferredObject[] arguments) throws HiveException { 39 | BooleanWritable found = new BooleanWritable(false); 40 | // if either argument is null, or if the list doesn't contain the same primitives 41 | if(arguments[0].get() == null || arguments[1].get() == null || !element_inspector.sameAsTypeIn(array_inspector)) 42 | return found; 43 | Object element = arguments[0].get(); 44 | Object elist = arguments[1].get(); 45 | for(int i=0; i SELECT index_of('-', phone_number) FROM contact_info;\n" + 13 | " 3" 14 | ) 15 | public class IndexOf extends UDF { 16 | private final IntWritable result = new IntWritable(); 17 | 18 | public IntWritable evaluate(Text needle, Text haystack, IntWritable fromIndex) { 19 | int index = 0; 20 | if(needle != null && haystack != null) 21 | index = haystack.toString().indexOf(needle.toString(), fromIndex.get()); 22 | result.set(index); 23 | return result; 24 | } 25 | 26 | public IntWritable evaluate(Text needle, Text haystack) { 27 | return evaluate(needle, haystack, new IntWritable(0)); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/IndexOfMaxElem.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import com.livingsocial.hive.utils.KISSInspector; 4 | 5 | import org.apache.hadoop.hive.ql.exec.Description; 6 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 7 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 8 | import org.apache.hadoop.hive.ql.metadata.HiveException; 9 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 10 | import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; 11 | import org.apache.hadoop.io.IntWritable; 12 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 13 | 14 | import org.apache.commons.logging.Log; 15 | import org.apache.commons.logging.LogFactory; 16 | 17 | @Description(name = "index_of_max_elem", value = "_FUNC_(a) - Returns index of maximum element of the array a") 18 | public class IndexOfMaxElem extends GenericUDF { 19 | private ListObjectInspector array_inspector; 20 | private KISSInspector elem_inspector; 21 | static final Log LOG = LogFactory.getLog(InArray.class.getName()); 22 | 23 | @Override 24 | public ObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException { 25 | if(args.length != 1 || !KISSInspector.isList(args[0])) 26 | throw new UDFArgumentException("index_of_max_elem() takes one argument: an array"); 27 | array_inspector = (ListObjectInspector) args[0]; 28 | elem_inspector = new KISSInspector(array_inspector.getListElementObjectInspector()); 29 | return PrimitiveObjectInspectorFactory.writableIntObjectInspector; 30 | } 31 | 32 | @Override 33 | public IntWritable evaluate(DeferredObject[] arguments) throws HiveException { 34 | Object elist = arguments[0].get(); 35 | 36 | //Possibly check for Comparable here 37 | if(elist == null || array_inspector.getListLength(elist) == 0) 38 | return new IntWritable(-1); 39 | 40 | IntWritable maxIndex = new IntWritable(0); 41 | Comparable maxVal = (Comparable) elem_inspector.get(array_inspector.getListElement(elist,0)); 42 | 43 | for(int i=0; i 0) { 47 | maxVal = listElem; 48 | maxIndex = new IntWritable(i); 49 | } 50 | } 51 | return maxIndex; 52 | } 53 | 54 | @Override 55 | public String getDisplayString(String[] children) { 56 | assert (children.length == 1); 57 | return "index_of_max_elem(" + children[0] + ")"; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/IsoYearWeek.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.GregorianCalendar; 7 | import java.util.Date; 8 | 9 | import org.apache.hadoop.hive.ql.exec.Description; 10 | import org.apache.hadoop.hive.ql.exec.UDF; 11 | // import org.apache.hadoop.hive.serde2.io.TimestampWritable; 12 | import org.apache.hadoop.io.IntWritable; 13 | import org.apache.hadoop.io.Text; 14 | 15 | /** 16 | * IsoYearWeek. 17 | * 18 | */ 19 | @Description(name = "isoyearweek", 20 | value = "_FUNC_(date) - Returns the year of ISO week number of the given date. A week " 21 | + "is considered to start on a Monday and week 1 is the first week with >3 days." 22 | + "The first 1-3 days of a year prior to a week ", 23 | extended = "Examples:\n" 24 | + " > SELECT _FUNC_('2008-02-20') FROM src LIMIT 1;\n" 25 | + " 8\n" 26 | + " > SELECT _FUNC_('1980-12-31 12:59:59') FROM src LIMIT 1;\n" + " 1") 27 | public class IsoYearWeek extends UDF { 28 | private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 29 | private final Calendar cal = Calendar.getInstance(); 30 | private final Calendar calNearThur = Calendar.getInstance(); 31 | 32 | private IntWritable result = new IntWritable(); 33 | 34 | public IsoYearWeek() { 35 | cal.setFirstDayOfWeek(Calendar.MONDAY); 36 | cal.setMinimalDaysInFirstWeek(4); 37 | calNearThur.setFirstDayOfWeek(Calendar.MONDAY); 38 | calNearThur.setMinimalDaysInFirstWeek(4); 39 | } 40 | 41 | /** 42 | * Get the week of the year from a date string. 43 | * 44 | * @param dateString 45 | * the dateString in the format of "yyyy-MM-dd HH:mm:ss" or 46 | * "yyyy-MM-dd". 47 | * @return an int from 1 to 53. null if the dateString is not a valid date 48 | * string. 49 | */ 50 | public IntWritable evaluate(Text dateString) { 51 | if (dateString == null) { 52 | return null; 53 | } 54 | try { 55 | Date date = formatter.parse(dateString.toString()); 56 | int checkYear; 57 | 58 | cal.setTime(date); 59 | calNearThur.setTime(date); 60 | 61 | boolean isSunday = cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY; 62 | if (isSunday) 63 | calNearThur.add(Calendar.DAY_OF_MONTH,5-(cal.get(Calendar.DAY_OF_WEEK)+7)); 64 | else 65 | calNearThur.add(Calendar.DAY_OF_MONTH,5-(cal.get(Calendar.DAY_OF_WEEK))); 66 | result.set(calNearThur.get(Calendar.YEAR)); 67 | return (result); 68 | } catch (ParseException e) { 69 | return null; 70 | } 71 | } 72 | 73 | // public IntWritable evaluate(TimestampWritable t) { 74 | // if (t == null) { 75 | // return null; 76 | // } 77 | // 78 | // cal.setTime(t.getTimestamp()); 79 | // calNearThur.setTime(t.getTimestamp()); 80 | // 81 | // boolean isSunday = cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY; 82 | // if (isSunday) 83 | // calNearThur.add(Calendar.DAY_OF_MONTH,5-(cal.get(Calendar.DAY_OF_WEEK)+7)); 84 | // else 85 | // calNearThur.add(Calendar.DAY_OF_MONTH,5-(cal.get(Calendar.DAY_OF_WEEK))); 86 | // result.set(calNearThur.get(Calendar.YEAR)); 87 | // return (result); 88 | // } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/MaxDate.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import com.livingsocial.hive.Utils; 4 | import com.livingsocial.hive.utils.KISSInspector; 5 | 6 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 7 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 8 | import org.apache.hadoop.hive.ql.exec.Description; 9 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 10 | import org.apache.hadoop.hive.ql.metadata.HiveException; 11 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; 12 | 13 | @Description( 14 | name = "max_date", 15 | value = "_FUNC_(a1, a2, ...) - Returns the largest non-null date argument", 16 | extended = "Example:\n" + 17 | " > SELECT _FUNC_('2011-01-01 10:11:00', NULL, '2011-02-01', NULL) FROM src LIMIT 1;\n" + 18 | " '2011-02-01" 19 | ) 20 | public final class MaxDate extends GenericUDF { 21 | KISSInspector[] inspectors; 22 | 23 | @Override 24 | public ObjectInspector initialize(ObjectInspector[] arguments) 25 | throws UDFArgumentTypeException { 26 | 27 | inspectors = new KISSInspector[arguments.length]; 28 | 29 | for(int i=0; i best_time) { 52 | best = ai; 53 | best_time = ts; 54 | } 55 | } 56 | } 57 | return best; 58 | } 59 | 60 | @Override 61 | public String getDisplayString(String[] children) { 62 | StringBuilder sb = new StringBuilder(); 63 | sb.append("max_date("); 64 | if (children.length > 0) { 65 | sb.append(children[0]); 66 | for(int i=1; i SELECT _FUNC_('2011-01-01 10:11:00', NULL, '2011-02-01', NULL) FROM src LIMIT 1;\n" + 18 | " '2011-01-01 10:11:00" 19 | ) 20 | public final class MinDate extends GenericUDF { 21 | KISSInspector[] inspectors; 22 | 23 | @Override 24 | public ObjectInspector initialize(ObjectInspector[] arguments) 25 | throws UDFArgumentTypeException { 26 | 27 | inspectors = new KISSInspector[arguments.length]; 28 | 29 | for(int i=0; i 0) { 65 | sb.append(children[0]); 66 | for(int i=1; i Utils.stringToTimestamp(o.toString())) { 38 | mMin.set(o); 39 | } 40 | } 41 | return true; 42 | } 43 | 44 | public Text terminatePartial() { 45 | return mEmpty ? null : mMin; 46 | } 47 | 48 | public boolean merge(Text o) { 49 | return iterate(o); 50 | } 51 | 52 | public Text terminate() { 53 | return mEmpty ? null : mMin; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/ScriptedUDAF.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.apache.hadoop.hive.ql.exec.Description; 7 | import org.apache.hadoop.hive.ql.metadata.HiveException; 8 | import org.apache.hadoop.hive.ql.parse.SemanticException; 9 | import org.apache.hadoop.hive.ql.udf.UDFType; 10 | import org.apache.hadoop.hive.ql.udf.generic.AbstractGenericUDAFResolver; 11 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator; 12 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AggregationBuffer; 13 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFParameterInfo; 14 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDFUtils; 15 | import org.apache.hadoop.hive.serde2.lazybinary.objectinspector.LazyBinaryObjectInspectorFactory; 16 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 17 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters; 18 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 19 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; 20 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | import com.livingsocial.hive.utils.ScriptingHelper; 25 | import com.livingsocial.hive.utils.ScriptingHelper.InitializationContainer; 26 | 27 | /** 28 | * This does not work, but is close. See the FIXME comment in the init function 29 | */ 30 | @UDFType(deterministic = false, stateful = true) 31 | @Description(name = "scriptedUDAF", value = "_FUNC_(script_to_run, language, return_type, script_arg1, script_arg_2, ....) " + 32 | "- Runs custom UDAF code from the various functions in the script. The required functions are: iterate(agg_data, arg1, arg2, ...), partial(agg_data), convert_to_string(agg_data), convert_from_string(agg_data), merge(agg_data1, agg_data2), and terminate(agg_data).", 33 | extended = "Function descriptions in the script:\n" + 34 | " iterate receives an agg_data object and all the extra arguments in the UDAF call. On first call agg_data will be null. The script needs to build an appropriate object, accumulate data from the arguments, and return the agg object. That agg object will be passed to later calls. \n" + 35 | " partial receives the agg_data object from the iterate call and returns a partial aggregation (this can simply return agg_data)\n" + 36 | " convert_to_string receives the partial_results object from the partial call and returns a string\n" + 37 | " convert_from_string receives the string from convert_to_string and rebuilds the partial_results object\n" + 38 | " merge receives 2 partial_results objects and returns a merged version with data from both\n" + 39 | " terminate receives a merged partial_results object and returns the final return object type. The object returned needs to adhere to the return_type specified in the _FUNC_ call\n" + 40 | "\nLanguage is the javax.script engine name. Additional languages can be added by adding the jar implementing the scripting engine ('add jar groovy-all.jar;' or similar)\n" + 41 | "Return_type is a hive style data definition ('string', 'bigint', 'array>', ...) \n\n" + 42 | "Example:\n" + 43 | " > -- compute the differences between a series of time events in a group \n" + 44 | "select person_id, _FUNC_('\n" + 45 | " require \"json\\n" + 46 | " \n" + 47 | " def iterate(result, time)\n" + 48 | " result ||= []\n" + 49 | " result << time.to_i\n" + 50 | " result\n" + 51 | " end\n" + 52 | " \n" + 53 | " def convert_to_string(result)\n" + 54 | " result.to_json\n" + 55 | " end\n" + 56 | " \n" + 57 | " def convert_from_string(json)\n" + 58 | " JSON.parse(json)\n" + 59 | " end\n" + 60 | " \n" + 61 | " def merge(result1, result2)\n" + 62 | " result1 ||= []\n" + 63 | " result1.concat(result2)\n" + 64 | " result1\n" + 65 | " end\n" + 66 | " \n" + 67 | " # Note: since this does no partial aggregation it is a bad example of a UDAF\n" + 68 | " def partial(times)\n" + 69 | " times\n" + 70 | " end\n" + 71 | " \n" + 72 | " def terminate(times)\n" + 73 | " times.sort!\n" + 74 | " last=0\n" + 75 | " output = []\n" + 76 | " times.each { |time|\n" + 77 | " output << t - last\n" + 78 | " last = t\n" + 79 | " }\n" + 80 | " output\n" + 81 | " end\n" + 82 | " \n" + 83 | " ', 'ruby', 'array', 'array', purchase_time ) as time_diffs\n" + 84 | " from purchases\n" + 85 | " group by person_id\n" + 86 | " \n" + 87 | "\nAlternate syntax:\n> SELECT group_id, _FUNC_('/my_scripts/reusable.rb', 'ruby', val1, val2) FROM src_table GROUP BY group_id; \n" + 88 | " this will load the script from the location in HDFS. ") 89 | public class ScriptedUDAF extends AbstractGenericUDAFResolver { 90 | private static final Logger LOG = LoggerFactory.getLogger(ScriptedUDAF.class); 91 | 92 | @Override 93 | public GenericUDAFEvaluator getEvaluator(GenericUDAFParameterInfo info) 94 | throws SemanticException { 95 | return new ScriptedUDAFEvaluator(); 96 | } 97 | 98 | private static class MyAggBuffer implements AggregationBuffer { 99 | public Object data; 100 | } 101 | 102 | public static class ScriptedUDAFEvaluator extends GenericUDAFEvaluator { 103 | private InitializationContainer initData; 104 | 105 | GenericUDFUtils.ReturnObjectInspectorResolver outputResolver; 106 | 107 | // Store all intermediate data in a string/string map 108 | ObjectInspector intermediateInternal = ObjectInspectorFactory.getStandardMapObjectInspector( 109 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); 110 | ObjectInspector intermediateExternal = LazyBinaryObjectInspectorFactory.getLazyBinaryMapObjectInspector( 111 | PrimitiveObjectInspectorFactory.writableStringObjectInspector, PrimitiveObjectInspectorFactory.writableStringObjectInspector); 112 | 113 | private ObjectInspectorConverters.Converter intermediateConverterInput = ObjectInspectorConverters.getConverter(intermediateExternal, intermediateInternal); 114 | 115 | @Override 116 | public ObjectInspector init(Mode m, ObjectInspector[] parameters) 117 | throws HiveException { 118 | super.init(m, parameters); 119 | LOG.info("Mode: " + m.name(), new Exception()); 120 | 121 | 122 | 123 | if (m == Mode.PARTIAL1 || m == Mode.COMPLETE) { 124 | // This is getting the full arg list 125 | if (initData == null) initData = ScriptingHelper.initialize(parameters); 126 | 127 | } else { 128 | // This is getting only intermediate data so there's nothing to do here 129 | if (initData == null) { 130 | initData = new ScriptingHelper.InitializationContainer(); 131 | } 132 | } 133 | 134 | // Fall back error check 135 | if (initData == null) { 136 | throw new HiveException("Something went wrong while trying to initialize things"); 137 | } 138 | 139 | if (m == Mode.PARTIAL1 || m == Mode.PARTIAL2) { 140 | outputResolver = ScriptingHelper.buildReturnResolver(intermediateExternal); 141 | } else if (m == Mode.COMPLETE) { 142 | outputResolver = ScriptingHelper.buildReturnResolver(initData.outputOi); 143 | } else { 144 | // FIXME: 145 | // This does not work because there is no way to know what the return type should be 146 | // If there is a way to pass the constant OI type from the original input to the 147 | // mode=FINAL call then this can work. 148 | throw new IllegalStateException("This does not work, see the comment in the code"); 149 | } 150 | return outputResolver.get(); 151 | } 152 | 153 | @Override 154 | public AggregationBuffer getNewAggregationBuffer() throws HiveException { 155 | return new MyAggBuffer(); 156 | } 157 | 158 | @Override 159 | public void reset(AggregationBuffer agg) throws HiveException { 160 | ((MyAggBuffer)agg).data = null; 161 | } 162 | 163 | @Override 164 | public void iterate(AggregationBuffer agg, Object[] arguments) 165 | throws HiveException { 166 | LOG.info("Start iterate"); 167 | MyAggBuffer data = (MyAggBuffer) agg; 168 | 169 | Object[] args = new Object[1+arguments.length - initData.argOffset]; 170 | for (int i = 0; i < args.length-1; i++) { 171 | args[i+1] = ObjectInspectorUtils.copyToStandardJavaObject(arguments[i+initData.argOffset], initData.argumentOIs[i]); 172 | } 173 | args[0] = data.data; 174 | 175 | try { 176 | data.data = initData.engine.invokeFunction("iterate", args); 177 | } catch (Exception e) { 178 | throw new HiveException("Error invoking the iterate function", e); 179 | } 180 | LOG.info("End iterate"); 181 | } 182 | 183 | @Override 184 | public Object terminatePartial(AggregationBuffer agg) throws HiveException { 185 | LOG.info("Start terminatePartial"); 186 | MyAggBuffer myAgg = (MyAggBuffer) agg; 187 | 188 | String rtn = null; 189 | try { 190 | rtn = initData.engine.invokeFunction("convert_to_string", (Object)myAgg.data).toString(); 191 | } catch (Exception e) { 192 | throw new HiveException("Error invoking the partial function", e); 193 | } 194 | 195 | Map out = new HashMap(); 196 | out.put("data", rtn); 197 | out.put("script", initData.script); 198 | out.put("language", initData.language); 199 | out.put("returntype", initData.returnType); 200 | 201 | try { 202 | Object tmp = outputResolver.convertIfNecessary(out, intermediateInternal); 203 | LOG.info("End terminatePartial"); 204 | return tmp; 205 | } catch (Exception e) { 206 | e.printStackTrace(System.err); 207 | throw new HiveException("bad stuff", e); 208 | } 209 | } 210 | 211 | @Override 212 | public void merge(AggregationBuffer agg, Object partial) 213 | throws HiveException { 214 | 215 | LOG.info("Merging a " + partial.getClass().getName()); 216 | MyAggBuffer myAgg = (MyAggBuffer) agg; 217 | 218 | @SuppressWarnings("unchecked") 219 | Map converted = (Map) intermediateConverterInput.convert(partial); 220 | 221 | try { 222 | String script = (String) converted.get("script"); 223 | String language = (String) converted.get("language"); 224 | if (initData.engine == null) { 225 | initData.engine = ScriptingHelper.initializeEngine(language, script); 226 | } 227 | String data = (String) converted.get("data"); 228 | Object convertedData = initData.engine.invokeFunction("convert_from_string", data); 229 | 230 | try { 231 | myAgg.data = initData.engine.invokeFunction("merge", myAgg.data, convertedData); 232 | } catch (Exception e) { 233 | throw new HiveException("Error invoking the merge function", e); 234 | } 235 | } catch (Exception e) { 236 | e.printStackTrace(); 237 | throw new HiveException("bad stuff"); 238 | } 239 | LOG.info("End merge"); 240 | } 241 | 242 | @Override 243 | public Object terminate(AggregationBuffer agg) throws HiveException { 244 | LOG.info("Start terminate"); 245 | MyAggBuffer myAgg = (MyAggBuffer) agg; 246 | 247 | try { 248 | Object out = initData.engine.invokeFunction("terminate", myAgg.data); 249 | 250 | LOG.info("End terminate"); 251 | return outputResolver.convertIfNecessary(out, outputResolver.get()); 252 | } catch (Exception e) { 253 | throw new HiveException("Error invoking the terminate function", e); 254 | } 255 | 256 | } 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/ScriptedUDF.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import javax.script.Invocable; 4 | 5 | import org.apache.hadoop.hive.ql.exec.Description; 6 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 7 | import org.apache.hadoop.hive.ql.metadata.HiveException; 8 | import org.apache.hadoop.hive.ql.parse.SemanticException; 9 | import org.apache.hadoop.hive.ql.udf.UDFType; 10 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 11 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 12 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; 13 | 14 | import com.livingsocial.hive.utils.ScriptingHelper; 15 | 16 | @UDFType(deterministic = false, stateful = true) 17 | @Description(name = "scriptedUDF", value = "_FUNC_(script_to_run, language, return_type, script_arg1, script_arg_2, ....) " + 18 | "- Returns the specified return_type (hive style types) from the evaluate function of the script.", 19 | extended = "Function descriptions in the script:\n" + 20 | " evaluate receives all the extra script_arguments passed in the _FUNC_ call and returns an object adhering to the defined return_type \n" + 21 | "\nLanguage is the javax.script engine name. Additional languages can be added by adding the jar implementing the scripting engine ('add jar groovy-all.jar;' or similar)\n" + 22 | "Return_type is a hive style data definition ('string', 'bigint', 'array>', ...) \n\n" + 23 | "Example:\n > -- Gather complex data combining groups and individual rows without joins \n" + 24 | " select person_id, purchase_data['time'], purchase_data['diff'], \n" + 25 | " purchase_data['product'], purchase_data['purchase_count'] as pc,\n" + 26 | " purchase_data['blah']\n" + 27 | " from (\n" + 28 | " select person_id, scriptedUDF('\n" + 29 | " require \"json\"\n" + 30 | " def evaluate(data)\n" + 31 | " # This gathers all the data about purchases by person in one place so complex infromation can be gathered while avoiding complex joins \n" + 32 | " # Note: In order for this to work all the data passed into _FUNC_ for a row needs to fit into memory \n" + 33 | " tmp = [] # convert things over to a ruby array\n" + 34 | " tmp.concat(data)\n" + 35 | " tmp.sort_by! { |a| a.get(\"time\") } # for the time differences\n" + 36 | " last=0\n" + 37 | " tmp.map{ |row| \n" + 38 | " # Compute the time difference between purchases and add the total purchase count per person\n" + 39 | " t = row[\"time\"] \n" + 40 | " \n" + 41 | " # The parts that would be much more difficult to generate with SQL \n" + 42 | " row[\"diff\"] = t - last\n" + 43 | " row[\"purchase_count\"] = tmp.length\n" + 44 | " row[\"first_purchase\"] = tmp[0][\"time\"]\n" + 45 | " row[\"last_purchase\"] = tmp[-1][\"time\"]\n" + 46 | " \n" + 47 | " # This shows that built-in libraries are available\n" + 48 | " row[\"blah\"] = JSON.generate({\"id\" => row[\"id\"]})\n" + 49 | " last = t\n" + 50 | " row\n" + 51 | " }\n" + 52 | " end', 'ruby', 'array>', \n" + 53 | " -- gather all the data about purchases by people so it can all be passed into the evaluate function \n" + 54 | " bh_collect(map( -- Note, bh_collect is from Klouts Brickhouse and allows collecting any type, see https://github.com/klout/brickhouse/ \n" + 55 | " 'time', unix_liberal_timestamp(purchase_time), \n" + 56 | " 'product', product_id)) ) as all_data \n" + 57 | " from purchases\n" + 58 | " group by person_id\n" + 59 | " ) foo \n" + 60 | " -- explode the data back out so it is available in flattened form \n" + 61 | " lateral view explode(all_data) bar as purchase_data \n" + 62 | "\n" + 63 | "\nAlternate syntax:\n> SELECT _FUNC_('/my_scripts/reusable.rb', 'ruby', 'map', val1, val2) FROM src_table; \n" + 64 | " this will load the script from the location in HDFS and will invoke the evaluate function. This function needs to return a map of strings keys and int values. ") 65 | public class ScriptedUDF extends GenericUDF { 66 | 67 | private ScriptingHelper.InitializationContainer initData; 68 | 69 | private Invocable engine; 70 | 71 | @Override 72 | public ObjectInspector initialize(ObjectInspector[] arguments) 73 | throws UDFArgumentException { 74 | 75 | try { 76 | initData = ScriptingHelper.initialize(arguments); 77 | } catch (SemanticException e) { 78 | throw new UDFArgumentException(e); 79 | } 80 | 81 | return initData.returnOIResolver.get(); 82 | } 83 | 84 | @Override 85 | public Object evaluate(DeferredObject[] arguments) throws HiveException { 86 | if (engine == null) engine = ScriptingHelper.initializeEngine(initData.language, initData.script); 87 | 88 | Object[] args = new Object[arguments.length - initData.argOffset]; 89 | for (int i = 0; i < args.length; i++) { 90 | args[i] = ObjectInspectorUtils.copyToStandardJavaObject(arguments[i+initData.argOffset].get(), initData.argumentOIs[i]); 91 | } 92 | 93 | Object out; 94 | try { 95 | out = engine.invokeFunction("evaluate", args); 96 | } catch (Exception e) { 97 | throw new HiveException("Error invoking the evaluate function", e); 98 | } 99 | return initData.returnOIResolver.convertIfNecessary(out, initData.outputOi); 100 | } 101 | 102 | @Override 103 | public String getDisplayString(String[] children) { 104 | StringBuilder sb = new StringBuilder(); 105 | sb.append("scriptedUDF("); 106 | for (int i = 0; i < children.length; i++) { 107 | if ( i != 0 ) sb.append(", "); 108 | sb.append(children); 109 | } 110 | sb.append(")"); 111 | return sb.toString(); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/Sha1.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import org.apache.hadoop.hive.ql.exec.UDF; 4 | import org.apache.hadoop.io.Text; 5 | 6 | import java.security.*; 7 | 8 | /** 9 | * Fork of datamine md5 changing it to sha1 10 | * originally found at https://gist.github.com/1050002 11 | */ 12 | public final class Sha1 extends UDF { 13 | 14 | public Text evaluate(final Text s) { 15 | if (s == null) { 16 | return null; 17 | } 18 | try { 19 | MessageDigest md = MessageDigest.getInstance("SHA1"); 20 | md.update(s.toString().getBytes()); 21 | byte[] hash = md.digest(); 22 | StringBuilder builder = new StringBuilder(); 23 | for (byte b : hash) { 24 | builder.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); 25 | } 26 | return new Text(builder.toString()); 27 | } catch (NoSuchAlgorithmException nsae) { 28 | throw new IllegalArgumentException("SHA1 is not setup"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/StripHTML.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import org.apache.hadoop.hive.ql.exec.Description; 4 | import org.apache.hadoop.hive.ql.exec.UDF; 5 | import org.apache.hadoop.io.Text; 6 | import org.jsoup.Jsoup; 7 | 8 | 9 | @Description( 10 | name = "striphtml", 11 | value = "_FUNC_(str) - Returns str with all HTML tags removed." 12 | ) 13 | public class StripHTML extends UDF { 14 | public Text evaluate(Text html) { 15 | String stripped = Jsoup.parse(html.toString()).text(); 16 | return new Text(stripped); 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/Tokenize.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import java.io.IOException; 4 | import java.io.Reader; 5 | import java.io.StringReader; 6 | import java.util.ArrayList; 7 | 8 | import org.apache.hadoop.hive.ql.exec.Description; 9 | import org.apache.hadoop.hive.ql.exec.UDF; 10 | import org.apache.hadoop.hive.ql.metadata.HiveException; 11 | import org.apache.hadoop.io.Text; 12 | import org.apache.lucene.analysis.Analyzer; 13 | import org.apache.lucene.analysis.TokenStream; 14 | import org.apache.lucene.analysis.Tokenizer; 15 | import org.apache.lucene.analysis.charfilter.HTMLStripCharFilter; 16 | import org.apache.lucene.analysis.core.LowerCaseFilter; 17 | import org.apache.lucene.analysis.core.StopFilter; 18 | import org.apache.lucene.analysis.en.EnglishPossessiveFilter; 19 | import org.apache.lucene.analysis.en.KStemFilter; 20 | import org.apache.lucene.analysis.en.PorterStemFilter; 21 | import org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilter; 22 | import org.apache.lucene.analysis.standard.StandardAnalyzer; 23 | import org.apache.lucene.analysis.standard.StandardFilter; 24 | import org.apache.lucene.analysis.standard.StandardTokenizer; 25 | import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; 26 | import org.apache.lucene.analysis.util.CharArraySet; 27 | import org.apache.lucene.util.Version; 28 | 29 | /** 30 | * Tokenize: splits a natural language chunk of text into an array of stemmed 31 | * lowercase words. English stop words are excluded from the output. 32 | * 33 | */ 34 | @Description(name = "tokenize", value = "_FUNC_(str) - Splits str" 35 | + " into an arrays of stemmed words") 36 | public class Tokenize extends UDF { 37 | 38 | public ArrayList evaluate(Text text) throws HiveException { 39 | ArrayList result = new ArrayList(); 40 | Analyzer analyzer = new MyAnalyzer(); 41 | try { 42 | TokenStream stream = analyzer.tokenStream("", 43 | new StringReader(text.toString())); 44 | stream.reset(); 45 | while (stream.incrementToken()) { 46 | CharTermAttribute term = stream 47 | .getAttribute(CharTermAttribute.class); 48 | result.add(new Text(term.toString())); 49 | } 50 | } catch (IOException e) { 51 | throw new HiveException(e); 52 | } finally { 53 | analyzer.close(); 54 | } 55 | return result; 56 | } 57 | 58 | private static class DefaultSetHolder { 59 | static final CharArraySet DEFAULT_STOP_SET = StandardAnalyzer.STOP_WORDS_SET; 60 | } 61 | 62 | /** 63 | * Customer Analyzer based on {@link StandardAnalyzer} except using 64 | * {@link KStemFilter} instead of the more aggressive 65 | * {@link PorterStemFilter}. I also added in the {@link ASCIIFoldingFilter} 66 | * in order to remove accents from words, and {@link HTMLStripCharFilter} 67 | * to strip out HTML elements. 68 | */ 69 | private static class MyAnalyzer extends Analyzer { 70 | 71 | @Override 72 | protected TokenStreamComponents createComponents(String fieldName, 73 | Reader reader) { 74 | Version matchVersion = Version.LUCENE_45; 75 | final Tokenizer source = new StandardTokenizer(matchVersion, reader); 76 | TokenStream result = new StandardFilter(matchVersion, source); 77 | result = new EnglishPossessiveFilter(matchVersion, result); 78 | result = new LowerCaseFilter(matchVersion, result); 79 | result = new StopFilter(matchVersion, result, 80 | DefaultSetHolder.DEFAULT_STOP_SET); 81 | result = new ASCIIFoldingFilter(result); 82 | result = new KStemFilter(result); 83 | return new TokenStreamComponents(source, result); 84 | } 85 | 86 | @Override 87 | protected Reader initReader(String fieldName, Reader reader) { 88 | return new HTMLStripCharFilter(reader); 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/UDFQuarter.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | 8 | import org.apache.hadoop.hive.ql.exec.Description; 9 | import org.apache.hadoop.hive.ql.exec.UDF; 10 | import org.apache.hadoop.hive.serde2.io.TimestampWritable; 11 | import org.apache.hadoop.io.IntWritable; 12 | import org.apache.hadoop.io.Text; 13 | 14 | /** 15 | * 16 | * UDFQuarter 17 | * 18 | * From https://issues.apache.org/jira/browse/HIVE-3404 until it's in the main hive build 19 | * 20 | */ 21 | @Description(name = "quarter", value = "_FUNC_(date or timestamp) -" + 22 | " Returns the quarter of the year corresponding to date or timestamp") 23 | public class UDFQuarter extends UDF { 24 | private final SimpleDateFormat formatter = new SimpleDateFormat( 25 | "yyyy-MM-dd"); 26 | private final Calendar calendar = Calendar.getInstance(); 27 | private IntWritable result = new IntWritable(); 28 | 29 | public UDFQuarter() { 30 | 31 | } 32 | /** 33 | * Get the quarter of the year from a date string. 34 | * 35 | * @param dateString 36 | * the dateString in the format of "yyyy-MM-dd HH:mm:ss" or 37 | * "yyyy-MM-dd". 38 | * @return an IntWritable from 1 to 4. null if the dateString is not a valid date 39 | * string. 40 | */ 41 | public IntWritable evaluate(Text dateString) { 42 | if (dateString == null) { 43 | return null; 44 | } 45 | try { 46 | Date date = formatter.parse(dateString.toString()); 47 | calendar.setTime(date); 48 | int month = calendar.get(Calendar.MONTH) + 1; 49 | result = getQuarter(month); 50 | 51 | } catch (ParseException e) { 52 | return null; 53 | } 54 | return result; 55 | 56 | } 57 | /** 58 | * Get the quarter of the year from a date Timestamp. 59 | * 60 | * @param dateTimeStamp 61 | * the dateTimeStamp in the format of "yyyy-MM-dd HH:mm:ss" or 62 | * "yyyy-MM-dd". 63 | * @return an IntWritable from 1 to 4. null if the dateTimeStamp is not a valid date 64 | * TimeStamp. 65 | */ 66 | public IntWritable evaluate(TimestampWritable dateTimeStamp) { 67 | if (dateTimeStamp == null) { 68 | return null; 69 | } 70 | calendar.setTime(dateTimeStamp.getTimestamp()); 71 | int month = calendar.get(Calendar.MONTH) + 1; 72 | result = getQuarter(month); 73 | return result; 74 | } 75 | 76 | /** 77 | * getQuarter method calculates in which quarter the date falls 78 | * 79 | * @param monthOfYear 80 | * @return quarter 81 | */ 82 | public IntWritable getQuarter(int monthOfYear) { 83 | IntWritable quarter = new IntWritable(); 84 | 85 | if (monthOfYear >= 1 && monthOfYear <= 3) { 86 | quarter.set(1); 87 | } else if (monthOfYear >= 4 && monthOfYear <= 6) { 88 | quarter.set(2); 89 | } else if (monthOfYear >= 7 && monthOfYear <= 9) { 90 | quarter.set(3); 91 | } else if (monthOfYear >= 10 && monthOfYear <= 12) { 92 | quarter.set(4); 93 | } 94 | return quarter; 95 | 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/URLDecode.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import org.apache.hadoop.hive.ql.exec.UDF; 4 | import org.apache.hadoop.hive.ql.exec.Description; 5 | import org.apache.hadoop.io.Text; 6 | import java.net.URLDecoder; 7 | 8 | @Description( 9 | name = "urldecode", 10 | value = "_FUNC_(str) - Returns urldecoded string", 11 | extended = "Example:\n" + 12 | " > SELECT urldecode(url_refer) FROM visits a;\n" + 13 | " http://www.livingsocial.com/Buy Now" 14 | ) 15 | public class URLDecode extends UDF { 16 | public Text evaluate(Text s) { 17 | Text to_value = null; 18 | if(s != null) { 19 | try { 20 | to_value.set(URLDecoder.decode(s.toString(), "UTF-8")); 21 | } catch (Exception e) { 22 | to_value = new Text(s); 23 | }; 24 | } 25 | return to_value; 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/UnixLiberalTimestamp.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | 4 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 5 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 6 | import org.apache.hadoop.hive.ql.exec.Description; 7 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 8 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; 9 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 10 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; 11 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDFUnixTimeStamp; 12 | import org.apache.hadoop.hive.ql.metadata.HiveException; 13 | import org.apache.hadoop.io.Text; 14 | 15 | @Description( 16 | name = "unix_liberal_timestamp", 17 | value = "_FUNC_(str) - gets unix timestamp in either yyyy-MM-dd HH:mm:ss or yyyy-MM-dd format - returns null if input is null", 18 | extended = "Example:\n" + 19 | " > SELECT a.* FROM srcpart a WHERE _FUNC_ (a.hr) < unix_timestamp() LIMIT 1;\n" 20 | ) 21 | public class UnixLiberalTimestamp extends GenericUDFUnixTimeStamp { 22 | 23 | private transient StringObjectInspector stringOI; 24 | 25 | public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { 26 | if (arguments.length != 1) { 27 | throw new UDFArgumentLengthException(getName().toUpperCase() + " only takes 1 arguments: String"); 28 | } 29 | super.initialize(new ObjectInspector[]{arguments[0], 30 | PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveObjectInspector.PrimitiveCategory.STRING)}); 31 | 32 | stringOI = (StringObjectInspector) arguments[0]; 33 | return PrimitiveObjectInspectorFactory.writableLongObjectInspector; 34 | } 35 | 36 | public Object evaluate(DeferredObject[] arguments) throws HiveException { 37 | String datestring = stringOI.getPrimitiveJavaObject(arguments[0].get()); 38 | if (datestring == null) return null; 39 | if (datestring.length() == 19) // timestamp 40 | return super.evaluate(new DeferredObject[]{arguments[0], 41 | new DeferredJavaObject("yyyy-MM-dd HH:mm:ss")}); 42 | else if (datestring.length() > 19) // timestamp with milliseconds 43 | return super.evaluate(new DeferredObject[]{arguments[0], 44 | new DeferredJavaObject("yyyy-MM-dd HH:mm:ss.S")}); 45 | else // date 46 | return super.evaluate(new DeferredObject[]{arguments[0], 47 | new DeferredJavaObject("yyyy-MM-dd")}); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/UserAgentParser.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import java.text.ParseException; 4 | import java.io.IOException; 5 | import java.text.SimpleDateFormat; 6 | import java.util.Calendar; 7 | import java.util.Date; 8 | 9 | import org.apache.hadoop.io.IntWritable; 10 | import org.apache.hadoop.io.Text; 11 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 12 | import org.apache.hadoop.hive.ql.exec.Description; 13 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 14 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 15 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 16 | import org.apache.hadoop.hive.ql.metadata.HiveException; 17 | import org.apache.hadoop.hive.ql.udf.UDFType; 18 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 19 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category; 20 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters; 21 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; 22 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; 23 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 24 | 25 | import ua_parser.Parser; 26 | import ua_parser.Client; 27 | 28 | import org.apache.commons.logging.Log; 29 | import org.apache.commons.logging.LogFactory; 30 | 31 | @UDFType(deterministic = true) 32 | @Description(name = "user_agent_parser", 33 | value = "_FUNC_(string, string) - returns parsed information about a user agent string", 34 | extended = "Examples:\n" 35 | + " > SELECT _FUNC_('Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3','os_major') FROM src LIMIT 1;\n" 36 | + " iOS 5 \n") 37 | public class UserAgentParser extends GenericUDF { 38 | 39 | private Text result = new Text(); 40 | private ObjectInspectorConverters.Converter[] converters; 41 | static final Log LOG = LogFactory.getLog(UserAgentParser.class.getName()); 42 | 43 | private static final Parser uaParser; 44 | static { 45 | try { 46 | uaParser = new Parser(); 47 | } 48 | catch(IOException e) { 49 | LOG.warn("Caught IOException: " + e.getMessage()); 50 | throw new RuntimeException("could not instantiate parser"); 51 | } 52 | } 53 | 54 | 55 | private enum userOptions { 56 | os, os_family, os_major, os_minor, ua, ua_family, ua_major, ua_minor, device 57 | } 58 | 59 | public UserAgentParser() { 60 | } 61 | 62 | @Override 63 | public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { 64 | if (arguments.length > 2 || arguments.length == 0) { 65 | throw new UDFArgumentLengthException("_FUNC_ expects exactly 2 arguments"); 66 | } 67 | for (int i = 0; i < arguments.length; i++) { 68 | if (arguments[i].getCategory() != Category.PRIMITIVE) { 69 | throw new UDFArgumentTypeException(i, 70 | "A string argument was expected but an argument of type " + arguments[i].getTypeName() 71 | + " was given."); 72 | 73 | } 74 | 75 | // Now that we have made sure that the argument is of primitive type, we can get the primitive 76 | // category 77 | PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arguments[i]) 78 | .getPrimitiveCategory(); 79 | 80 | if (primitiveCategory != PrimitiveCategory.STRING 81 | && primitiveCategory != PrimitiveCategory.VOID) { 82 | throw new UDFArgumentTypeException(i, 83 | "A string argument was expected but an argument of type " + arguments[i].getTypeName() 84 | + " was given."); 85 | } 86 | } 87 | 88 | converters = new ObjectInspectorConverters.Converter[arguments.length]; 89 | for (int i = 0; i < arguments.length; i++) { 90 | converters[i] = ObjectInspectorConverters.getConverter(arguments[i], 91 | PrimitiveObjectInspectorFactory.writableStringObjectInspector); 92 | } 93 | 94 | // We will be returning a Text object 95 | return PrimitiveObjectInspectorFactory.writableStringObjectInspector; 96 | } 97 | 98 | /** 99 | * Get a parsed string from an input user agent string 100 | * 101 | * @param UserAgent - string containing the user agent to parse 102 | * 103 | * @param options - options from the set of strings "os", "device", and "ua". "os" and "ua" 104 | * may optionally append "_family", "_major" and "_minor". 105 | * "os" and "ua" return json; other options return a string only. 106 | * No option returns a JSON formatted string (example: "{user_agent: %s, os: %s, device: %s}") 107 | * 108 | * @return string containing a parsed user agent based upon options entered. 109 | * string. 110 | */ 111 | public Object evaluate(DeferredObject[] arguments) throws HiveException { 112 | 113 | assert (arguments.length>0 && arguments.length<3); 114 | Text UserAgent = (Text) converters[0].convert(arguments[0].get()); 115 | Text options = (arguments.length == 2 ? (Text) converters[1].convert(arguments[1].get()) : null) ; 116 | 117 | if (UserAgent == null ) { 118 | return null; 119 | } 120 | 121 | try { 122 | Client c = uaParser.parse(UserAgent.toString()); 123 | 124 | if (options == null) { 125 | result.set(c.toString()); 126 | } 127 | 128 | else { 129 | userOptions uo = userOptions.valueOf(options.toString().toLowerCase()); 130 | 131 | switch (uo) { 132 | case os: 133 | result.set(c.os.toString()); 134 | break; 135 | case os_family: 136 | result.set(c.os.family == null ? "null" : c.os.family ); 137 | break; 138 | case os_major: 139 | result.set(c.os.major == null ? "null" : c.os.major ); 140 | break; 141 | case os_minor: 142 | result.set(c.os.minor == null ? "null" : c.os.minor ); 143 | break; 144 | case ua: 145 | result.set(c.userAgent.toString()); 146 | break; 147 | case ua_family: 148 | result.set(c.userAgent.family == null ? "null" : c.userAgent.family ); 149 | break; 150 | case ua_major: 151 | result.set(c.userAgent.major == null ? "null" : c.userAgent.major ); 152 | break; 153 | case ua_minor: 154 | result.set(c.userAgent.minor == null ? "null" : c.userAgent.minor ); 155 | break; 156 | case device: 157 | result.set(c.device.family == null ? "null" : c.device.family ); 158 | break; 159 | default: 160 | result = null; 161 | break; 162 | } 163 | } 164 | } catch (IllegalArgumentException e) { 165 | LOG.warn("Caught IllegalArgumentException: " + e.getMessage()); 166 | return null; 167 | } 168 | 169 | return result; 170 | } 171 | 172 | // public Text evaluate(Text UserAgent) { 173 | // return evaluate(UserAgent, null); 174 | // } 175 | @Override 176 | public String getDisplayString(String[] children) { 177 | assert (children.length > 0 && children.length < 3); 178 | return "user_agent_parser(" + children[0] + ( children.length == 1 ? "" : ", " + children[1] ) + ")"; 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/ZTest.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import org.apache.commons.math.MathException; 4 | import org.apache.commons.math.distribution.NormalDistribution; 5 | import org.apache.commons.math.distribution.NormalDistributionImpl; 6 | import org.apache.hadoop.hive.ql.exec.Description; 7 | import org.apache.hadoop.hive.ql.exec.UDF; 8 | import org.apache.hadoop.hive.serde2.io.DoubleWritable; 9 | import org.apache.hadoop.io.LongWritable; 10 | 11 | @Description( 12 | name = "p_value", 13 | value = "_FUNC_(double controlAvg, double controlStddev, long controlSize, double treatmentAvg, double treatmentStddev, long treatmentSize) - Returns the p_value for the control and treatment groups based on the passed in stats", 14 | extended = "Example:\n" + 15 | " > SELECT p_value(avg(if(control=1, revenue, 0)), stddev_pop(if(control=1, revenue, 0)), sum(if(control=1, 1, 0)), \n" + 16 | " avg(if(control=0, revenue, 0)), stddev_pop(if(control=0, revenue, 0)), sum(if(control=0, 1, 0))) \n" + 17 | " FROM revenue_table;\n" + 18 | "\n" + 19 | " Alternate format: p_value(critical_value). This skips the rest and just does a t-dist lookup" 20 | ) 21 | public class ZTest extends UDF { 22 | 23 | private static NormalDistribution distribution = new NormalDistributionImpl(); 24 | 25 | public double pval(double val){ 26 | try { 27 | return 2 * (1 - distribution.cumulativeProbability(val)); 28 | } catch (MathException e) { 29 | throw new RuntimeException(e); 30 | } 31 | } 32 | 33 | private double criticalValue(double controlAvg, double controlStddev, long controlSize, 34 | double treatmentAvg, double treatmentStddev, long treatmentSize) { 35 | return Math.abs(treatmentAvg - controlAvg) / Math.sqrt( 36 | (treatmentStddev*treatmentStddev/treatmentSize) + 37 | (controlStddev*controlStddev/controlSize)); 38 | } 39 | 40 | private double pval(final double controlAvg, final double controlStddev, final long controlSize, 41 | final double treatmentAvg, final double treatmentStddev, final long treatmentSize) { 42 | 43 | double critValue = criticalValue(controlAvg, controlStddev, controlSize, 44 | treatmentAvg, treatmentStddev, treatmentSize); 45 | return pval(critValue); 46 | } 47 | 48 | 49 | public DoubleWritable evaluate(final DoubleWritable criticalValue) { 50 | if (criticalValue == null) return null; 51 | double val = criticalValue.get(); 52 | return new DoubleWritable(pval(val)); 53 | } 54 | 55 | // For now ignore the degrees of freedom and use the infinite degrees model 56 | public DoubleWritable evaluate(final DoubleWritable criticalValue, final LongWritable degreesOfFreedom) { 57 | return evaluate(criticalValue); 58 | } 59 | 60 | public DoubleWritable evaluate(final DoubleWritable controlAvg, final DoubleWritable controlStddev, final LongWritable controlSize, 61 | final DoubleWritable treatmentAvg, final DoubleWritable treatmentStddev, final LongWritable treatmentSize) { 62 | if( controlAvg == null || controlSize == null || controlStddev == null || 63 | treatmentAvg == null || treatmentSize == null || treatmentStddev == null) { 64 | return null; 65 | } 66 | 67 | return new DoubleWritable(pval(controlAvg.get(), controlStddev.get(), controlSize.get(), 68 | treatmentAvg.get(), treatmentStddev.get(), treatmentSize.get())); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udf/gpsDistanceFrom.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udf; 2 | 3 | import org.apache.hadoop.hive.ql.exec.UDF; 4 | import org.apache.hadoop.hive.ql.exec.Description; 5 | import org.apache.hadoop.io.Text; 6 | //import org.apache.hadoop.io.DoubleWritable; 7 | import org.apache.hadoop.hive.serde2.io.DoubleWritable; 8 | // import org.apache.log4j.Logger; 9 | import org.apache.commons.logging.Log; 10 | import org.apache.commons.logging.LogFactory; 11 | 12 | @Description( 13 | name = "gpsDistanceFrom", 14 | value = "_FUNC_(double,double,double,double, text {optional} ) - Returns distance as a double in miles (by default). Accepts 'km' as an optional parameter", 15 | extended = "Example:\n" + 16 | " > SELECT gpsDistanceFrom(a.latitude,a.longitude,b.latitude,b.longitude,'km') FROM visits a join users u on a.user_id=u.id;\n" + 17 | " 1.215615431564 " 18 | ) 19 | 20 | /* 21 | calculation of distance between two points using the haversine formula 22 | 23 | may look into overloading evaluate to accept 'km' as a 5th arg, returning distance in km. For now, returns distance in miles. 24 | 25 | ** 2012-12-18 - updated to return null if any of the inputs return null; changed return type to DoubleWritable. 26 | */ 27 | public class gpsDistanceFrom extends UDF { 28 | 29 | private DoubleWritable result = new DoubleWritable(); 30 | static final Log LOG = LogFactory.getLog(gpsDistanceFrom.class.getName()); 31 | 32 | public DoubleWritable evaluate(DoubleWritable lat1, DoubleWritable lng1, DoubleWritable lat2, DoubleWritable lng2, Text options) { 33 | //set up a few variables 34 | double earthRadius = 3958.75; 35 | double kmConversion = 1.609344; 36 | 37 | if(lat1==null || lng1 == null || lat2 == null || lng2 == null) 38 | return null; 39 | 40 | 41 | double dLat=Math.toRadians(lat2.get()-lat1.get()); 42 | double dLng=Math.toRadians(lng2.get()-lng1.get()); 43 | double p1 = Math.sin(dLat/2) * Math.sin(dLat/2) + 44 | Math.cos(Math.toRadians(lat1.get())) * Math.cos(Math.toRadians(lat2.get())) * 45 | Math.sin(dLng/2) * Math.sin(dLng/2); 46 | double p2 = 2 * Math.atan2(Math.sqrt(p1), Math.sqrt(1-p1)); 47 | double dist=earthRadius * p2; 48 | 49 | // add option to return kilometers 50 | if (options != null && options.toString().toLowerCase().equals("km")) { 51 | result.set(dist * kmConversion); 52 | } 53 | else { 54 | result.set(dist); 55 | } 56 | return result; 57 | } 58 | 59 | public DoubleWritable evaluate(DoubleWritable lat1, DoubleWritable lng1, DoubleWritable lat2, DoubleWritable lng2) { 60 | return evaluate(lat1, lng1, lat2, lng2, null); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udtf/BinCase.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udtf; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.lang.StringBuffer; 6 | 7 | import com.livingsocial.hive.utils.KISSInspector; 8 | import org.apache.hadoop.hive.ql.udf.UDFBin; 9 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF; 10 | import org.apache.hadoop.hive.ql.exec.UDF; 11 | import org.apache.hadoop.hive.ql.exec.Description; 12 | import org.apache.hadoop.io.Text; 13 | import org.apache.hadoop.io.LongWritable; 14 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 15 | import org.apache.hadoop.hive.ql.metadata.HiveException; 16 | import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; 17 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 18 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 19 | import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; 20 | 21 | 22 | @Description(name = "bin_case", 23 | value = "_FUNC_(column, (array of bit field names)) - table generating function that spits out column name for each bit position that is a 1") 24 | public class BinCase extends GenericUDTF { 25 | 26 | private class BinCaseSelector { 27 | private KISSInspector bitfield_inspector; 28 | private ListObjectInspector bitnames_inspector; 29 | private UDFBin b; 30 | private ArrayList result; 31 | public BinCaseSelector(ObjectInspector bfi, ObjectInspector bni) { 32 | bitfield_inspector = new KISSInspector(bfi); 33 | bitnames_inspector = (ListObjectInspector) bni; 34 | result = new ArrayList(); 35 | b = new UDFBin(); 36 | } 37 | 38 | public ArrayList getNames(Object bf, Object bn) { 39 | result.clear(); 40 | List names = bitnames_inspector.getList(bn); 41 | long value = bitfield_inspector.toLong(bf); 42 | String values = b.evaluate(new LongWritable(value)).toString(); 43 | String reversed = (new StringBuffer(values)).reverse().toString(); 44 | for(int i=0; i fieldNames = new ArrayList(); 71 | ArrayList fieldOIs = new ArrayList(); 72 | fieldNames.add("col"); 73 | fieldOIs.add(bcs.getNamesInspector()); 74 | return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs); 75 | } 76 | 77 | private final Object[] forwardObj = new Object[1]; 78 | 79 | @Override 80 | public void process(Object[] o) throws HiveException { 81 | ArrayList names = bcs.getNames(o[0], o[1]); 82 | for (Object r : names) { 83 | forwardObj[0] = r; 84 | forward(forwardObj); 85 | } 86 | } 87 | 88 | @Override 89 | public String toString() { 90 | return "bin_case"; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udtf/FirstN.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udtf; 2 | 3 | import com.livingsocial.hive.utils.KISSInspector; 4 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 5 | import org.apache.hadoop.hive.ql.exec.Description; 6 | import org.apache.hadoop.hive.ql.metadata.HiveException; 7 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF; 8 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 9 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 10 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; 11 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory.*; 12 | import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; 13 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector; 14 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 15 | 16 | import java.util.ArrayList; 17 | 18 | @Description( 19 | name = "first_n", 20 | value = "_FUNC_(group_by, values, how_many) - return table of first how_many values by group_by" 21 | ) 22 | 23 | public class FirstN extends GenericUDTF { 24 | private class FirstNSelector { 25 | private KISSInspector group_inspector, value_inspector, max_inspector; 26 | private Object current_group = null; 27 | private int current_count; 28 | 29 | public FirstNSelector(ObjectInspector gpoi, ObjectInspector vpoi, ObjectInspector maxoi) { 30 | group_inspector = new KISSInspector(gpoi); 31 | value_inspector = new KISSInspector(vpoi); 32 | max_inspector = new KISSInspector(maxoi); 33 | } 34 | 35 | public Object[] getFirstN(Object group, Object value, Object max) { 36 | Object[] result = null; 37 | int maxi = (new Float(max_inspector.toFloat(max))).intValue(); 38 | 39 | if(!group_inspector.get(group).equals(current_group)) { 40 | current_group = group_inspector.get(group); 41 | current_count = 1; 42 | result = new Object[] { group_inspector.get(group), value_inspector.get(value) }; 43 | } else if(current_count < maxi) { 44 | current_count += 1; 45 | result = new Object[] { group_inspector.get(group), value_inspector.get(value) }; 46 | } 47 | 48 | return result; 49 | } 50 | 51 | public AbstractPrimitiveJavaObjectInspector getGroupInspector() { 52 | return group_inspector.getAnInspector(); 53 | } 54 | 55 | public AbstractPrimitiveJavaObjectInspector getValueInspector() { 56 | return value_inspector.getAnInspector(); 57 | } 58 | } 59 | 60 | FirstNSelector firstNSelector; 61 | 62 | @Override 63 | public void close() throws HiveException { 64 | } 65 | 66 | @Override 67 | public StructObjectInspector initialize(ObjectInspector [] args) throws UDFArgumentException { 68 | if(args.length != 3 || !KISSInspector.isPrimitive(args[0]) || !KISSInspector.isPrimitive(args[1]) || !KISSInspector.isPrimitive(args[2])) 69 | throw new UDFArgumentException("first_n() takes three primitive arguments"); 70 | 71 | firstNSelector = new FirstNSelector(args[0], args[1], args[2]); 72 | 73 | ArrayList fieldNames = new ArrayList(); 74 | ArrayList fieldOIs = new ArrayList(); 75 | fieldNames.add("group"); 76 | fieldNames.add("value"); 77 | fieldOIs.add(firstNSelector.getGroupInspector()); 78 | fieldOIs.add(firstNSelector.getValueInspector()); 79 | return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs); 80 | } 81 | 82 | @Override 83 | public void process(Object [] o) throws HiveException { 84 | Object result[] = firstNSelector.getFirstN(o[0], o[1], o[2]); 85 | if(result != null) 86 | forward(result); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/udtf/Intervals.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.udtf; 2 | 3 | import com.livingsocial.hive.utils.KISSInspector; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.text.ParseException; 8 | import java.text.SimpleDateFormat; 9 | 10 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 11 | import org.apache.hadoop.hive.ql.exec.Description; 12 | import org.apache.hadoop.hive.ql.metadata.HiveException; 13 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF; 14 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 15 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 16 | import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; 17 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 18 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; 19 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; 20 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory.*; 21 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector; 22 | 23 | @Description( 24 | name = "intervals", 25 | value = "_FUNC_(group_by, values) - get all intervals between values by group_by" 26 | ) 27 | 28 | public class Intervals extends GenericUDTF { 29 | private class Intervaler { 30 | private KISSInspector group_inspector, value_inspector; 31 | private Object current_group = null; 32 | private float last_value; 33 | 34 | public Intervaler(ObjectInspector gpoi, ObjectInspector vpoi) { 35 | group_inspector = new KISSInspector(gpoi); 36 | value_inspector = new KISSInspector(vpoi); 37 | } 38 | 39 | public Object[] getInterval(Object group, Object value) { 40 | float new_value = value_inspector.toFloat(value); 41 | Object[] result = null; 42 | 43 | if(!group_inspector.get(group).equals(current_group)) { 44 | current_group = group_inspector.get(group); 45 | } else { 46 | Float diff = new Float(new_value - last_value); 47 | result = new Object[] { group_inspector.get(group), diff }; 48 | } 49 | 50 | last_value = new_value; 51 | return result; 52 | } 53 | 54 | public AbstractPrimitiveJavaObjectInspector getGroupInspector() { 55 | return group_inspector.getAnInspector(); 56 | } 57 | } 58 | 59 | Intervaler intervaler; 60 | 61 | @Override 62 | public void close() throws HiveException { 63 | } 64 | 65 | @Override 66 | public StructObjectInspector initialize(ObjectInspector [] args) throws UDFArgumentException { 67 | if(args.length != 2 || !KISSInspector.isPrimitive(args[0]) || !KISSInspector.isPrimitive(args[1])) 68 | throw new UDFArgumentException("intervals() takes two primitive arguments"); 69 | 70 | intervaler = new Intervaler(args[0], args[1]); 71 | 72 | ArrayList fieldNames = new ArrayList(); 73 | ArrayList fieldOIs = new ArrayList(); 74 | fieldNames.add("group"); 75 | fieldNames.add("interval"); 76 | fieldOIs.add(intervaler.getGroupInspector()); 77 | fieldOIs.add(PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveCategory.FLOAT)); 78 | return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs); 79 | } 80 | 81 | @Override 82 | public void process(Object [] o) throws HiveException { 83 | Object result[] = intervaler.getInterval(o[0], o[1]); 84 | if(result != null) 85 | forward(result); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/utils/KISSInspector.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.utils; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.livingsocial.hive.Utils; 7 | 8 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 9 | import org.apache.hadoop.hive.ql.exec.Description; 10 | import org.apache.hadoop.hive.ql.metadata.HiveException; 11 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF; 12 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 13 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 14 | import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; 15 | import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; 16 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 17 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; 18 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; 19 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory.*; 20 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector; 21 | 22 | public class KISSInspector { 23 | private PrimitiveObjectInspector inspector; 24 | 25 | public KISSInspector(ObjectInspector arg) { 26 | inspector = (PrimitiveObjectInspector) arg; 27 | } 28 | 29 | public boolean sameAsTypeIn(ListObjectInspector loi) { 30 | PrimitiveObjectInspector poi = (PrimitiveObjectInspector) loi.getListElementObjectInspector(); 31 | return poi.getPrimitiveCategory() == getCategory(); 32 | } 33 | 34 | public PrimitiveCategory getCategory() { 35 | return inspector.getPrimitiveCategory(); 36 | } 37 | 38 | public AbstractPrimitiveJavaObjectInspector getAnInspector() { 39 | return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(getCategory()); 40 | } 41 | 42 | public Object get(Object value) { 43 | return inspector.getPrimitiveJavaObject(value); 44 | } 45 | 46 | public float toFloat(Object value) { 47 | float result; 48 | value = get(value); 49 | switch(getCategory()) { 50 | case STRING: 51 | long timestamp = Utils.stringToTimestamp((String) value); 52 | result = (timestamp < 0) ? 0L : (new Long(timestamp)).floatValue(); 53 | break; 54 | case BOOLEAN: 55 | result = ((Boolean) value).booleanValue() ? 1.0f : 0.0f; 56 | break; 57 | case UNKNOWN: 58 | result = 0.0f; 59 | break; 60 | case VOID: 61 | result = 0.0f; 62 | break; 63 | default: // all other types are numerical 64 | result = ((Number) value).floatValue(); 65 | break; 66 | } 67 | return result; 68 | } 69 | 70 | public long toLong(Object value) { 71 | long result; 72 | value = get(value); 73 | switch(getCategory()) { 74 | case STRING: 75 | long timestamp = Utils.stringToTimestamp((String) value); 76 | result = (timestamp < 0) ? 0L : (new Long(timestamp)).longValue(); 77 | break; 78 | case BOOLEAN: 79 | result = ((Boolean) value).booleanValue() ? 1L : 0L; 80 | break; 81 | case UNKNOWN: 82 | result = 0L; 83 | break; 84 | case VOID: 85 | result = 0L; 86 | break; 87 | default: // all other types are numerical 88 | result = ((Number) value).longValue(); 89 | break; 90 | } 91 | return result; 92 | } 93 | 94 | public boolean isNull() { 95 | return getCategory() == PrimitiveCategory.VOID; 96 | } 97 | 98 | public boolean isString() { 99 | return getCategory() == PrimitiveCategory.STRING; 100 | } 101 | 102 | public static boolean isPrimitive(ObjectInspector oi) { 103 | return oi.getCategory() == ObjectInspector.Category.PRIMITIVE; 104 | } 105 | 106 | public static boolean isList(ObjectInspector oi) { 107 | return oi.getCategory() == ObjectInspector.Category.LIST; 108 | } 109 | 110 | public boolean equalPrimitive(Object first, Object second) { 111 | if((first == null && second != null) || (first != null && second == null)) 112 | return false; 113 | if(first == null && second == null) 114 | return true; 115 | 116 | first = get(first); 117 | second = get(second); 118 | boolean result; 119 | switch(getCategory()) { 120 | case STRING: 121 | result = ((String) first).compareTo((String) second) == 0; 122 | break; 123 | case BOOLEAN: 124 | result = ((Boolean) first).equals((Boolean) second); 125 | break; 126 | case UNKNOWN: 127 | result = first.equals(second); 128 | break; 129 | case VOID: 130 | result = first.equals(second); 131 | break; 132 | default: // all other types are numerical 133 | result = ((Integer) first).intValue() == ((Integer) second).intValue(); 134 | break; 135 | } 136 | return result; 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/main/java/com/livingsocial/hive/utils/ScriptingHelper.java: -------------------------------------------------------------------------------- 1 | package com.livingsocial.hive.utils; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | import javax.script.Invocable; 8 | import javax.script.ScriptEngine; 9 | import javax.script.ScriptEngineManager; 10 | import javax.script.ScriptException; 11 | 12 | import org.apache.hadoop.conf.Configuration; 13 | import org.apache.hadoop.fs.FileSystem; 14 | import org.apache.hadoop.fs.Path; 15 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 16 | import org.apache.hadoop.hive.ql.metadata.HiveException; 17 | import org.apache.hadoop.hive.ql.parse.SemanticException; 18 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDFUtils; 19 | import org.apache.hadoop.hive.serde2.objectinspector.ConstantObjectInspector; 20 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 21 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters; 22 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter; 23 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; 24 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 25 | import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils; 26 | 27 | public class ScriptingHelper { 28 | 29 | // Offset to get past the constants in the arg list 30 | private static int ARG_OFFSET = 3; 31 | 32 | public static class InitializationContainer { 33 | public String script; 34 | public String language; 35 | public ObjectInspector[] argumentOIs; 36 | 37 | public String returnType; 38 | public ObjectInspector outputOi; 39 | public ObjectInspector outputJavaOi; 40 | public GenericUDFUtils.ReturnObjectInspectorResolver returnOIResolver; 41 | 42 | public int argOffset = ARG_OFFSET; 43 | public Invocable engine; 44 | 45 | } 46 | 47 | public static InitializationContainer initialize(ObjectInspector[] arguments) 48 | throws SemanticException { 49 | 50 | InitializationContainer rtn = new InitializationContainer(); 51 | 52 | if (arguments != null) { 53 | // Only validate inputs if this is the main call, for merging and terminating this step is not needed. 54 | 55 | // Nothing else can really be validated until evaluation time 56 | if (arguments.length < rtn.argOffset+1) { 57 | throw new SemanticException( 58 | "At least " + (rtn.argOffset+1) + " arguments are required, the script to run, the script language, the return type, and at least one argument, got " 59 | + arguments.length + " arguments passed in"); 60 | } 61 | 62 | // Convert all the constant string params 63 | rtn.script = getConstString(arguments[0], 1); 64 | rtn.language = getConstString(arguments[1], 2); 65 | rtn.returnType = getConstString(arguments[2], 3); 66 | 67 | // Get converters for all the actual arguments 68 | rtn.argumentOIs = new ObjectInspector[arguments.length - rtn.argOffset]; 69 | System.arraycopy(arguments, rtn.argOffset, rtn.argumentOIs, 0, rtn.argumentOIs.length); 70 | 71 | rtn.outputOi = javaObjectInspectorFromType(rtn.returnType); 72 | rtn.outputJavaOi = javaObjectInspectorFromType(rtn.returnType); 73 | rtn.returnOIResolver = buildReturnResolver(rtn.outputOi); 74 | 75 | } 76 | 77 | // Do this to test the script and make sure it's valid client-side 78 | try { 79 | rtn.engine = initializeEngine(rtn.language, rtn.script); 80 | } catch (HiveException e) { 81 | throw new SemanticException("The Script or Language settings seem to have problems: " + e, e); 82 | } 83 | 84 | return rtn; 85 | } 86 | 87 | public static String getConstString(ObjectInspector argument, int num) 88 | throws UDFArgumentTypeException { 89 | if (!ObjectInspectorUtils.isConstantObjectInspector(argument)) { 90 | new Exception().printStackTrace(System.err); 91 | throw new UDFArgumentTypeException(num, 92 | "The script argument " + num + " must be a constant string, but " 93 | + argument.getTypeName() + " was passed instead. (class=" + argument.getClass().getName() + ")"); 94 | } 95 | return (String) ObjectInspectorConverters.getConverter( 96 | argument, 97 | PrimitiveObjectInspectorFactory.javaStringObjectInspector).convert(((ConstantObjectInspector)argument).getWritableConstantValue()); 98 | } 99 | 100 | public static ObjectInspector javaObjectInspectorFromType(String returnType) throws SemanticException { 101 | return TypeInfoUtils.getStandardJavaObjectInspectorFromTypeInfo(TypeInfoUtils.getTypeInfoFromTypeString(returnType)); 102 | } 103 | 104 | public static ObjectInspector writableObjectInspectorFromType(String returnType) throws SemanticException { 105 | return TypeInfoUtils.getStandardWritableObjectInspectorFromTypeInfo(TypeInfoUtils.getTypeInfoFromTypeString(returnType)); 106 | } 107 | 108 | public static GenericUDFUtils.ReturnObjectInspectorResolver buildReturnResolver(ObjectInspector outputOi) throws SemanticException { 109 | GenericUDFUtils.ReturnObjectInspectorResolver rtn = new GenericUDFUtils.ReturnObjectInspectorResolver(true); 110 | rtn.update(outputOi); 111 | return rtn; 112 | } 113 | 114 | public static Converter getConverter(ObjectInspector oi) { 115 | ObjectInspector output = ObjectInspectorUtils.getStandardObjectInspector(oi); 116 | return output != null ? ObjectInspectorConverters.getConverter(oi, output) : null; 117 | } 118 | 119 | /** 120 | * Builds an invocable scripting engine using the passed in args. 121 | * This loads and compiles the script so the functions are available 122 | * in the returned Invocable engine. 123 | */ 124 | public static Invocable initializeEngine(String language, String script) throws HiveException { 125 | 126 | // Make sure we can find a scripting engine for the language 127 | ScriptEngine tmp = new ScriptEngineManager().getEngineByName(language); 128 | if (tmp == null) { 129 | throw new HiveException( 130 | "Could not find a script implementation for language " + language); 131 | } 132 | 133 | if (!(tmp instanceof Invocable)) { 134 | throw new HiveException("The script engine for " + language 135 | + " doesn't support invocable"); 136 | } 137 | 138 | Invocable engine = (Invocable) tmp; 139 | 140 | String scriptText; 141 | if (script.startsWith("/")) { 142 | // The file is a file in HDFS 143 | 144 | // Note: this is not the best way to do this, but it works 145 | Configuration conf = new Configuration(); 146 | String root = conf.get("fs.defaultFS"); 147 | String path = root + script; 148 | try { 149 | FileSystem fs = FileSystem.get(conf); 150 | Path scriptFile = new Path(path); 151 | BufferedReader reader = new BufferedReader(new InputStreamReader( 152 | fs.open(scriptFile))); 153 | String line = null; 154 | StringBuilder scriptBuilder = new StringBuilder(); 155 | while ((line = reader.readLine()) != null) { 156 | scriptBuilder.append(line); 157 | scriptBuilder.append("\n"); 158 | } 159 | scriptText = scriptBuilder.toString(); 160 | } catch (IOException e) { 161 | throw new HiveException( 162 | "Unable to load the script from file " + script, e); 163 | } 164 | } else { 165 | // The script is a literal script and should be handled directly 166 | scriptText = script; 167 | } 168 | 169 | try { 170 | tmp.eval(scriptText); 171 | } catch (ScriptException e) { 172 | throw new HiveException( 173 | "Something went wrong with the script when evaluating it", e); 174 | } 175 | 176 | return engine; 177 | 178 | } 179 | 180 | } 181 | --------------------------------------------------------------------------------