├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── yahoo │ │ └── hive │ │ └── udf │ │ └── funnel │ │ ├── Conversion.java │ │ ├── Fallout.java │ │ ├── Funnel.java │ │ ├── FunnelAggregateBuffer.java │ │ ├── ListUtils.java │ │ ├── Merge.java │ │ └── MergeAggregateBuffer.java └── resources │ └── checkstyle.xml └── test ├── java └── com │ └── yahoo │ └── hive │ └── udf │ └── funnel │ ├── ConversionTest.java │ ├── FalloutTest.java │ ├── FunnelTest.java │ └── MergeTest.java └── resources └── log4j.properties /.gitignore: -------------------------------------------------------------------------------- 1 | target/** 2 | *.swp 3 | *.swo 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | after_success: 5 | - mvn clean cobertura:cobertura coveralls:report 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | jar: 2 | mvn clean checkstyle:check package 3 | 4 | test: 5 | mvn clean checkstyle:check test 6 | 7 | code-coverage: 8 | mvn checkstyle:check cobertura:cobertura 9 | 10 | clean: 11 | mvn clean 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hive Funnel Analysis UDFs 2 | 3 | [![Build Status](https://travis-ci.org/yahoo/hive-funnel-udf.svg?branch=master)](https://travis-ci.org/yahoo/hive-funnel-udf) 4 | [![Coverage Status](https://coveralls.io/repos/github/yahoo/hive-funnel-udf/badge.svg?branch=master)](https://coveralls.io/github/yahoo/hive-funnel-udf?branch=master) 5 | [![Apache License 2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg?style=flat)](LICENSE) 6 | 7 | [Funnel analysis](https://en.wikipedia.org/wiki/Funnel_analysis) is a method for 8 | tracking user conversion rates across actions. This enables detection of actions 9 | causing high user fallout. 10 | 11 | These Hive UDFs enables funnel analysis to be performed simply and easily on any 12 | Hive table. 13 | 14 | ## Table of Contents 15 | 16 | * [Requirements](#requirements) 17 | * [How to build](#how-to-build) 18 | * [Build JAR](#build-jar) 19 | * [Register JAR with Hive](#register-jar-with-hive) 20 | * [How to use](#how-to-use) 21 | * [`funnel`](#funnel) 22 | * [`funnel_merge`](#funnel_merge) 23 | * [`funnel_conversion`](#funnel_conversion) 24 | * [`funnel_fallout`](#funnel_fallout) 25 | * [Security](#security) 26 | * [Examples](#examples) 27 | * [Simple funnel](#simple-funnel) 28 | * [Simple funnel with conversion](#simple-funnel-with-conversion) 29 | * [Funnel with multiple groups](#funnel-with-multiple-groups) 30 | * [Multiple parallel funnels](#multiple-parallel-funnels) 31 | * [Contributors](#contributors) 32 | * [License](#license) 33 | 34 | ## Requirements 35 | 36 | [Maven](https://maven.apache.org/index.html) is required to build the funnel 37 | UDFs. 38 | 39 | ## How to build 40 | 41 | There is a provided `Makefile` with all the build targets. 42 | 43 | ### Build JAR 44 | 45 | ```bash 46 | make jar 47 | ``` 48 | 49 | This creates a `funnel.jar` in the `target/` directory. 50 | 51 | ### Register JAR with Hive 52 | 53 | To use the funnel UDFs, you need to register it with Hive. 54 | 55 | With temporary functions: 56 | 57 | ```sql 58 | ADD JAR funnel.jar; 59 | CREATE TEMPORARY FUNCTION funnel AS 'com.yahoo.hive.udf.funnel.Funnel'; 60 | CREATE TEMPORARY FUNCTION funnel_merge AS 'com.yahoo.hive.udf.funnel.Merge'; 61 | CREATE TEMPORARY FUNCTION funnel_conversion AS 'com.yahoo.hive.udf.funnel.Conversion'; 62 | CREATE TEMPORARY FUNCTION funnel_fallout AS 'com.yahoo.hive.udf.funnel.Fallout'; 63 | ``` 64 | 65 | With permenant functions you need to put the JAR on HDFS, and it will be registered with a database (you have to replace `DATABASE` and `PATH_TO_JAR` with your values): 66 | 67 | ```sql 68 | CREATE FUNCTION DATABASE.funnel AS 'com.yahoo.hive.udf.funnel.Funnel' USING JAR 'hdfs:///PATH_TO_JAR/funnel.jar'; 69 | CREATE FUNCTION DATABASE.funnel_merge AS 'com.yahoo.hive.udf.funnel.Merge' USING JAR 'hdfs:///PATH_TO_JAR/funnel.jar'; 70 | CREATE FUNCTION DATABASE.funnel_conversion AS 'com.yahoo.hive.udf.funnel.Conversion' USING JAR 'hdfs:///PATH_TO_JAR/funnel.jar'; 71 | CREATE FUNCTION DATABASE.funnel_fallout AS 'com.yahoo.hive.udf.funnel.Fallout' USING JAR 'hdfs:///PATH_TO_JAR/funnel.jar'; 72 | ``` 73 | 74 | ## How to use 75 | 76 | There are four funnel UDFs provided: [`funnel`](#funnel), 77 | [`funnel_merge`](#funnel_merge), [`funnel_conversion`](#funnel_conversion), 78 | [`funnel_fallout`](#funnel_fallout). 79 | 80 | The [`funnel`](#funnel) UDF outputs an array of longs showing conversion rates 81 | across the provided funnel steps. 82 | 83 | The [`funnel_merge`](#funnel_merge) UDF merges multiple arrays of longs by 84 | adding them together. 85 | 86 | The [`funnel_conversion`](#funnel_conversion) UDF takes a raw count funnel result and 87 | converts it to the conversion rate. 88 | 89 | The [`funnel_fallout`](#funnel_fallout) UDF takes a raw count funnel result and 90 | converts it to the fallout rate. 91 | 92 | There is no need to sort the data on timestamp, the UDF will take care of it. If 93 | there is a collision in the timestamps, it then sorts on the action column. 94 | 95 | ### `funnel` 96 | `funnel(action_column, timestamp_column, array(funnel_1_a, funnel_1_b), array(funnel_2), ...)` 97 | - Builds a funnel report applied to the `action_column`, sorted by the 98 | `timestamp_column`. 99 | - The funnel steps are arrays of the same type as the `action` column. This allows 100 | for multiple matches to move to the next funnel. 101 | - For example, funnel_1 could be `array('register_button', 102 | 'facebook_invite_register')`. The funnel will match the first occurence 103 | of either of these actions and proceed to the next funnel. 104 | - Or, funnel_1 could just be `array('register_button')`. 105 | - You can have an arbitrary number of funnels. 106 | - The `timestamp_column` can be of any comparable type (Strings, Integers, 107 | Dates, etc). 108 | 109 | ### `funnel_merge` 110 | `funnel_merge(funnel_column)` 111 | - Merges funnels. Use with funnel UDF. 112 | 113 | ### `funnel_conversion` 114 | `funnel_conversion(funnel_column)` 115 | - Converts the result of a [`funnel_merge`](#funnel_merge) to a conversion 116 | rate. Use with funnel and funnel_merge UDF. 117 | - For example, a result from [`funnel_merge`](#funnel_merge) could look like 118 | `[245, 110, 54, 13]`. This is result is in raw counts. If we pass this 119 | through [`funnel_conversion`](#funnel_conversion) then it would look like 120 | `[1.0, 0.44, 0.49, 0.24]`. 121 | 122 | ### `funnel_fallout` 123 | `funnel_fallout(funnel_column)` 124 | - Converts the result of a [`funnel_merge`](#funnel_merge) to a fallout rate. 125 | Use with funnel and funnel_merge UDF. 126 | - For example, a result from [`funnel_merge`](#funnel_merge) could look like 127 | `[245, 110, 54, 13]`. This is result is in raw counts. If we pass this 128 | through [`funnel_fallout`](#funnel_fallout) then it would look like `[0.0, 129 | 0.55, 0.50, 0.75]`. 130 | 131 | ## Security 132 | 133 | Older versions of Hive have known security issues. Keep the following issues in mind when deciding what Hive version to use when building the UDFs. Use the following steps to mitigate these issues, or update to Hive 2.3.4 to avoid all issues at once. 134 | 135 | ### [CVE-2018-11777](https://nvd.nist.gov/vuln/detail/CVE-2018-11777) 136 | 137 | #### Description 138 | 139 | In Apache Hive 2.3.3, 3.1.0 and earlier, local resources on HiveServer2 machines are not properly protected against malicious user if ranger, sentry or sql standard authorizer is not in use. 140 | 141 | #### Resolution 142 | 143 | Update pom.xml to use Hive 2.3.4. 144 | 145 | ### [CVE-2018-1284](https://nvd.nist.gov/vuln/detail/CVE-2018-1284) 146 | 147 | #### Description 148 | 149 | In Apache Hive 0.6.0 to 2.3.2, malicious user might use any xpath UDFs (xpath/xpath_string/xpath_boolean/xpath_number/xpath_double/xpath_float/xpath_long/xpath_int/xpath_short) to expose the content of a file on the machine running HiveServer2 owned by HiveServer2 user (usually hive) if hive.server2.enable.doAs=false. 150 | 151 | #### Resolution 152 | 153 | Update pom.xml to use Hive 2.3.3 or do not set `hive.server2.enable.doAs` to `false`. 154 | 155 | ### [CVE-2015-7521](https://nvd.nist.gov/vuln/detail/CVE-2015-7521) 156 | 157 | #### Description 158 | 159 | The authorization framework in Apache Hive 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.2.0 and 1.2.1, on clusters protected by Ranger and SqlStdHiveAuthorization, allows attackers to bypass intended parent table access restrictions via unspecified partition-level operations. 160 | 161 | #### Resolution 162 | 163 | Update pom.xml to use Hive 1.2.2. 164 | 165 | ## Examples 166 | 167 | Assume a table `user_data`: 168 | 169 | | action | timestamp | user_id | gender | 170 | |---------------------|-----------|---------|--------| 171 | | signup_page | 100 | 1 | f | 172 | | confirm_button | 200 | 1 | f | 173 | | submit_button | 300 | 1 | f | 174 | | signup_page | 200 | 2 | m | 175 | | submit_button | 400 | 2 | m | 176 | | signup_page | 100 | 3 | f | 177 | | confirm_button | 200 | 3 | f | 178 | | decline | 200 | 3 | f | 179 | | ... | ... | ... | ... | 180 | 181 | ### Simple funnel 182 | 183 | ```sql 184 | SELECT funnel_merge(funnel) 185 | FROM (SELECT funnel(action, timestamp, array('signup_page', 'email_signup'), 186 | array('confirm_button'), 187 | array('submit_button')) AS funnel 188 | FROM user_data 189 | GROUP BY user_id) t1; 190 | ``` 191 | 192 | Result: `[3, 2, 1]` 193 | 194 | ### Simple funnel with conversion rate 195 | 196 | ```sql 197 | SELECT funnel_conversion(funnel_merge(funnel)) 198 | FROM (SELECT funnel(action, timestamp, array('signup_page'), 199 | array('confirm_button'), 200 | array('submit_button')) AS funnel 201 | FROM user_data 202 | GROUP BY user_id) t1; 203 | ``` 204 | 205 | Result: `[1.0, 0.66, 0.5]` 206 | 207 | ### Funnel with multiple groups 208 | 209 | ```sql 210 | SELECT gender, funnel_merge(funnel) 211 | FROM (SELECT gender, 212 | funnel(action, timestamp, array('signup_page'), 213 | array('confirm_button'), 214 | array('submit_button')) AS funnel 215 | FROM table 216 | GROUP BY user_id, gender) t1 217 | GROUP BY gender; 218 | ``` 219 | 220 | Result: `m: [1, 0, 0], f: [2, 2, 1]` 221 | 222 | ### Multiple parallel funnels 223 | 224 | ```sql 225 | SELECT funnel_merge(funnel1), funnel_merge(funnel2) 226 | FROM (SELECT funnel(action, timestamp, array('signup_page'), 227 | array('confirm_button'), 228 | array('submit_button')) AS funnel1 229 | funnel(action, timestamp, array('signup_page'), 230 | array('decline')) AS funnel2 231 | FROM table 232 | GROUP BY user_id) t1; 233 | ``` 234 | 235 | Result: `[3, 2, 1] [3, 1]` 236 | 237 | ## Contributors 238 | 239 | Josh Walters, [josh@joshwalters.com](mailto:josh@joshwalters.com) 240 | 241 | ## License 242 | 243 | [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 244 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.yahoo.hive.udf 5 | funnel 6 | jar 7 | 1.0 8 | funnel 9 | http://yahoo.com 10 | 11 | UTF-8 12 | 1.2.1 13 | 1.2.1 14 | 15 | 16 | 17 | org.apache.hive 18 | hive-exec 19 | ${hive.version} 20 | provided 21 | 22 | 23 | org.apache.hadoop 24 | hadoop-core 25 | ${hadoop.version} 26 | provided 27 | 28 | 29 | commons-logging 30 | commons-logging 31 | 1.1.1 32 | provided 33 | 34 | 35 | junit 36 | junit 37 | 4.12 38 | test 39 | 40 | 41 | org.mockito 42 | mockito-all 43 | 1.10.19 44 | test 45 | 46 | 47 | 48 | 49 | 50 | org.apache.maven.plugins 51 | maven-compiler-plugin 52 | 3.5 53 | 54 | 1.8 55 | 1.8 56 | 57 | 58 | 59 | org.apache.maven.plugins 60 | maven-jar-plugin 61 | 2.6 62 | 63 | ${project.artifactId} 64 | 65 | 66 | 67 | org.apache.maven.plugins 68 | maven-checkstyle-plugin 69 | 2.16 70 | 71 | 72 | org.apache.maven.plugins 73 | maven-checkstyle-plugin 74 | 2.16 75 | 76 | true 77 | src/main/resources/checkstyle.xml 78 | 79 | 80 | 81 | org.eluder.coveralls 82 | coveralls-maven-plugin 83 | 4.1.0 84 | 85 | 86 | 87 | 88 | 89 | 90 | org.codehaus.mojo 91 | cobertura-maven-plugin 92 | 2.7 93 | 94 | 95 | html 96 | xml 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /src/main/java/com/yahoo/hive/udf/funnel/Conversion.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | import org.apache.commons.logging.Log; 22 | import org.apache.commons.logging.LogFactory; 23 | import org.apache.hadoop.hive.ql.exec.Description; 24 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 25 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 26 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 27 | import org.apache.hadoop.hive.ql.metadata.HiveException; 28 | import org.apache.hadoop.hive.ql.udf.UDFType; 29 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 30 | import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; 31 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 32 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 33 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; 34 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 35 | 36 | @UDFType(deterministic = true) 37 | @Description(name = "conversion", 38 | value = "conversion(funnel) - Converts a funnel from raw counts to conversion rates.", 39 | extended = "Converts absolute count funnel to conversion rates.") 40 | public class Conversion extends GenericUDF { 41 | static final Log LOG = LogFactory.getLog(Conversion.class.getName()); 42 | 43 | private ListObjectInspector listInputObjectInspector; 44 | 45 | @Override 46 | public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { 47 | if (arguments.length != 1) { 48 | throw new UDFArgumentLengthException("The operator 'conversion' accepts 1 argument."); 49 | } 50 | 51 | // Check that the argument is a list type 52 | if (arguments[0].getCategory() != ObjectInspector.Category.LIST) { 53 | throw new UDFArgumentTypeException(1, "Only list type arguments are accepted, but " + arguments[0].getTypeName() + " was passed."); 54 | } 55 | 56 | // Check that the list is of type long 57 | // May want to add support for int/double/float later 58 | switch (((PrimitiveObjectInspector) ((ListObjectInspector) arguments[0]).getListElementObjectInspector()).getPrimitiveCategory()) { 59 | case LONG: 60 | break; 61 | default: 62 | throw new UDFArgumentTypeException(1, "A long array argument should be passed, but " + arguments[0].getTypeName() + " was passed instead."); 63 | } 64 | 65 | // Get the list object inspector 66 | listInputObjectInspector = (ListObjectInspector) arguments[0]; 67 | 68 | // This UDF will return a list of doubles 69 | return ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaDoubleObjectInspector); 70 | } 71 | 72 | @Override 73 | public Object evaluate(DeferredObject[] args) throws HiveException { 74 | // Check that we only have one argument 75 | if (args.length != 1) { 76 | return null; 77 | } 78 | 79 | // Get the deferred object into a list 80 | List funnel = (List) listInputObjectInspector.getList(args[0].get()); 81 | 82 | // Stores our return list 83 | List result = new ArrayList<>(); 84 | 85 | // If funnel is empty, return 86 | if (funnel.size() <= 0) { 87 | return result; 88 | } 89 | 90 | // First element is always 100% 91 | result.add(1.0); 92 | 93 | // Starting from the second element, calculate conversion rate 94 | for (int i = 1; i < funnel.size(); i++) { 95 | // Check for 0's 96 | if (funnel.get(i) <= 0 || funnel.get(i - 1) <= 0) { 97 | result.add(0.0); 98 | } else { 99 | // No 0's, calculate ratio 100 | result.add((double) funnel.get(i) / funnel.get(i - 1)); 101 | } 102 | } 103 | 104 | return result; 105 | } 106 | 107 | @Override 108 | public String getDisplayString(String[] children) { 109 | return "Converts absolute count funnel to conversion rates."; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/yahoo/hive/udf/funnel/Fallout.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | import org.apache.commons.logging.Log; 22 | import org.apache.commons.logging.LogFactory; 23 | import org.apache.hadoop.hive.ql.exec.Description; 24 | import org.apache.hadoop.hive.ql.exec.UDFArgumentException; 25 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 26 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 27 | import org.apache.hadoop.hive.ql.metadata.HiveException; 28 | import org.apache.hadoop.hive.ql.udf.UDFType; 29 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; 30 | import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; 31 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 32 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 33 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; 34 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 35 | 36 | @UDFType(deterministic = true) 37 | @Description(name = "fallout", 38 | value = "fallout(funnel) - Converts a funnel from raw counts to fallout rates.", 39 | extended = "Converts absolute count funnel to fallout rates.") 40 | public class Fallout extends GenericUDF { 41 | static final Log LOG = LogFactory.getLog(Fallout.class.getName()); 42 | 43 | private ListObjectInspector listInputObjectInspector; 44 | 45 | @Override 46 | public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { 47 | if (arguments.length != 1) { 48 | throw new UDFArgumentLengthException("The operator 'fallout' accepts 1 argument."); 49 | } 50 | 51 | // Check that the argument is a list type 52 | if (arguments[0].getCategory() != ObjectInspector.Category.LIST) { 53 | throw new UDFArgumentTypeException(1, "Only list type arguments are accepted, but " + arguments[0].getTypeName() + " was passed."); 54 | } 55 | 56 | // Check that the list is of type long 57 | // May want to add support for int/double/float later 58 | switch (((PrimitiveObjectInspector) ((ListObjectInspector) arguments[0]).getListElementObjectInspector()).getPrimitiveCategory()) { 59 | case LONG: 60 | break; 61 | default: 62 | throw new UDFArgumentTypeException(1, "A long array argument should be passed, but " + arguments[0].getTypeName() + " was passed instead."); 63 | } 64 | 65 | // Get the list object inspector 66 | listInputObjectInspector = (ListObjectInspector) arguments[0]; 67 | 68 | // This UDF will return a list of doubles 69 | return ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaDoubleObjectInspector); 70 | } 71 | 72 | @Override 73 | public Object evaluate(DeferredObject[] args) throws HiveException { 74 | // Check that we only have one argument 75 | if (args.length != 1) { 76 | return null; 77 | } 78 | 79 | // Get the deferred object into a list 80 | List funnel = (List) listInputObjectInspector.getList(args[0].get()); 81 | 82 | // Stores our return list 83 | List result = new ArrayList<>(); 84 | 85 | // If funnel is empty, return 86 | if (funnel.size() <= 0) { 87 | return result; 88 | } 89 | 90 | // First element is always 0% 91 | result.add(0.0); 92 | 93 | // Starting from the second element, calculate fallout rate 94 | for (int i = 1; i < funnel.size(); i++) { 95 | // Check for 0's 96 | if (funnel.get(i) <= 0 || funnel.get(i - 1) <= 0) { 97 | result.add(0.0); 98 | } else { 99 | // No 0's, calculate ratio 100 | result.add(1 - ((double) funnel.get(i) / funnel.get(i - 1))); 101 | } 102 | } 103 | 104 | return result; 105 | } 106 | 107 | @Override 108 | public String getDisplayString(String[] children) { 109 | return "Converts absolute count funnel to fallout rates."; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/yahoo/hive/udf/funnel/Funnel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.Arrays; 20 | import java.util.HashSet; 21 | import java.util.List; 22 | import java.util.stream.Collectors; 23 | import org.apache.commons.logging.Log; 24 | import org.apache.commons.logging.LogFactory; 25 | import org.apache.hadoop.hive.ql.exec.Description; 26 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 27 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 28 | import org.apache.hadoop.hive.ql.metadata.HiveException; 29 | import org.apache.hadoop.hive.ql.parse.SemanticException; 30 | import org.apache.hadoop.hive.ql.udf.UDFType; 31 | import org.apache.hadoop.hive.ql.udf.generic.AbstractGenericUDAFResolver; 32 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator; 33 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFParameterInfo; 34 | import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; 35 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 36 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 37 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; 38 | import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; 39 | import org.apache.hadoop.hive.serde2.objectinspector.StandardStructObjectInspector; 40 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 41 | import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo; 42 | import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; 43 | import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; 44 | 45 | @UDFType(deterministic = true) 46 | @Description(name = "funnel", 47 | value = "_FUNC_(action_column, timestamp_column, step_1, step_2, ...) - Builds a funnel report applied to the action_column. Steps are arrays of the same type as action. Should be used with merge_funnel UDF.", 48 | extended = "Example: SELECT funnel(action, timestamp, array('signup_page', 'email_signup'), \n" + 49 | " array('confirm_button'),\n" + 50 | " array('submit_button')) AS funnel\n" + 51 | " FROM table\n" + 52 | " GROUP BY user_id;") 53 | public class Funnel extends AbstractGenericUDAFResolver { 54 | static final Log LOG = LogFactory.getLog(Funnel.class.getName()); 55 | 56 | @Override 57 | public FunnelEvaluator getEvaluator(GenericUDAFParameterInfo info) throws SemanticException { 58 | // Get the parameters 59 | TypeInfo [] parameters = info.getParameters(); 60 | 61 | // Check number of arguments 62 | if (parameters.length < 3) { 63 | throw new UDFArgumentLengthException("Please specify the action column, the timestamp column, and at least one funnel."); 64 | } 65 | 66 | // Check the action_column type and enforce that all funnel steps are the same type 67 | if (parameters[0].getCategory() != ObjectInspector.Category.PRIMITIVE) { 68 | throw new UDFArgumentTypeException(0, "Only primitive type arguments are accepted but " + parameters[0].getTypeName() + " was passed."); 69 | } 70 | PrimitiveCategory actionColumnCategory = ((PrimitiveTypeInfo) parameters[0]).getPrimitiveCategory(); 71 | 72 | // Check the timestamp_column type 73 | if (parameters[1].getCategory() != ObjectInspector.Category.PRIMITIVE) { 74 | throw new UDFArgumentTypeException(1, "Only primitive type arguments are accepted but " + parameters[0].getTypeName() + " was passed."); 75 | } 76 | 77 | // Check that all funnel steps are the same type as the action_column 78 | for (int i = 2; i < parameters.length; i++) { 79 | switch (parameters[i].getCategory()) { 80 | case LIST: 81 | // Check that the list is of primitives of the same type as the action column 82 | TypeInfo typeInfo = ((ListTypeInfo) parameters[i]).getListElementTypeInfo(); 83 | if (typeInfo.getCategory() != ObjectInspector.Category.PRIMITIVE || ((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory() != actionColumnCategory) { 84 | throw new UDFArgumentTypeException(i, "Funnel list parameter " + Integer.toString(i) + " of type " + parameters[i].getTypeName() + " does not match expected type " + parameters[0].getTypeName() + "."); 85 | } 86 | break; 87 | default: 88 | throw new UDFArgumentTypeException(i, "Funnel list parameter " + Integer.toString(i) + " of type " + parameters[i].getTypeName() + " should be a list."); 89 | } 90 | } 91 | 92 | return new FunnelEvaluator(); 93 | } 94 | 95 | public static class FunnelEvaluator extends GenericUDAFEvaluator { 96 | /** For PARTIAL1 and COMPLETE. */ 97 | private ObjectInspector actionObjectInspector; 98 | 99 | /** For PARTIAL1 and COMPLETE. */ 100 | private ObjectInspector timestampObjectInspector; 101 | 102 | /** For PARTIAL1 and COMPLETE. */ 103 | private ListObjectInspector funnelObjectInspector; 104 | 105 | /** For PARTIAL2 and FINAL. */ 106 | private StandardStructObjectInspector internalMergeObjectInspector; 107 | 108 | /** Action key constant. */ 109 | private static final String ACTION = "action"; 110 | 111 | /** Timestamp key constant. */ 112 | private static final String TIMESTAMP = "timestamp"; 113 | 114 | /** Funnel key constant. */ 115 | private static final String FUNNEL = "funnel"; 116 | 117 | @Override 118 | public ObjectInspector init(Mode m, ObjectInspector[] parameters) throws HiveException { 119 | super.init(m, parameters); 120 | 121 | // Setup the object inspectors and return type 122 | switch (m) { 123 | case PARTIAL1: 124 | // Get the object inspectors 125 | actionObjectInspector = parameters[0]; 126 | timestampObjectInspector = parameters[1]; 127 | funnelObjectInspector = (ListObjectInspector) parameters[2]; 128 | 129 | // The field names for the struct, order matters 130 | List fieldNames = Arrays.asList(ACTION, TIMESTAMP, FUNNEL); 131 | 132 | // The field inspectors for the struct, order matters 133 | List fieldInspectors = Arrays.asList(actionObjectInspector, timestampObjectInspector, actionObjectInspector) 134 | .stream() 135 | .map(ObjectInspectorUtils::getStandardObjectInspector) 136 | .map(ObjectInspectorFactory::getStandardListObjectInspector) 137 | .collect(Collectors.toList()); 138 | 139 | // Will output structs 140 | return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldInspectors); 141 | case PARTIAL2: 142 | // Get the struct object inspector 143 | internalMergeObjectInspector = (StandardStructObjectInspector) parameters[0]; 144 | 145 | // Will output structs 146 | return internalMergeObjectInspector; 147 | case FINAL: 148 | // Get the struct object inspector 149 | internalMergeObjectInspector = (StandardStructObjectInspector) parameters[0]; 150 | 151 | // Will output list of longs 152 | return ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector); 153 | case COMPLETE: 154 | // Get the object inspectors 155 | actionObjectInspector = parameters[0]; 156 | timestampObjectInspector = parameters[1]; 157 | funnelObjectInspector = (ListObjectInspector) parameters[2]; 158 | 159 | // Will output list of longs 160 | return ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector); 161 | default: 162 | throw new HiveException("Unknown Mode: " + m.toString()); 163 | } 164 | } 165 | 166 | @Override 167 | public AggregationBuffer getNewAggregationBuffer() throws HiveException { 168 | return new FunnelAggregateBuffer(); 169 | } 170 | 171 | 172 | /** 173 | * Adds funnel steps to the aggregate. Funnel steps can be lists or 174 | * scalars. 175 | * 176 | * @param funnelAggregate 177 | * @param parameters 178 | */ 179 | private void addFunnelSteps(FunnelAggregateBuffer funnelAggregate, Object[] parameters) { 180 | Arrays.stream(parameters) 181 | .map(this::convertFunnelStepObjectToList) 182 | .map(ListUtils::removeNullFromList) 183 | .filter(ListUtils::isNotEmpty) 184 | .forEach(funnelStep -> { 185 | funnelAggregate.funnelSteps.add(new HashSet(funnelStep)); 186 | funnelAggregate.funnelSet.addAll(funnelStep); 187 | }); 188 | } 189 | 190 | @Override 191 | public void iterate(AggregationBuffer aggregate, Object[] parameters) throws HiveException { 192 | FunnelAggregateBuffer funnelAggregate = (FunnelAggregateBuffer) aggregate; 193 | 194 | // Add the funnel steps if not already stored 195 | if (funnelAggregate.funnelSteps.isEmpty()) { 196 | // Funnel steps start at index 2 197 | addFunnelSteps(funnelAggregate, Arrays.copyOfRange(parameters, 2, parameters.length)); 198 | } 199 | 200 | // Get the action_column value and add it (if it matches a funnel) 201 | Object action = parameters[0]; 202 | Object timestamp = parameters[1]; 203 | if (action != null && timestamp != null) { 204 | // Get the action value 205 | Object actionValue = ObjectInspectorUtils.copyToStandardObject(action, actionObjectInspector); 206 | // Get the timestamp value 207 | Object timestampValue = ObjectInspectorUtils.copyToStandardObject(timestamp, timestampObjectInspector); 208 | 209 | // If the action is not null and it is one of the funnels we are looking for, keep it 210 | if (actionValue != null && timestampValue != null && funnelAggregate.funnelSet.contains(actionValue)) { 211 | funnelAggregate.actions.add(actionValue); 212 | funnelAggregate.timestamps.add(timestampValue); 213 | } 214 | } 215 | } 216 | 217 | /** 218 | * Given a struct and a key, look the key up in the struct with the 219 | * merge object inspector. 220 | * 221 | * @param object Struct object 222 | * @param key Key to look up 223 | */ 224 | private Object structLookup(Object object, String key) { 225 | return internalMergeObjectInspector.getStructFieldData(object, internalMergeObjectInspector.getStructFieldRef(key)); 226 | } 227 | 228 | @Override 229 | public void merge(AggregationBuffer aggregate, Object partial) throws HiveException { 230 | FunnelAggregateBuffer funnelAggregate = (FunnelAggregateBuffer) aggregate; 231 | 232 | // Lists for partial data 233 | List partialActionList = ListUtils.toList(structLookup(partial, ACTION)); 234 | List partialTimestampList = ListUtils.toList(structLookup(partial, TIMESTAMP)); 235 | 236 | // If we don't have any funnel steps stored, then we should copy the funnel steps from the partial list 237 | if (funnelAggregate.funnelSteps.isEmpty()) { 238 | List partialFunnelList = ListUtils.toList(structLookup(partial, FUNNEL)); 239 | funnelAggregate.deserializeFunnel(partialFunnelList); 240 | } 241 | 242 | // Add all the partial actions and timestamps to the end of the lists 243 | funnelAggregate.actions.addAll(partialActionList); 244 | funnelAggregate.timestamps.addAll(partialTimestampList); 245 | } 246 | 247 | @Override 248 | public void reset(AggregationBuffer aggregate) throws HiveException { 249 | FunnelAggregateBuffer funnelAggregate = (FunnelAggregateBuffer) aggregate; 250 | funnelAggregate.clear(); 251 | } 252 | 253 | 254 | @Override 255 | public Object terminate(AggregationBuffer aggregate) throws HiveException { 256 | FunnelAggregateBuffer funnelAggregate = (FunnelAggregateBuffer) aggregate; 257 | return funnelAggregate.computeFunnel(); 258 | } 259 | 260 | @Override 261 | public Object terminatePartial(AggregationBuffer aggregate) throws HiveException { 262 | FunnelAggregateBuffer funnelAggregate = (FunnelAggregateBuffer) aggregate; 263 | return funnelAggregate.serialize(); 264 | } 265 | 266 | /** 267 | * Convert object to list of funnels for a funnel step. 268 | * 269 | * @parameter 270 | * @return List of funnels in funnel step 271 | */ 272 | private List convertFunnelStepObjectToList(Object parameter) { 273 | if (parameter instanceof List) { 274 | return (List) funnelObjectInspector.getList(parameter); 275 | } else { 276 | return Arrays.asList(ObjectInspectorUtils.copyToStandardObject(parameter, funnelObjectInspector.getListElementObjectInspector())); 277 | } 278 | } 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /src/main/java/com/yahoo/hive/udf/funnel/FunnelAggregateBuffer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.ArrayList; 20 | import java.util.Collections; 21 | import java.util.HashSet; 22 | import java.util.List; 23 | import java.util.Set; 24 | import java.util.stream.IntStream; 25 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AggregationBuffer; 26 | 27 | /** 28 | * Used to build funnel. 29 | */ 30 | class FunnelAggregateBuffer implements AggregationBuffer { 31 | /** List of actions. */ 32 | List actions = new ArrayList<>(); 33 | 34 | /** List of timestamps associated with actions. */ 35 | List timestamps = new ArrayList<>(); 36 | 37 | /** List of funnel steps. Funnel steps can have multiple funnels. */ 38 | List> funnelSteps = new ArrayList>(); 39 | 40 | /** Set of all funnels we are looking for. */ 41 | Set funnelSet = new HashSet<>(); 42 | 43 | /** 44 | * Serialize actions, timestamps, and funnel steps. Have to split funnel 45 | * steps with null. This is more efficient than passing around structs. 46 | * 47 | * @return List of objects 48 | */ 49 | public List serialize() { 50 | List serialized = new ArrayList<>(); 51 | serialized.add(actions); 52 | serialized.add(timestamps); 53 | // Need to do special logic for funnel steps 54 | List serializedFunnelSteps = new ArrayList<>(); 55 | for (Set e : funnelSteps) { 56 | // Separate funnel steps with null 57 | serializedFunnelSteps.addAll(e); 58 | serializedFunnelSteps.add(null); 59 | } 60 | // Add the funnel steps 61 | serialized.add(serializedFunnelSteps); 62 | return serialized; 63 | } 64 | 65 | /** 66 | * Deserialize funnel steps. Have to deserialize the null separated list. 67 | */ 68 | public void deserializeFunnel(List serializedFunnel) { 69 | // Have to "deserialize" from the null separated list 70 | Set funnelStepAccumulator = new HashSet<>(); 71 | for (Object e : serializedFunnel) { 72 | // If not null 73 | if (e != null) { 74 | // Add to the step accumulator 75 | funnelStepAccumulator.add(e); 76 | } else { 77 | // Found a null, add the funnel step 78 | // Need to do a deep copy 79 | funnelSteps.add(new HashSet<>(funnelStepAccumulator)); 80 | // Clear the set 81 | funnelStepAccumulator.clear(); 82 | } 83 | } 84 | } 85 | 86 | /** 87 | * Clear the aggregate. 88 | */ 89 | public void clear() { 90 | actions.clear(); 91 | timestamps.clear(); 92 | } 93 | 94 | /** 95 | * Compute the funnel. Sort the actions by timestamp/action, then build the 96 | * funnel. 97 | * 98 | * @return list of longs representing the funnel 99 | */ 100 | public List computeFunnel() { 101 | // Create index, sort on timestamp/action 102 | Integer[] sortedIndex = IntStream.rangeClosed(0, actions.size() - 1) 103 | .boxed() 104 | .sorted(this::funnelAggregateComparator) 105 | .toArray(Integer[]::new); 106 | 107 | // Input size 108 | int inputSize = actions.size(); 109 | 110 | // Stores the current index we are at for the funnel 111 | int currentFunnelStep = 0; 112 | 113 | // The last funnel index 114 | int funnelStepSize = funnelSteps.size(); 115 | 116 | // Result funnel, all 0's at the start 117 | List results = new ArrayList<>(Collections.nCopies(funnelStepSize, 0L)); 118 | 119 | // Check every sorted action until we reach the end of the funnel 120 | for (int i = 0; i < inputSize && currentFunnelStep < funnelStepSize; i++) { 121 | // Check if the current action is in the current funnel step 122 | if (funnelSteps.get(currentFunnelStep).contains(actions.get(sortedIndex[i]))) { 123 | // We have a match, output 1 for this funnel step 124 | results.set(currentFunnelStep, 1L); 125 | // Move to the next funnel step 126 | currentFunnelStep++; 127 | } 128 | } 129 | 130 | return results; 131 | } 132 | 133 | /** 134 | * Used for sorting array of integers according to funnel aggregate 135 | * timestamp/action columns. If timestamps match, uses action column. 136 | * 137 | * @param i1 138 | * @param i2 139 | * @param funnelAggregate 140 | * @return ordering of i1 and i2 141 | */ 142 | private int funnelAggregateComparator(Integer i1, Integer i2) { 143 | int result = ((Comparable) timestamps.get(i1)).compareTo(timestamps.get(i2)); 144 | // Match in timestamp, sort on action 145 | if (result == 0) { 146 | return ((Comparable) actions.get(i1)).compareTo(actions.get(i2)); 147 | } 148 | return result; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/com/yahoo/hive/udf/funnel/ListUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.List; 20 | import java.util.Objects; 21 | import java.util.stream.Collectors; 22 | import org.apache.hadoop.hive.serde2.lazybinary.LazyBinaryArray; 23 | 24 | public class ListUtils { 25 | /** 26 | * Returns true if list if not empty. 27 | * 28 | * @param list 29 | * @return True if list not empty 30 | */ 31 | public static boolean isNotEmpty(List list) { 32 | return !list.isEmpty(); 33 | } 34 | 35 | /** 36 | * Removes null values from list. 37 | * 38 | * @param list 39 | * @return List without null values 40 | */ 41 | public static List removeNullFromList(List list) { 42 | return list.stream() 43 | .filter(Objects::nonNull) 44 | .collect(Collectors.toList()); 45 | } 46 | 47 | /** 48 | * Cast an object to a list. Checks if it is a LazyBinaryArray or a 49 | * regular list. 50 | * 51 | * @param object Input object to try and cast to a list. 52 | * @return List of objects. 53 | */ 54 | public static List toList(Object object) { 55 | List result; 56 | if (object instanceof LazyBinaryArray) { 57 | result = ((LazyBinaryArray) object).getList(); 58 | } else { 59 | result = (List) object; 60 | } 61 | return result; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/yahoo/hive/udf/funnel/Merge.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.List; 20 | import java.util.stream.Collectors; 21 | import org.apache.commons.logging.Log; 22 | import org.apache.commons.logging.LogFactory; 23 | import org.apache.hadoop.hive.ql.exec.Description; 24 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 25 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 26 | import org.apache.hadoop.hive.ql.metadata.HiveException; 27 | import org.apache.hadoop.hive.ql.parse.SemanticException; 28 | import org.apache.hadoop.hive.ql.udf.UDFType; 29 | import org.apache.hadoop.hive.ql.udf.generic.AbstractGenericUDAFResolver; 30 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator; 31 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFParameterInfo; 32 | import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector; 33 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 34 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 35 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.LongObjectInspector; 36 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 37 | import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo; 38 | import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; 39 | import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; 40 | 41 | @UDFType(deterministic = true) 42 | @Description(name = "merge_funnel", 43 | value = "_FUNC_(funnel_column) - Merges funnels. Use with funnel UDF.", 44 | extended = "Example: SELECT merge_funnel(funnel)\n" + 45 | " FROM (SELECT funnel(action, timestamp, array('signup_page', 'email_signup'), \n" + 46 | " array('confirm_button'),\n" + 47 | " array('submit_button')) AS funnel\n" + 48 | " FROM table\n" + 49 | " GROUP BY user_id) t;") 50 | public class Merge extends AbstractGenericUDAFResolver { 51 | static final Log LOG = LogFactory.getLog(Merge.class.getName()); 52 | 53 | @Override 54 | public MergeEvaluator getEvaluator(GenericUDAFParameterInfo info) throws SemanticException { 55 | // Get the parameters 56 | TypeInfo [] parameters = info.getParameters(); 57 | 58 | // Check number of arguments 59 | if (parameters.length != 1) { 60 | throw new UDFArgumentLengthException("Please specify the funnel column."); 61 | } 62 | 63 | // Check if the parameter is not a list 64 | if (parameters[0].getCategory() != ObjectInspector.Category.LIST) { 65 | throw new UDFArgumentTypeException(0, "Only list type arguments are accepted but " + parameters[0].getTypeName() + " was passed as the first parameter."); 66 | } 67 | 68 | // Check that the list is an array of primitives 69 | if (((ListTypeInfo) parameters[0]).getListElementTypeInfo().getCategory() != ObjectInspector.Category.PRIMITIVE) { 70 | throw new UDFArgumentTypeException(0, "A long array argument should be passed, but " + parameters[0].getTypeName() + " was passed instead."); 71 | } 72 | 73 | // Check that the list is of type long 74 | // May want to add support for int/double/float later 75 | switch (((PrimitiveTypeInfo) ((ListTypeInfo) parameters[0]).getListElementTypeInfo()).getPrimitiveCategory()) { 76 | case LONG: 77 | break; 78 | default: 79 | throw new UDFArgumentTypeException(0, "A long array argument should be passed, but " + parameters[0].getTypeName() + " was passed instead."); 80 | } 81 | 82 | return new MergeEvaluator(); 83 | } 84 | 85 | public static class MergeEvaluator extends GenericUDAFEvaluator { 86 | /** Input list object inspector. Used during iterate. */ 87 | private ListObjectInspector listObjectInspector; 88 | 89 | /** Long object inspector. Used during merge. */ 90 | private LongObjectInspector longObjectInspector; 91 | 92 | @Override 93 | public ObjectInspector init(Mode mode, ObjectInspector[] parameters) throws HiveException { 94 | super.init(mode, parameters); 95 | 96 | // Setup the list and element object inspectors. 97 | listObjectInspector = (ListObjectInspector) parameters[0]; 98 | longObjectInspector = (LongObjectInspector) listObjectInspector.getListElementObjectInspector(); 99 | 100 | // Will return a list of longs 101 | return ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector); 102 | } 103 | 104 | @Override 105 | public AggregationBuffer getNewAggregationBuffer() throws HiveException { 106 | return new MergeAggregateBuffer(); 107 | } 108 | 109 | @Override 110 | public void iterate(AggregationBuffer aggregate, Object[] parameters) throws HiveException { 111 | Object parameter = parameters[0]; 112 | // If not null 113 | if (parameter != null) { 114 | // Get the funnel aggregate and the funnel data 115 | MergeAggregateBuffer funnelAggregate = (MergeAggregateBuffer) aggregate; 116 | List funnel = (List) listObjectInspector.getList(parameter); 117 | 118 | // Add the funnel to the funnel aggregate 119 | funnelAggregate.addFunnel(funnel); 120 | } 121 | } 122 | 123 | @Override 124 | public void merge(AggregationBuffer aggregate, Object partial) throws HiveException { 125 | if (partial != null) { 126 | 127 | // Get the funnel aggregate and the funnel data 128 | MergeAggregateBuffer funnelAggregate = (MergeAggregateBuffer) aggregate; 129 | 130 | // Convert the partial results into a list of longs 131 | List funnel = listObjectInspector.getList(partial) 132 | .stream() 133 | .map(longObjectInspector::get) 134 | .collect(Collectors.toList()); 135 | 136 | // Add the funnel to the funnel aggregate 137 | funnelAggregate.addFunnel(funnel); 138 | } 139 | } 140 | 141 | @Override 142 | public void reset(AggregationBuffer aggregate) throws HiveException { 143 | MergeAggregateBuffer funnelAggregate = (MergeAggregateBuffer) aggregate; 144 | funnelAggregate.clear(); 145 | } 146 | 147 | @Override 148 | public Object terminate(AggregationBuffer aggregate) throws HiveException { 149 | MergeAggregateBuffer funnelAggregate = (MergeAggregateBuffer) aggregate; 150 | return funnelAggregate.output(); 151 | } 152 | 153 | @Override 154 | public Object terminatePartial(AggregationBuffer aggregate) throws HiveException { 155 | MergeAggregateBuffer funnelAggregate = (MergeAggregateBuffer) aggregate; 156 | return funnelAggregate.output(); 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/main/java/com/yahoo/hive/udf/funnel/MergeAggregateBuffer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 22 | import org.apache.hadoop.hive.ql.metadata.HiveException; 23 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AggregationBuffer; 24 | 25 | /** 26 | * Merges funnels into an aggregate. 27 | */ 28 | class MergeAggregateBuffer implements AggregationBuffer { 29 | /** Stores funnel aggregate. */ 30 | List elements = new ArrayList<>(); 31 | 32 | /** 33 | * Add a funnel to the aggregate. 34 | * 35 | * @param funnel Funnel in the form of a list of longs. 36 | */ 37 | public void addFunnel(List funnel) throws HiveException { 38 | // If empty, just copy elements 39 | if (elements.isEmpty()) { 40 | elements.addAll(funnel); 41 | } else { 42 | // If the sizes don't match, throw an exception 43 | if (elements.size() != funnel.size()) { 44 | throw new UDFArgumentTypeException(0, "Funnels must be of the same size to merge!"); 45 | } 46 | // Not empty, merge with existing list 47 | for (int i = 0; i < funnel.size(); i++) { 48 | elements.set(i, (funnel.get(i) + elements.get(i))); 49 | } 50 | } 51 | } 52 | 53 | /** 54 | * Clear the aggregate. 55 | */ 56 | public void clear() { 57 | elements.clear(); 58 | } 59 | 60 | /** 61 | * Output aggregate. Must do a deep copy, and return a new list. 62 | * 63 | * @return Funnel aggregate counts. 64 | */ 65 | public List output() { 66 | List values = new ArrayList(elements.size()); 67 | values.addAll(elements); 68 | return values; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/resources/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | -------------------------------------------------------------------------------- /src/test/java/com/yahoo/hive/udf/funnel/ConversionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.Arrays; 20 | import java.util.List; 21 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 22 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 23 | import org.apache.hadoop.hive.ql.metadata.HiveException; 24 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF.DeferredObject; 25 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 26 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 27 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 28 | import org.junit.Assert; 29 | import org.junit.Test; 30 | import static org.mockito.Mockito.mock; 31 | import static org.mockito.Mockito.when; 32 | 33 | /** 34 | * Unit test for Conversion. 35 | */ 36 | public class ConversionTest { 37 | @Test(expected = UDFArgumentLengthException.class) 38 | public void testTooManyInputs() throws HiveException { 39 | Conversion udf = new Conversion(); 40 | 41 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 42 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector), 43 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 44 | }; 45 | 46 | udf.initialize(inputOiList); 47 | } 48 | 49 | @Test(expected = UDFArgumentTypeException.class) 50 | public void testBadInputType() throws HiveException { 51 | Conversion udf = new Conversion(); 52 | 53 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 54 | PrimitiveObjectInspectorFactory.javaLongObjectInspector 55 | }; 56 | 57 | udf.initialize(inputOiList); 58 | } 59 | 60 | @Test 61 | public void testConvertToConversion() throws HiveException { 62 | Conversion udf = new Conversion(); 63 | 64 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 65 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 66 | }; 67 | 68 | udf.initialize(inputOiList); 69 | 70 | List inputList = Arrays.asList(10L, 5L, 1L); 71 | 72 | DeferredObject obj1 = mock(DeferredObject.class); 73 | DeferredObject[] objs = new DeferredObject[] { obj1 }; 74 | when(obj1.get()).thenReturn(inputList); 75 | 76 | Assert.assertEquals(Arrays.asList(1.0, 0.5, 0.2), udf.evaluate(objs)); 77 | } 78 | 79 | @Test 80 | public void testIncorrectNumberOfArgs() throws HiveException { 81 | Conversion udf = new Conversion(); 82 | 83 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 84 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 85 | }; 86 | 87 | udf.initialize(inputOiList); 88 | 89 | List inputList = Arrays.asList(10L); 90 | 91 | DeferredObject obj1 = mock(DeferredObject.class); 92 | DeferredObject[] objs = new DeferredObject[] { obj1, obj1 }; 93 | 94 | when(obj1.get()).thenReturn(inputList); 95 | 96 | Assert.assertEquals(null, udf.evaluate(objs)); 97 | } 98 | 99 | @Test 100 | public void testEmptyFunnel() throws HiveException { 101 | Conversion udf = new Conversion(); 102 | 103 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 104 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 105 | }; 106 | 107 | udf.initialize(inputOiList); 108 | 109 | List inputList = Arrays.asList(); 110 | 111 | DeferredObject obj1 = mock(DeferredObject.class); 112 | DeferredObject[] objs = new DeferredObject[] { obj1 }; 113 | when(obj1.get()).thenReturn(inputList); 114 | 115 | Assert.assertEquals(Arrays.asList(), udf.evaluate(objs)); 116 | } 117 | 118 | @Test 119 | public void testConvertToConversionWithZeros() throws HiveException { 120 | Conversion udf = new Conversion(); 121 | 122 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 123 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 124 | }; 125 | 126 | udf.initialize(inputOiList); 127 | 128 | List inputList = Arrays.asList(10L, 5L, 0L, 0L, 0L); 129 | 130 | DeferredObject obj1 = mock(DeferredObject.class); 131 | DeferredObject[] objs = new DeferredObject[] { obj1 }; 132 | when(obj1.get()).thenReturn(inputList); 133 | 134 | Assert.assertEquals(Arrays.asList(1.0, 0.5, 0.0, 0.0, 0.0), udf.evaluate(objs)); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/test/java/com/yahoo/hive/udf/funnel/FalloutTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.Arrays; 20 | import java.util.List; 21 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 22 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 23 | import org.apache.hadoop.hive.ql.metadata.HiveException; 24 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDF.DeferredObject; 25 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 26 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 27 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 28 | import org.junit.Assert; 29 | import org.junit.Test; 30 | import static org.mockito.Mockito.mock; 31 | import static org.mockito.Mockito.when; 32 | 33 | /** 34 | * Unit test for Fallout. 35 | */ 36 | public class FalloutTest { 37 | @Test(expected = UDFArgumentLengthException.class) 38 | public void testTooManyInputs() throws HiveException { 39 | Fallout udf = new Fallout(); 40 | 41 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 42 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector), 43 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 44 | }; 45 | 46 | udf.initialize(inputOiList); 47 | } 48 | 49 | @Test(expected = UDFArgumentTypeException.class) 50 | public void testBadInputType() throws HiveException { 51 | Fallout udf = new Fallout(); 52 | 53 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 54 | PrimitiveObjectInspectorFactory.javaLongObjectInspector 55 | }; 56 | 57 | udf.initialize(inputOiList); 58 | } 59 | 60 | @Test 61 | public void testConvertToFallout() throws HiveException { 62 | Fallout udf = new Fallout(); 63 | 64 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 65 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 66 | }; 67 | 68 | udf.initialize(inputOiList); 69 | 70 | List inputList = Arrays.asList(10L, 5L, 1L); 71 | 72 | DeferredObject obj1 = mock(DeferredObject.class); 73 | DeferredObject[] objs = new DeferredObject[] { obj1 }; 74 | when(obj1.get()).thenReturn(inputList); 75 | 76 | Assert.assertEquals(Arrays.asList(0.0, 0.5, 0.8), udf.evaluate(objs)); 77 | } 78 | 79 | @Test 80 | public void testIncorrectNumberOfArgs() throws HiveException { 81 | Fallout udf = new Fallout(); 82 | 83 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 84 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 85 | }; 86 | 87 | udf.initialize(inputOiList); 88 | 89 | List inputList = Arrays.asList(10L); 90 | 91 | DeferredObject obj1 = mock(DeferredObject.class); 92 | DeferredObject[] objs = new DeferredObject[] { obj1, obj1 }; 93 | 94 | when(obj1.get()).thenReturn(inputList); 95 | 96 | Assert.assertEquals(null, udf.evaluate(objs)); 97 | } 98 | 99 | @Test 100 | public void testEmptyFunnel() throws HiveException { 101 | Fallout udf = new Fallout(); 102 | 103 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 104 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 105 | }; 106 | 107 | udf.initialize(inputOiList); 108 | 109 | List inputList = Arrays.asList(); 110 | 111 | DeferredObject obj1 = mock(DeferredObject.class); 112 | DeferredObject[] objs = new DeferredObject[] { obj1 }; 113 | when(obj1.get()).thenReturn(inputList); 114 | 115 | Assert.assertEquals(Arrays.asList(), udf.evaluate(objs)); 116 | } 117 | 118 | @Test 119 | public void testConvertToFalloutWithZeros() throws HiveException { 120 | Fallout udf = new Fallout(); 121 | 122 | ObjectInspector[] inputOiList = new ObjectInspector[]{ 123 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 124 | }; 125 | 126 | udf.initialize(inputOiList); 127 | 128 | List inputList = Arrays.asList(10L, 5L, 0L, 0L, 0L); 129 | 130 | DeferredObject obj1 = mock(DeferredObject.class); 131 | DeferredObject[] objs = new DeferredObject[] { obj1 }; 132 | when(obj1.get()).thenReturn(inputList); 133 | 134 | Assert.assertEquals(Arrays.asList(0.0, 0.5, 0.0, 0.0, 0.0), udf.evaluate(objs)); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/test/java/com/yahoo/hive/udf/funnel/FunnelTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.ArrayList; 20 | import java.util.Arrays; 21 | import java.util.List; 22 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 23 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 24 | import org.apache.hadoop.hive.ql.metadata.HiveException; 25 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AggregationBuffer; 26 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.Mode; 27 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator; 28 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFParameterInfo; 29 | import org.apache.hadoop.hive.ql.udf.generic.SimpleGenericUDAFParameterInfo; 30 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 31 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 32 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 33 | import org.junit.Assert; 34 | import org.junit.Test; 35 | 36 | public class FunnelTest { 37 | @Test(expected = UDFArgumentLengthException.class) 38 | public void testInvalidNumberOfParams() throws HiveException { 39 | Funnel udaf = new Funnel(); 40 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 41 | PrimitiveObjectInspectorFactory.javaLongObjectInspector 42 | }; 43 | 44 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 45 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 46 | } 47 | 48 | @Test(expected = UDFArgumentTypeException.class) 49 | public void testComplexParamPosition1() throws HiveException { 50 | Funnel udaf = new Funnel(); 51 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 52 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector), 53 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 54 | PrimitiveObjectInspectorFactory.javaStringObjectInspector 55 | }; 56 | 57 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 58 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 59 | } 60 | 61 | @Test(expected = UDFArgumentTypeException.class) 62 | public void testComplexParamPosition2() throws HiveException { 63 | Funnel udaf = new Funnel(); 64 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 65 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 66 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector), 67 | PrimitiveObjectInspectorFactory.javaStringObjectInspector 68 | }; 69 | 70 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 71 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 72 | } 73 | 74 | @Test(expected = UDFArgumentTypeException.class) 75 | public void testNonmatchingParamPosition4() throws HiveException { 76 | Funnel udaf = new Funnel(); 77 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 78 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 79 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 80 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 81 | PrimitiveObjectInspectorFactory.javaLongObjectInspector 82 | }; 83 | 84 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 85 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 86 | } 87 | 88 | @Test(expected = UDFArgumentTypeException.class) 89 | public void testComplexParamPosition4() throws HiveException { 90 | Funnel udaf = new Funnel(); 91 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 92 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 93 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 94 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 95 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 96 | }; 97 | 98 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 99 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 100 | } 101 | 102 | @Test(expected = UDFArgumentTypeException.class) 103 | public void testComplexValueInFunnelList() throws HiveException { 104 | Funnel udaf = new Funnel(); 105 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 106 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 107 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 108 | ObjectInspectorFactory.getStandardListObjectInspector(ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector)), 109 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector) 110 | }; 111 | 112 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 113 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 114 | } 115 | 116 | @Test(expected = UDFArgumentTypeException.class) 117 | public void testFunnelListValueNotMatchingWithActionColumn() throws HiveException { 118 | Funnel udaf = new Funnel(); 119 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 120 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 121 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, 122 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector), 123 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 124 | }; 125 | 126 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 127 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 128 | } 129 | 130 | @Test 131 | public void testComplete() throws HiveException { 132 | Funnel udaf = new Funnel(); 133 | 134 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 135 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, // action_column 136 | PrimitiveObjectInspectorFactory.javaLongObjectInspector, // timestamp_column 137 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector), // funnel_step_1 138 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector) // funnel_step_1 139 | }; 140 | 141 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 142 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 143 | 144 | ObjectInspector outputObjectInspector = udafEvaluator.init(Mode.COMPLETE, inputObjectInspectorList); 145 | 146 | // Order will be "alpha, beta, gamma, delta" when ordered on timestamp_column 147 | // Funnel is "beta" -> "gamma" -> "epsilon" 148 | // Should return [1, 1, 0] as we don't have an epsilon 149 | Object[] parameters1 = new Object[]{ "beta", 200L, new ArrayList(), Arrays.asList("beta", "BAD"), null, "gamma", Arrays.asList("epsilon")}; // Test empty list funnel step, and null in funnel step 150 | Object[] parameters2 = new Object[]{"alpha", 100L, Arrays.asList("beta", "BAD"), "gamma", Arrays.asList("epsilon")}; 151 | Object[] parameters3 = new Object[]{"delta", 400L, Arrays.asList("beta", "BAD"), "gamma", Arrays.asList("epsilon")}; 152 | Object[] parameters4 = new Object[]{"gamma", 200L, Arrays.asList("beta", "BAD"), "gamma", Arrays.asList("epsilon")}; // gamma and beta happen at the same time, beta should come first (sorted on action after timestamp) 153 | Object[] parameters5 = new Object[]{ null, 800L, Arrays.asList("beta", "BAD"), "gamma", Arrays.asList("epsilon")}; // Check null action_column 154 | Object[] parameters6 = new Object[]{"omega", null, Arrays.asList("beta", "BAD"), "gamma", Arrays.asList("epsilon")}; // Check null timestamp 155 | 156 | // Process the data 157 | AggregationBuffer agg = udafEvaluator.getNewAggregationBuffer(); 158 | udafEvaluator.reset(agg); 159 | udafEvaluator.iterate(agg, parameters1); 160 | udafEvaluator.iterate(agg, parameters2); 161 | udafEvaluator.iterate(agg, parameters3); 162 | udafEvaluator.iterate(agg, parameters4); 163 | udafEvaluator.iterate(agg, parameters5); 164 | udafEvaluator.iterate(agg, parameters6); 165 | Object result = udafEvaluator.terminate(agg); 166 | 167 | // Expected 168 | List expected = new ArrayList<>(); 169 | expected.add(1L); 170 | expected.add(1L); 171 | expected.add(0L); 172 | 173 | Assert.assertEquals(expected, result); 174 | } 175 | 176 | @Test 177 | public void testPartial1() throws HiveException { 178 | Funnel udaf = new Funnel(); 179 | 180 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 181 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, // action_column 182 | PrimitiveObjectInspectorFactory.javaLongObjectInspector, // timestamp_column 183 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector), // funnel_step_1 184 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector) // funnel_step_1 185 | }; 186 | 187 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 188 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 189 | 190 | ObjectInspector outputObjectInspector = udafEvaluator.init(Mode.PARTIAL1, inputObjectInspectorList); 191 | 192 | // Order will be "alpha, beta, gamma, delta" when ordered on timestamp_column 193 | // Funnel is "beta" -> "gamma" -> "epsilon" 194 | // Should return [1, 1, 0] as we don't have an epsilon 195 | Object[] parameters1 = new Object[]{ "beta", 200L, Arrays.asList("beta"), "gamma", Arrays.asList("epsilon")}; 196 | Object[] parameters2 = new Object[]{"alpha", 100L, Arrays.asList("beta"), "gamma", Arrays.asList("epsilon")}; 197 | Object[] parameters3 = new Object[]{"delta", 400L, Arrays.asList("beta"), "gamma", Arrays.asList("epsilon")}; 198 | Object[] parameters4 = new Object[]{"gamma", 300L, Arrays.asList("beta"), "gamma", Arrays.asList("epsilon")}; 199 | 200 | // Process the data 201 | AggregationBuffer agg = udafEvaluator.getNewAggregationBuffer(); 202 | udafEvaluator.reset(agg); 203 | udafEvaluator.iterate(agg, parameters1); 204 | udafEvaluator.iterate(agg, parameters2); 205 | udafEvaluator.iterate(agg, parameters3); 206 | udafEvaluator.iterate(agg, parameters4); 207 | Object result = udafEvaluator.terminatePartial(agg); 208 | 209 | // Expected partial output 210 | List expected = new ArrayList<>(); 211 | expected.add(Arrays.asList("beta", "gamma")); 212 | expected.add(Arrays.asList(200L, 300L)); 213 | expected.add(Arrays.asList("beta", null, "gamma", null, "epsilon", null)); 214 | 215 | Assert.assertEquals(expected, result); 216 | } 217 | 218 | @Test 219 | public void testPartial2() throws HiveException { 220 | Funnel udaf = new Funnel(); 221 | 222 | // Construct the object inspector for udaf evaluator 223 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 224 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, // action_column 225 | PrimitiveObjectInspectorFactory.javaLongObjectInspector, // timestamp_column 226 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector), // funnel_step_1 227 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector) // funnel_step_1 228 | }; 229 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 230 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 231 | 232 | // Construct the struct object inspector 233 | List fieldNames = new ArrayList<>(); 234 | fieldNames.add("action"); 235 | fieldNames.add("timestamp"); 236 | fieldNames.add("funnel"); 237 | List fieldInspectors = new ArrayList<>(); 238 | fieldInspectors.add(ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector)); 239 | fieldInspectors.add(ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector)); 240 | fieldInspectors.add(ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector)); 241 | ObjectInspector structObjectInspector = ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldInspectors); 242 | ObjectInspector[] evaluatorInputObjectInspectorList = new ObjectInspector[]{structObjectInspector}; 243 | 244 | ObjectInspector outputObjectInspector = udafEvaluator.init(Mode.PARTIAL2, evaluatorInputObjectInspectorList); 245 | 246 | // Create the two structs to merge 247 | List parameter1 = new ArrayList<>(); 248 | parameter1.add(Arrays.asList("beta")); 249 | parameter1.add(Arrays.asList(300L)); 250 | parameter1.add(Arrays.asList("alpha", null, "beta", null, "gamma", null, "epsilon", null)); 251 | 252 | List parameter2 = new ArrayList<>(); 253 | parameter2.add(Arrays.asList("gamma", "alpha")); 254 | parameter2.add(Arrays.asList(400L, 200L)); 255 | parameter1.add(Arrays.asList("alpha", null, "beta", null, "gamma", null, "epsilon", null)); 256 | 257 | // Process the data 258 | AggregationBuffer agg = udafEvaluator.getNewAggregationBuffer(); 259 | udafEvaluator.reset(agg); 260 | udafEvaluator.merge(agg, parameter1); 261 | udafEvaluator.merge(agg, parameter2); 262 | Object result = udafEvaluator.terminatePartial(agg); 263 | 264 | // Expected 265 | List expected = new ArrayList<>(); 266 | expected.add(Arrays.asList("beta", "gamma", "alpha")); 267 | expected.add(Arrays.asList(300L, 400L, 200L)); 268 | expected.add(Arrays.asList("alpha", null, "beta", null, "gamma", null, "epsilon", null)); 269 | 270 | Assert.assertEquals(expected, result); 271 | } 272 | 273 | @Test 274 | public void testFinal() throws HiveException { 275 | Funnel udaf = new Funnel(); 276 | 277 | // Construct the object inspector for udaf evaluator 278 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 279 | PrimitiveObjectInspectorFactory.javaStringObjectInspector, // action_column 280 | PrimitiveObjectInspectorFactory.javaLongObjectInspector, // timestamp_column 281 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector), // funnel_step_1 282 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector) // funnel_step_1 283 | }; 284 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 285 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 286 | 287 | // Construct the struct object inspector 288 | List fieldNames = new ArrayList<>(); 289 | fieldNames.add("action"); 290 | fieldNames.add("timestamp"); 291 | fieldNames.add("funnel"); 292 | List fieldInspectors = new ArrayList<>(); 293 | fieldInspectors.add(ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector)); 294 | fieldInspectors.add(ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector)); 295 | fieldInspectors.add(ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector)); 296 | ObjectInspector structObjectInspector = ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldInspectors); 297 | ObjectInspector[] evaluatorInputObjectInspectorList = new ObjectInspector[]{structObjectInspector}; 298 | 299 | ObjectInspector outputObjectInspector = udafEvaluator.init(Mode.FINAL, evaluatorInputObjectInspectorList); 300 | 301 | // Create the two structs to merge 302 | List parameter1 = new ArrayList<>(); 303 | parameter1.add(Arrays.asList("beta")); 304 | parameter1.add(Arrays.asList(300L)); 305 | parameter1.add(Arrays.asList("alpha", null, "beta", null, "gamma", null, "epsilon", null)); 306 | 307 | List parameter2 = new ArrayList<>(); 308 | parameter2.add(Arrays.asList("gamma", "alpha")); 309 | parameter2.add(Arrays.asList(400L, 200L)); 310 | parameter2.add(Arrays.asList("alpha", null, "beta", null, "gamma", null, "epsilon", null)); 311 | 312 | // Process the data 313 | AggregationBuffer agg = udafEvaluator.getNewAggregationBuffer(); 314 | udafEvaluator.reset(agg); 315 | udafEvaluator.merge(agg, parameter1); 316 | udafEvaluator.merge(agg, parameter2); 317 | Object result = udafEvaluator.terminate(agg); 318 | 319 | // Expected 320 | List expected = Arrays.asList(1L, 1L, 1L, 0L); 321 | 322 | Assert.assertEquals(expected, result); 323 | } 324 | } 325 | -------------------------------------------------------------------------------- /src/test/java/com/yahoo/hive/udf/funnel/MergeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Yahoo Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.yahoo.hive.udf.funnel; 18 | 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; 22 | import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; 23 | import org.apache.hadoop.hive.ql.metadata.HiveException; 24 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AggregationBuffer; 25 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.Mode; 26 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator; 27 | import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFParameterInfo; 28 | import org.apache.hadoop.hive.ql.udf.generic.SimpleGenericUDAFParameterInfo; 29 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; 30 | import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; 31 | import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; 32 | import org.junit.Assert; 33 | import org.junit.Test; 34 | 35 | public class MergeTest { 36 | @Test(expected = UDFArgumentLengthException.class) 37 | public void testInvalidNumberOfParams() throws HiveException { 38 | Merge udaf = new Merge(); 39 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 40 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector), 41 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 42 | }; 43 | 44 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 45 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 46 | } 47 | 48 | @Test(expected = UDFArgumentTypeException.class) 49 | public void testPrimitiveParam() throws HiveException { 50 | Merge udaf = new Merge(); 51 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 52 | PrimitiveObjectInspectorFactory.javaStringObjectInspector 53 | }; 54 | 55 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 56 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 57 | } 58 | 59 | @Test(expected = UDFArgumentTypeException.class) 60 | public void testArrayOfNonPrimitives() throws HiveException { 61 | Merge udaf = new Merge(); 62 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 63 | ObjectInspectorFactory.getStandardListObjectInspector(ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector)) 64 | }; 65 | 66 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 67 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 68 | } 69 | 70 | @Test(expected = UDFArgumentTypeException.class) 71 | public void testArrayOfNonNumbers() throws HiveException { 72 | Merge udaf = new Merge(); 73 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 74 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaStringObjectInspector) 75 | }; 76 | 77 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 78 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 79 | } 80 | 81 | @Test 82 | public void testComplete() throws HiveException { 83 | Merge udaf = new Merge(); 84 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 85 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 86 | }; 87 | 88 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 89 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 90 | 91 | ObjectInspector outputObjectInspector = udafEvaluator.init(Mode.COMPLETE, inputObjectInspectorList); 92 | 93 | List funnel1 = new ArrayList<>(); 94 | funnel1.add(1L); 95 | funnel1.add(1L); 96 | funnel1.add(0L); 97 | 98 | List funnel2 = new ArrayList<>(); 99 | funnel2.add(1L); 100 | funnel2.add(0L); 101 | funnel2.add(0L); 102 | 103 | Object[] parameters1 = new Object[]{null}; 104 | Object[] parameters2 = new Object[]{funnel1}; 105 | Object[] parameters3 = new Object[]{funnel2}; 106 | 107 | AggregationBuffer agg = udafEvaluator.getNewAggregationBuffer(); 108 | udafEvaluator.reset(agg); 109 | udafEvaluator.iterate(agg, parameters1); 110 | udafEvaluator.iterate(agg, parameters2); 111 | udafEvaluator.iterate(agg, parameters3); 112 | Object result = udafEvaluator.terminate(agg); 113 | 114 | // Expected 115 | List expected = new ArrayList<>(); 116 | expected.add(2L); 117 | expected.add(1L); 118 | expected.add(0L); 119 | 120 | Assert.assertEquals(expected, result); 121 | } 122 | 123 | @Test 124 | public void testPartial2() throws HiveException { 125 | Merge udaf = new Merge(); 126 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 127 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 128 | }; 129 | 130 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 131 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 132 | 133 | ObjectInspector outputObjectInspector = udafEvaluator.init(Mode.PARTIAL2, inputObjectInspectorList); 134 | 135 | // Setup the two partial results 136 | List partialResults1 = new ArrayList<>(); 137 | partialResults1.add(1L); 138 | partialResults1.add(1L); 139 | partialResults1.add(0L); 140 | 141 | List partialResults2 = new ArrayList<>(); 142 | partialResults2.add(1L); 143 | partialResults2.add(1L); 144 | partialResults2.add(1L); 145 | 146 | // Merge the partial results 147 | MergeAggregateBuffer agg = (MergeAggregateBuffer) udafEvaluator.getNewAggregationBuffer(); 148 | udafEvaluator.reset(agg); 149 | udafEvaluator.merge(agg, partialResults1); 150 | udafEvaluator.merge(agg, partialResults2); 151 | Object result = udafEvaluator.terminatePartial(agg); 152 | 153 | // Expected results 154 | List expected = new ArrayList<>(); 155 | expected.add(2L); 156 | expected.add(2L); 157 | expected.add(1L); 158 | 159 | Assert.assertEquals(expected, result); 160 | } 161 | 162 | @Test(expected = UDFArgumentTypeException.class) 163 | public void testCompleteFunnelSizeMismatch() throws HiveException { 164 | Merge udaf = new Merge(); 165 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 166 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 167 | }; 168 | 169 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 170 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 171 | 172 | ObjectInspector outputObjectInspector = udafEvaluator.init(Mode.COMPLETE, inputObjectInspectorList); 173 | 174 | // Setup two funnels, different sizes. 175 | List funnel1 = new ArrayList<>(); 176 | funnel1.add(1L); 177 | funnel1.add(1L); 178 | funnel1.add(0L); 179 | 180 | List funnel2 = new ArrayList<>(); 181 | funnel2.add(1L); 182 | funnel2.add(0L); 183 | 184 | Object[] parameters1 = new Object[]{funnel1}; 185 | Object[] parameters2 = new Object[]{funnel2}; 186 | 187 | // Should cause an error when merging funnels of different sizes 188 | AggregationBuffer agg = udafEvaluator.getNewAggregationBuffer(); 189 | udafEvaluator.reset(agg); 190 | udafEvaluator.iterate(agg, parameters1); 191 | udafEvaluator.iterate(agg, parameters2); 192 | } 193 | 194 | @Test(expected = UDFArgumentTypeException.class) 195 | public void testPartial2FunnelSizeMismatch() throws HiveException { 196 | Merge udaf = new Merge(); 197 | ObjectInspector[] inputObjectInspectorList = new ObjectInspector[]{ 198 | ObjectInspectorFactory.getStandardListObjectInspector(PrimitiveObjectInspectorFactory.javaLongObjectInspector) 199 | }; 200 | 201 | GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(inputObjectInspectorList, false, false); 202 | GenericUDAFEvaluator udafEvaluator = udaf.getEvaluator(paramInfo); 203 | 204 | ObjectInspector outputObjectInspector = udafEvaluator.init(Mode.PARTIAL2, inputObjectInspectorList); 205 | 206 | // Setup the two partial results, should fail when merging list of different sizes 207 | List partialResults1 = new ArrayList<>(); 208 | partialResults1.add(1L); 209 | partialResults1.add(1L); 210 | 211 | List partialResults2 = new ArrayList<>(); 212 | partialResults2.add(1L); 213 | partialResults2.add(0L); 214 | partialResults2.add(0L); 215 | 216 | // Merge the partial results, should throw error due to list size difference 217 | MergeAggregateBuffer agg = (MergeAggregateBuffer) udafEvaluator.getNewAggregationBuffer(); 218 | udafEvaluator.reset(agg); 219 | udafEvaluator.merge(agg, partialResults1); 220 | udafEvaluator.merge(agg, partialResults2); 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=OFF 2 | --------------------------------------------------------------------------------