Nicholas Leong
01/19/2024, 8:03 AMhùng trần việt
01/19/2024, 10:46 AMpublic class String2RowDataFlatMap implements FlatMapFunctionString, RowData {
private RowType tableSchema;
public String2RowDataFlatMap(ResolvedSchema physicalSchema) {
this.tableSchema = (RowType) physicalSchema.toPhysicalRowDataType().getLogicalType();
}
@Override
public void flatMap(String value, CollectorRowData collector) throws Exception {
RowData result = this.deserializeString(value);
if (result != null) {
collector.collect(result);
}
}
RowData deserializeString(String value) throws UnsupportedEncodingException {
JSONObject jsonObject = new JSONObject(value);
JSONObject resultJsonObject = new JSONObject();
IteratorString keys = jsonObject.keys();
ListString lstParseFields = Arrays.asList("fullDocument", "documentKey", "_id");
while (keys.hasNext()) {
String key = keys.next();
if (lstParseFields.contains(key)) {
resultJsonObject.put(key, this.parseDocument(jsonObject.get(key).toString()));
} else {
resultJsonObject.put(key, jsonObject.get(key));
}
}
JSONObject fullDocument = resultJsonObject.getJSONObject("fullDocument");
GenericRowData genericRowData = new GenericRowData(this.tableSchema.getFieldCount());
for (RowType.RowField field : this.tableSchema.getFields()) {
int pos = this.tableSchema.getFields().indexOf(field);
if (!fullDocument.has(field.getName())) {
throw new UnsupportedEncodingException(
String.format("Field don't exist %s", field.getName()));
}
genericRowData.setField(pos, fullDocument.get(field.getName()));
}
return genericRowData;
}
}