我有jsons喜欢,
{
"name":"someone",
"job":"doctor",
"etc":"etc"
}
在每个json中,对于像医生,飞行员,司机,守望者等“工作”都有不同的价值。我想根据“工作”值分离每个json并将其存储在/home/doctor
,/home/pilot
,/home/driver
等不同的位置。
我已经尝试过SplitStream函数来执行此操作,但我必须指定这些值以匹配条件。
public class MyFlinkJob {
private static JsonParser jsonParser = new JsonParser();
private static String key_1 = "doctor";
private static String key_2 = "driver";
private static String key_3 = "pilot";
private static String key_default = "default";
public static void main(String args[]) throws Exception {
Properties prop = new Properties();
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
Properties props = new Properties();
props.setProperty("bootstrap.servers", kafka);
props.setProperty("group.id", "myjob");
FlinkKafkaConsumer<String> myConsumer = new FlinkKafkaConsumer<>("topic", new SimpleStringSchema(), props);
DataStream<String> record = env.addSource(myConsumer).rebalance()
SplitStream<String> split = record.split(new OutputSelector<String>() {
@Override
public Iterable<String> select(String val) {
JsonObject json = (JsonObject)jsonParser.parse(val);
String jsonValue = CommonFields.getFieldValue(json, "job");
List<String> output = new ArrayList<String>();
if (key_1.equalsIgnoreCase(jsonValue)) {
output.add("doctor");
} else if (key_2.equalsIgnoreCase(jsonValue)) {
output.add("driver");
} else if (key_3.equalsIgnoreCase(jsonValue)) {
output.add("pilot");
} else {
output.add("default");
}
return output;
}});
DataStream<String> doctor = split.select("doctor");
DataStream<String> driver = split.select("driver");
DataStream<String> pilot = split.select("pilot");
DataStream<String> default1 = split.select("default");
doctor.addSink(getBucketingSink(batchSize, prop, key_1));
driver.addSink(getBucketingSink(batchSize, prop, key_2));
pilot.addSink(getBucketingSink(batchSize, prop, key_3));
default1.addSink(getBucketingSink(batchSize, prop, key_default));
env.execute("myjob");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static BucketingSink<String> getBucketingSink(Long BatchSize, Properties prop, String key) {
BucketingSink<String> sink = new BucketingSink<String>("hdfs://*/home/"+key);
Configuration conf = new Configuration();
conf.set("hadoop.job.ugi", "hdfs");
sink.setFSConfig(conf);
sink.setBucketer(new DateTimeBucketer<String>(prop.getProperty("DateTimeBucketer")));
return sink;
}
}
假设如果任何其他值像工程师或其他东西一样进入“工作”并且我没有在课堂上指定那么它进入默认文件夹是否有任何方法可以根据“作业”的值自动拆分这些json事件而无需指定它创建一个包含/ home / enginerr等值名称的路径?
您想使用BucketingSink,它支持根据字段的值将记录写入单独的存储桶。我可能有一个map函数,它接受JSON字符串,解析它,并发出一个Tuple2<String, String>
,其中第一个元素是JSON中job
字段的值,第二个元素是完整的JSON字符串。