Flink1.17之前实现JdbcLookup谓词下推

2024-05-16 14:29

本文主要是介绍Flink1.17之前实现JdbcLookup谓词下推,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Flink1.17之前实现JdbcLookup谓词下推

需求背景

Flink在1.17版本之前,flink-connector-jdbc的LookupJoin是不支持on条件下推的,例如on device_id=‘1’,查询SQL中是不会包含device_id='1’的条件,相关issue:https://issues.apache.org/jira/browse/FLINK-32321,在1.19版本该问题已经解决。谓词不下推会导致每次查询的数据量变多,本篇文章主要介绍如何在1.17支持谓词下推

技术实现

在JdbcDynamicTableSource中是已经支持谓词下推到连接器端的,支持连接器的Lookup查询没有将谓词下推应用到SQL语句上,所以我们主要变动如下两个类:

  1. JdbcDynamicTableSource
  2. JdbcRowDataLookupFunction

修改JdbcDynamicTableSource

位置:org.apache.flink.connector.jdbc.table.JdbcDynamicTableSource

目的:在getLookupRuntimeProvider方法中将将谓词下推的查询条件以及参数传入到LookupFunction中。

修改内容:如下代码

    @Overridepublic LookupRuntimeProvider getLookupRuntimeProvider(LookupContext context) {// JDBC only support non-nested look up keysString[] keyNames = new String[context.getKeys().length];for (int i = 0; i < keyNames.length; i++) {int[] innerKeyArr = context.getKeys()[i];Preconditions.checkArgument(innerKeyArr.length == 1, "JDBC only support non-nested look up keys");keyNames[i] = DataType.getFieldNames(physicalRowDataType).get(innerKeyArr[0]);}final RowType rowType = (RowType) physicalRowDataType.getLogicalType();JdbcRowDataLookupFunction lookupFunction =new JdbcRowDataLookupFunction(options,lookupMaxRetryTimes,DataType.getFieldNames(physicalRowDataType).toArray(new String[0]),DataType.getFieldDataTypes(physicalRowDataType).toArray(new DataType[0]),keyNames,rowType,// 将谓词下推的查询条件以及参数传入到LookupFunction中resolvedPredicates,pushdownParams);if (cache != null) {return PartialCachingLookupProvider.of(lookupFunction, cache);} else {return LookupFunctionProvider.of(lookupFunction);}}

修改JdbcRowDataLookupFunction

位置:org.apache.flink.connector.jdbc.table.JdbcRowDataLookupFunction

目的:接受下推的条件及参数,重新拼装SQL,并在执行的时候将参数传入

修改内容:

  1. 构造方法支持接受下推的条件及参数两个变量,拼接条件语句,并将条件中的’?‘参数占位符替换为’:predicate_1’以支持FieldNamedPreparedStatement
 public JdbcRowDataLookupFunction(JdbcConnectorOptions options,int maxRetryTimes,String[] fieldNames,DataType[] fieldTypes,String[] keyNames,RowType rowType,List<String> resolvedPredicates,Object[] pushdownParams) {checkNotNull(options, "No JdbcOptions supplied.");checkNotNull(fieldNames, "No fieldNames supplied.");checkNotNull(fieldTypes, "No fieldTypes supplied.");checkNotNull(keyNames, "No keyNames supplied.");this.connectionProvider = new SimpleJdbcConnectionProvider(options);List<String> nameList = Arrays.asList(fieldNames);DataType[] keyTypes =Arrays.stream(keyNames).map(s -> {checkArgument(nameList.contains(s),"keyName %s can't find in fieldNames %s.",s,nameList);return fieldTypes[nameList.indexOf(s)];}).toArray(DataType[]::new);this.maxRetryTimes = maxRetryTimes;// 添加谓词条件查询的逻辑List<String> predicateNames = new ArrayList<>(resolvedPredicates.size());List<String> fieldNamedPredicates = new ArrayList<>(resolvedPredicates.size());for (String pred : resolvedPredicates) {while (pred.contains("?")){String predicateName = "predicate_"+predicateNames.size();pred = pred.replaceFirst("\\?", ":" + predicateName);predicateNames.add(predicateName);}fieldNamedPredicates.add(String.format("(%s)", pred));}String joinedConditions = fieldNamedPredicates.isEmpty() ? "" : " AND " + String.join(" AND ", fieldNamedPredicates);this.pushdownParams = pushdownParams;this.conditionNames = ArrayUtils.concat(keyNames, predicateNames.toArray(new String[0]));this.query =options.getDialect().getSelectFromStatement(options.getTableName(), fieldNames, keyNames) + joinedConditions;LOG.debug("Query generated for JDBC lookup: " + query);JdbcDialect jdbcDialect = options.getDialect();this.jdbcRowConverter = jdbcDialect.getRowConverter(rowType);this.lookupKeyRowConverter =jdbcDialect.getRowConverter(RowType.of(Arrays.stream(keyTypes).map(DataType::getLogicalType).toArray(LogicalType[]::new)));}
  1. 修改establishConnectionAndStatement方法,在创建Statement是将新生成的conditionNames作为fieldNames传入
    private void establishConnectionAndStatement() throws SQLException, ClassNotFoundException {Connection dbConn = connectionProvider.getOrEstablishConnection();statement = FieldNamedPreparedStatement.prepareStatement(dbConn, query, conditionNames);}
  1. 新增paddingPredicates方法用来想Statement中填充参数
    private FieldNamedPreparedStatement paddingPredicates() throws SQLException {// 进行谓词填充int pushdowParamStartIndex = conditionNames.length - pushdownParams.length;for (int i = pushdowParamStartIndex; i < conditionNames.length; i++) {Object param = pushdownParams[i - pushdowParamStartIndex];if (param instanceof String) {statement.setString(i, (String) param);} else if (param instanceof Long) {statement.setLong(i, (Long) param);} else if (param instanceof Integer) {statement.setInt(i, (Integer) param);} else if (param instanceof Double) {statement.setDouble(i, (Double) param);} else if (param instanceof Boolean) {statement.setBoolean(i, (Boolean) param);} else if (param instanceof Float) {statement.setFloat(i, (Float) param);} else if (param instanceof BigDecimal) {statement.setBigDecimal(i, (BigDecimal) param);} else if (param instanceof Byte) {statement.setByte(i, (Byte) param);} else if (param instanceof Short) {statement.setShort(i, (Short) param);} else if (param instanceof Date) {statement.setDate(i, (Date) param);} else if (param instanceof Time) {statement.setTime(i, (Time) param);} else if (param instanceof Timestamp) {statement.setTimestamp(i, (Timestamp) param);} else {// extends with other types if neededthrow new IllegalArgumentException("Padding predicate failed. Parameter "+ i+ " of type "+ param.getClass()+ " is not handled (yet).");}}return statement;}
  1. 修改lookup方法,在执行查询之前,进行参数填充
    /*** This is a lookup method which is called by Flink framework in runtime.** @param keyRow lookup keys*/@Overridepublic Collection<RowData> lookup(RowData keyRow) {for (int retry = 0; retry <= maxRetryTimes; retry++) {try {statement.clearParameters();// 谓词填充statement = paddingPredicates();statement = lookupKeyRowConverter.toExternal(keyRow, statement);try (ResultSet resultSet = statement.executeQuery()) {ArrayList<RowData> rows = new ArrayList<>();while (resultSet.next()) {RowData row = jdbcRowConverter.toInternal(resultSet);rows.add(row);}rows.trimToSize();return rows;}} catch (SQLException e) {LOG.error(String.format("JDBC executeBatch error, retry times = %d", retry), e);if (retry >= maxRetryTimes) {throw new RuntimeException("Execution of JDBC statement failed.", e);}try {if (!connectionProvider.isConnectionValid()) {statement.close();connectionProvider.closeConnection();establishConnectionAndStatement();}} catch (SQLException | ClassNotFoundException exception) {LOG.error("JDBC connection is not valid, and reestablish connection failed",exception);throw new RuntimeException("Reestablish JDBC connection failed", exception);}try {Thread.sleep(1000L * retry);} catch (InterruptedException e1) {throw new RuntimeException(e1);}}}return Collections.emptyList();}

这篇关于Flink1.17之前实现JdbcLookup谓词下推的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/995168

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4