我们在网页上经常可以看到比如 百度热榜,微博热搜 这样的排行数据,那么我们在进行网络搜索的时候如何统计这些数据呢?
热词统计有很多中方法,这里主要记录下flink如何进行热词统计。
一、场景
小白在网络上搜索水果相关内容,如何记录各中水果被搜索的次数呢?通过搜索的次数推荐搜索内容给用户,需要如何实现呢?
统计的水果有:“苹果”, “梨”, “西瓜”, “葡萄”, “火龙果”, “橘子”, “桃子”, "香蕉"
二、实现
如下为设计demo
我们先定义一个水果的数组FRUIT
private static final String[] FRUIT = { "苹果", "梨", "西瓜", "葡萄", "火龙果", "橘子", "桃子", "香蕉" };
获取数据流,随机模拟搜索的水果
统计结构:Tuple2<String, Integer> 水果名称,搜索次数
通过 keyBy(0) 聚合相同名称的水果
通过 sum(1) 统计搜索次数
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
DataStream<Tuple2<String, Integer>> fruit = env.addSource(new SourceFunction<Tuple2<String, Integer>>() {
private volatile boolean isRunning = true;
private final Random random = new Random();
@Override
public void run(SourceContext<Tuple2<String, Integer>> ctx) throws Exception {
while (isRunning) {
TimeUnit.SECONDS.sleep(1);
ctx.collect(Tuple2.of(FRUIT[random.nextInt(FRUIT.length)], 1));
}
}
@Override
public void cancel() {
isRunning = false;
}
});
fruit.keyBy(0).sum(1).print();
env.execute("fruit");
运行结果:
当统计完成后可以将统计好的数据传到页面上通过组建绘制词云哦