flink中作为源的elasticsearch连接器

f0brbegy  于 2021-06-21  发布在  Flink
关注(0)|答案(2)|浏览(432)

我使用elasticsearch连接器作为接收器将数据插入elasticsearch(请参阅:https://ci.apache.org/projects/flink/flink-docs-release-1.7/dev/connectors/elasticsearch.html).
但是,我没有找到任何连接器来从elasticsearch获取数据作为源。
在flink管道中是否有任何连接器或示例可以使用elasticsearch文档作为源?
当做,
阿里

9cbw7uwe

9cbw7uwe1#

我最终定义了一个简单的readfromlasticsearch函数

public static class ElasticsearchFunction
        extends ProcessFunction<MetricMeasurement, MetricPrediction> {

    public ElasticsearchFunction() throws UnknownHostException {
        client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("YOUR_IP"), PORT_NUMBER));
    }

    @Override
    public void processElement(MetricMeasurement in, Context context, Collector<MetricPrediction> out) throws Exception {
        MetricPrediction metricPrediction = new MetricPrediction();

        metricPrediction.setMetricId(in.getMetricId());
        metricPrediction.setGroupId(in.getGroupId());
        metricPrediction.setBucket(in.getBucket());

        // Get the metric measurement from Elasticsearch
        SearchResponse response = client.prepareSearch("YOUR_INDEX_NAME")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.termQuery("YOUR_TERM", in.getMetricId()))   // Query
                .setPostFilter(QueryBuilders.rangeQuery("value").from(0L).to(50L))     // Filter
                .setFrom(0).setSize(1).setExplain(true)
                .get();

        SearchHit[] results = response.getHits().getHits();
        for(SearchHit hit : results){
            String sourceAsString = hit.getSourceAsString();
            if (sourceAsString != null) {
                ObjectMapper mapper = new ObjectMapper();
                MetricMeasurement obj = mapper.readValue(sourceAsString, MetricMeasurement.class);
                obj.getMetricId();
                metricPrediction.setPredictionValue(obj.getValue());
            }
        }
        out.collect(metricPrediction);
    }
}
inkz8wg9

inkz8wg92#

我不知道flink有没有明确的es来源。我确实看到一个用户在谈论使用elasticsearch hadoop作为 HadoopInputFormat 但我不知道这是否对他们有效(见他们的代码)。

相关问题