Reputation: 65
A Hive table "Employee" contains a column "timerange", and the data is
timerange
1:10
1:13
1:17
1:21
1:26
If the last digit range is between (0 & 4), the data must be updated as 0. If the last digit range is between (5 & 9) must be updated as 5.
Expected output is
timerange
1:10
1:10
1:15
1:20
1:25
How can I do this?
Upvotes: 1
Views: 155
Reputation: 2725
You can do this through built-in string manipulation:
SELECT CASE WHEN SUBSTRING(timerange, LENGTH(timerange)) < "5"
THEN CONCAT(SUBSTRING(timerange, 1, LENGTH(timerange) - 1), "0")
ELSE CONCAT(SUBSTRING(timerange, 1, LENGTH(timerange) - 1), "5")
END AS timerange
FROM Employee;
Upvotes: 1
Reputation: 3677
You can create a generic UDF (GenericUDF).
Here is a sample UDF:
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.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.IntObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;
public class TimeRangeConverter GenericUDF {
@Override
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
if (arguments.length != 1) {
throw new UDFArgumentLengthException("The function time_range_converter(time_rage) requires 1 argument.");
}
ObjectInspector timeRangeVal = arguments[0];
if (!(timeRangeVal instanceof StringObjectInspector)) {
throw new UDFArgumentException("First argument must be of type String (time_range as String)");
}
return PrimitiveObjectInspectorFactory.writableStringObjectInspector;
}
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
String timeRangeVal = (String) ObjectInspectorUtils.copyToStandardJavaObject(arguments[0].get(),
PrimitiveObjectInspectorFactory.javaStringObjectInspector);
char[] characters = timeRangeVal.toCharArray();
if (characters[characters.length - 1] > '5') {
characters[characters.length - 1] = '5';
} else {
characters[characters.length - 1] = '0';
}
return String.valueOf(characters);
}
@Override
public String getDisplayString(String[] arguments) {
assert (arguments.length == 1);
return "time_range_converter(" + arguments[0] + ")";
}
}
Call the Hive update statement like:
CREATE TEMPORARY FUNCTION time_range_converterAS 'TimeRangeConverter';
UPDATE
Employee
SET
timerange = time_range_converter(timerange);
Upvotes: 0