├── .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 | [](https://travis-ci.org/yahoo/hive-funnel-udf)
4 | [](https://coveralls.io/github/yahoo/hive-funnel-udf?branch=master)
5 | [](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