我有类似json的
{
"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;
}
}
假设如果“ job”中有其他任何值,例如工程师或其他东西,而我在类中未指定,那么它将转到默认文件夹,是否有任何方法可以基于“ job”的值自动拆分那些json事件,而无需指定它并创建一个包含值名称的路径,例如/ home / enginerr?
答案 0 :(得分:1)
您想使用BucketingSink,它支持根据字段的值将记录写到单独的存储桶中。我可能有一个map函数,它接收JSON字符串,对其进行解析,并发出一个Tuple2<String, String>
,其中第一个元素是JSON中job
字段的值,第二个元素是是完整的JSON字符串。