Flink数据写入Elastic Search

需要注意的是,flink连接es时,端口号需要使用tcp端口(一般es默认http端口为9200,tcp端口为9300)。

代码如下:

    //es配置
    val config = new java.util.HashMap[String, String]
    config.put("bulk.flush.max.actions", "1")
    config.put("cluster.name", "your_name")
    val transportAddresses = new java.util.ArrayList[InetSocketAddress]
    transportAddresses.add(new InetSocketAddress(InetAddress.getByName("host1"), 9300))
    transportAddresses.add(new InetSocketAddress(InetAddress.getByName("host2"), 9300))
    transportAddresses.add(new InetSocketAddress(InetAddress.getByName("host3"), 9300))
    transportAddresses.add(new InetSocketAddress(InetAddress.getByName("host4"), 9300))
    transportAddresses.add(new InetSocketAddress(InetAddress.getByName("host5"), 9300))

    resultStream.addSink(new ElasticsearchSink(config, transportAddresses, new ElasticsearchSinkFunction[(String, Int, Int, Long, Long)] {
      def createIndexRequest(element: (String, Int, Int, Long, Long)): IndexRequest = {
        val dataMap = new java.util.HashMap[String, Any]
        val keys = element._1.split("_")
        val date = keys(0)
        val productId = keys(1)
        val channelId = keys(2)
        val carriorType = keys(3)
        val provinceName = keys(4)
        dataMap.put("date", date)
        dataMap.put("productId", productId)
        dataMap.put("channelId", channelId)
        dataMap.put("carriorType", carriorType)
        dataMap.put("provinceName", provinceName)
        dataMap.put("pv", element._2)
        dataMap.put("uv", element._3)
        val idCompact: String = date + productId + channelId + carriorType + provinceName
        val id: String = DataUtils.simpleEncode(idCompact)
        return Requests.indexRequest()
          .index("your_index")
          .`type`("your_type")
          .id(id)
          .source(dataMap)
      }
      def process(element: (String, Int, Int, Long, Long), ctx: RuntimeContext, indexer: RequestIndexer): Unit = {
        indexer.add(createIndexRequest(element))
      }
    }))

pom文件:

<dependency>
   <groupId>org.apache.flink</groupId>
   <artifactId>flink-connector-elasticsearch5_2.10</artifactId>
   <version>1.3.3</version>
</dependency>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值