Calling UDTFs in Spark SQL Jobs
Scenario
AI DataLake allows you to use Hive User-Defined Table-Generating Functions (UDTFs) to customize table-valued functions. UDTFs are used for one-in-multiple-out data operations, specifically, UDTF reads a row of data and outputs multiple values.
Constraints
If you use a static class or interface in a UDF, add try catch to capture exceptions. Otherwise, package conflicts may occur.
Environment Preparations
Before you start, set up the development environment.
| Preparation Item | Description |
|---|---|
| Operating system (OS) | Windows 7 or a later version is required. |
| JDK | JDK 1.8 is required. |
| IntelliJ IDEA | IntelliJ IDEA 2019.1 or a compatible version is required. |
| Maven | Basic configurations of the development environment. Maven is used for project management throughout the lifecycle of software development. |
Development Process
The UDTF development process is as follows:
| No. | Step | Operation Interface | Description |
|---|---|---|---|
| 1 | Create a Maven project and configure the POM file. | IntelliJ IDEA | Write the UDTF code by referring to the Procedure. |
| 2 | Write the UDTF code. | ||
| 3 | Debug, compile, and pack the code into a JAR package. | ||
| 4 | Upload the JAR package to OBS. | OBS console | Upload the UDTF JAR file to an OBS directory. |
| 5 | Create a UDTF. | DataArts Studio console | Create a UDTF on the Develop Script page of the DataArts Studio console. |
| 6 | Verify and use the UDTF. | DataArts Studio console | On the Develop Script page of the DataArts Studio console, use the created UDTF in a Spark SQL job. |
Procedure
- Create a Maven project and configure the POM file. This step uses IntelliJ IDEA 2020.2 as an example.
- Start IntelliJ IDEA and choose File > New > Project. Figure 2 Creating a project
- Choose Maven, set Project SDK to 1.8, and click Next. Figure 3 Choosing Maven
- Set the project name, configure the storage path, and click Finish. Figure 4 Creating a project
- Add the following content to the pom.xml file.
<dependencies> <dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-exec</artifactId> <version>1.2.1</version> </dependency> </dependencies>Figure 5 Adding configurations to the POM file
- Choose src > main and right-click the java folder. Choose New > Package to create a package and a class file. Figure 6 Creating a package and a class file
Set the package name as you need. In this example, set Package to com.huawei.demo. Then, press Enter.
Figure 7 Customizing a package
Create a Java class file in the package path. In this example, the Java Class file is UDTFSplit.
Figure 8 Creating a Java class file
- Start IntelliJ IDEA and choose File > New > Project.
- Write the UDTF code. For sample code, see Sample Code.
The UDTF class must inherit org.apache.hadoop.hive.ql.udf.generic.GenericUDTF to implement the initialize, process, and close methods.
- Call the initialize method in the UDTF. This method returns the information about the returned data rows of the UDTF, such as the number and type.
- Call the process method to process data. Each time forward() is called in the process method, a row is generated. If multiple columns are generated, you can put the values in an array and pass the array to the forward() function.
public void process(Object[] args) throws HiveException { // TODO Auto-generated method stub if(args.length == 0){ return; } String input = args[0].toString(); if(StringUtils.isEmpty(input)){ return; } String[] test = input.split(";"); for (int i = 0; i < test.length; i++) { try { String[] result = test[i].split(":"); forward(result); } catch (Exception e) { continue; } } } - Call the close method to clear methods that need to be closed.
- Use IntelliJ IDEA to compile the code and pack it into the JAR package.
- Click Maven in the tool bar on the right, and click clean and compile to compile the code. After the compilation is successful, click package.Figure 9 Compiling and packaging
The generated JAR package is stored in the target directory. In this example, the generated JAR package is named MyUDTF-1.0-SNAPSHOT.jar and stored in the D:\MyUDTF\target directory.
Figure 10 Generating a JAR file
- Click Maven in the tool bar on the right, and click clean and compile to compile the code.
- Log in to the OBS console and upload the JAR file to the OBS path.
The region of the OBS bucket to which the JAR file is uploaded must be the same as the region of the AI DataLake workspace. Cross-region operations are not allowed.
- Create a UDTF.
- On the AI DataLake console, click DataArts Studio in the lower left corner.
- On the Develop Script page, create a Serverless Spark SQL script and select the endpoint, catalog, and database. Figure 11 Creating a Serverless Spark SQL script
- In the SQL editing area, enter the following command for creating the UDTF:
CREATE FUNCTION mytestsplit AS 'com.huawei.demo.UDTFSplit' using jar 'obs://aidatalake-test-obs01/MyUDTF-1.0-SNAPSHOT.jar';
- Click Execute.
- Verify and use the UDTF.
Use the UDTF in the SELECT statement as follows:
select mytestsplit('abc:123\;efd:567\;utf:890'); - (Optional) Delete the UDTF.
If this function is no longer used, run the following statement to delete it:
Drop FUNCTION mytestsplit;
Sample Code
The complete UDTFSplit.java code is as follows:
import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
public class UDTFSplit extends GenericUDTF {
@Override
public void close() throws HiveException {
// TODO Auto-generated method stub
}
@Override
public void process(Object[] args) throws HiveException {
// TODO Auto-generated method stub
if(args.length == 0){
return;
}
String input = args[0].toString();
if(StringUtils.isEmpty(input)){
return;
}
String[] test = input.split(";");
for (int i = 0; i < test.length; i++) {
try {
String[] result = test[i].split(":");
forward(result);
} catch (Exception e) {
continue;
}
}
}
@Override
public StructObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException {
if (args.length != 1) {
throw new UDFArgumentLengthException("ExplodeMap takes only one argument");
}
if (args[0].getCategory() != ObjectInspector.Category.PRIMITIVE) {
throw new UDFArgumentException("ExplodeMap takes string as a parameter");
}
ArrayList<String> fieldNames = new ArrayList<String>();
ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
fieldNames.add("col1");
fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
fieldNames.add("col2");
fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
}
} What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot