pyflink读文件写入到elasticsearch

from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.functions import  MapFunction, RuntimeContext, KeyedProcessFunction
from abc import ABC, abstractmethod
# -*- coding: utf-8 -*-
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.functions import  MapFunction, RuntimeContext, KeyedProcessFunction
from pyflink.datastream.state import MapStateDescriptor
from pyflink.datastream.connectors.kafka import FlinkKafkaConsumer
from pyflink.common.typeinfo import Types, TypeInformation
from pyflink.datastream.connectors.elasticsearch import Elasticsearch7SinkBuilder, ElasticsearchEmitter, FlushBackoffType
from pyflink.datastream.connectors import DeliveryGuarantee
from pyflink.common.serialization import SimpleStringSchema
import json
import re
from datetime import datetime
from elasticsearch import Elasticsearch


import re
import redis


# 创建 StreamExecutionEnvironment 对象
env = StreamExecutionEnvironment.get_execution_environment()
env.set_parallelism(1)

# 读取文件,创建 DataStream 对象
data_stream = env.read_text_file('/root/pyflink/elink_test.txt')
# 对每行数据添加字符串 'aaaa'
class LogEvent:
    bus_seq = None
    line_number = None
    event_received_time = None
    app_name = None
    source_module_name = None
    source = None
    filename = None
    message = None
    serial_id = None
    thread_id = None
class MyMapFunction(MapFunction):
   def open(self, runtime_context: RuntimeContext):
     pool = redis.ConnectionPool(host='127.0.0.1',port=6379,max_connections=50)
     self.r = redis.Redis(connection_pool=pool)
   def close(self):
     self.r.close()

   def map(self,line):
    process_id='';
    bus_seq=''
    if not line.startswith("ES"):
        return 
    if '<Serial>' in line:
       pat=re.compile(r"<Serial>(\d+)</Serial>")
       bus_seq=pat.findall(line)
       process_id=line.split()[1]
       self.r.set(process_id,bus_seq[0])
    process_id=line.split()[1]
    if not len(process_id)==6 :
        process_id=line.split()[2]
     
    bus_seq=self.r.get(process_id) 
    if not bus_seq:
        return 
    #self.r.delete(process_id)
    log_event = LogEvent()
    LogEvent.bus_seq=bus_seq.decode('UTF-8')
    LogEvent.message=line
    #return (log_event.bus_seq.decode('UTF-8'),log_event.message)
    return LogEvent
    
class EsSink(MapFunction):
   def open(self, runtime_context: RuntimeContext):
     self.es = Elasticsearch("http://127.0.0.1:9200")

   def close(self):
     pass

   def map(self,LogEvent):
     try:
        data = {
          "@timestamp": datetime.now().strftime( "%Y-%m-%dT%H:%M:%S.000+0800" ),
           "content" : LogEvent.message,
            "bus_seq" : LogEvent.bus_seq
          }
     except:
          return
     self.es.index( index="flink_test",  document=data )
      
new_stream = data_stream.map(MyMapFunction()).map(EsSink())

# 输出到控制台
#new_stream.print()

# 执行任务
env.execute('Add "aaaa" to each line')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

scan724

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值