网站建设与管理答案,做标书有哪些好网站,鄱阳电商网站建设,做房产中介网站当Hive提供的内置函数不能满足查询需求时#xff0c;用户可以根据自己业务编写自定义函数#xff08;User Defined Functions, UDF), 然后在HiveQL中调用。
例如有这样一个需求#xff1a;为了保护用户隐私#xff0c;当查询数据的时候#xff0c;需要将用户手机号的中间…当Hive提供的内置函数不能满足查询需求时用户可以根据自己业务编写自定义函数User Defined Functions, UDF), 然后在HiveQL中调用。
例如有这样一个需求为了保护用户隐私当查询数据的时候需要将用户手机号的中间四位用*号代替比如手机号18001292688需要显示为180****2688。这时候就可以写一个自定义函数实现这个需求。
新建项目MyUDF,添加Maven依赖
?xml version1.0 encodingUTF-8?
project xmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdorg.example/groupIdartifactIdMyUDF/artifactIdversion1.0-SNAPSHOT/versionpropertiesmaven.compiler.source8/maven.compiler.sourcemaven.compiler.target8/maven.compiler.targetproject.build.sourceEncodingUTF-8/project.build.sourceEncodinghive.version2.1.1-cdh6.1.0/hive.version/propertiesdependenciesdependencygroupIdjdk.tools/groupIdartifactIdjdk.tools/artifactIdversion1.8/versionscopesystem/scopesystemPath${JAVA_HOME}/lib/tools.jar/systemPath/dependency!--Hadoop common包--!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-common --dependencygroupIdorg.apache.hadoop/groupIdartifactIdhadoop-common/artifactIdversion2.10.2/version/dependency!-- https://mvnrepository.com/artifact/org.apache.hive/hive-exec --dependencygroupIdorg.apache.hive/groupIdartifactIdhive-exec/artifactIdversion${hive.version}/version/dependency/dependencies!--添加CDH的仓库--repositoriesrepositoryidnexus-aliyun/idurlhttp://maven.aliyun.com/nexus/content/groups/public/url/repositoryrepositoryidcloudera/idurlhttps://repository.cloudera.com/artifactory/cloudera-repos/url/repository/repositoriesbuildpluginsplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-compiler-plugin/artifactIdversion3.6.0/versionconfigurationsource1.8/sourcetarget1.8/targetencodingUTF-8/encoding/configuration/plugin/plugins/build/project
新建类hive.demo.MyUDF
package hive.demo;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;/*** Hive自定义函数类*/
public class MyUDF extends UDF{/*** param text* 调用函数时需要传入的参数* return 隐藏后的手机号码* 自定义函数类需要一个名为evaluate()的方法Hive将调用该方法*/public String evaluate(Text text){String result 手机号码错误;if(text ! null text.getLength() 11){String inputStr text.toString();StringBuffer sb new StringBuffer();sb.append(inputStr.substring(0,3));sb.append(****);sb.append(inputStr.substring(7));result sb.toString();}return result;}
}打包MyUDF.jar上传至路径比如/home/hadoop/
在Hive CLI中执行
hiveadd jar /home/hadoop/MyUDF.jar;
创建函数名称
CREATE TEMPORARY FUNCTION formatPhone AS hive.demo.MyUDF;
新建一个表测试一下这个自定义的函数
CREATE TABLE t_user(id INT, phone STRING);
INSERT INTO TABLE t_user
SELECT 1, 13123567589
UNION ALL SELECT 2, 15898705673
UNION ALL SELECT 3, 18001292688;