Calcite 自定义优化器规则

2023-11-01 12:52

本文主要是介绍Calcite 自定义优化器规则,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1)总结
1.创建 CSVProjectRule 继承 RelRule<CSVProjectRule.Config>
a)在 CSVProjectRule.Config 接口中实现匹配规则
Config DEFAULT = EMPTY.withOperandSupplier(b0 ->b0.operand(LogicalProject.class).anyInputs()).as(Config.class);
b)在 CSVProjectRule 实现类中,如果匹配上了规则,则进行转换
 		@Overridepublic void onMatch(RelOptRuleCall call) {final LogicalProject project = call.rel(0);final RelNode converted = convert(project);if (converted != null) {call.transformTo(converted);}}------------------------------------------------public RelNode convert(RelNode rel) {final LogicalProject project = (LogicalProject) rel;final RelTraitSet traitSet = project.getTraitSet();return new CSVProject(project.getCluster(), traitSet,project.getInput(), project.getProjects(),project.getRowType());}
2.创建转换后的RelNode 即 CSVProject
2)代码示例

CSVProjectRule

package cn.com.ptpress.cdm.optimization.RelBuilder.optimizer;import cn.com.ptpress.cdm.optimization.RelBuilder.csvRelNode.CSVProject;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelRule;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.logical.LogicalProject;public class CSVProjectRule  extends RelRule<CSVProjectRule.Config> {@Overridepublic void onMatch(RelOptRuleCall call) {final LogicalProject project = call.rel(0);final RelNode converted = convert(project);if (converted != null) {call.transformTo(converted);}}/** Rule configuration. */public interface Config extends RelRule.Config {Config DEFAULT = EMPTY.withOperandSupplier(b0 ->b0.operand(LogicalProject.class).anyInputs()).as(Config.class);@Override default CSVProjectRule toRule() {return new CSVProjectRule(this);}}private CSVProjectRule(Config config) {super(config);}public RelNode convert(RelNode rel) {final LogicalProject project = (LogicalProject) rel;final RelTraitSet traitSet = project.getTraitSet();return new CSVProject(project.getCluster(), traitSet,project.getInput(), project.getProjects(),project.getRowType());}
}

CSVProjectRuleWithCost

package cn.com.ptpress.cdm.optimization.RelBuilder.optimizer;import cn.com.ptpress.cdm.optimization.RelBuilder.csvRelNode.CSVProject;
import cn.com.ptpress.cdm.optimization.RelBuilder.csvRelNode.CSVProjectWithCost;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelRule;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.logical.LogicalProject;public class CSVProjectRuleWithCost extends RelRule<CSVProjectRuleWithCost.Config> {@Overridepublic void onMatch(RelOptRuleCall call) {final LogicalProject project = call.rel(0);final RelNode converted = convert(project);if (converted != null) {call.transformTo(converted);}}/** Rule configuration. */public interface Config extends RelRule.Config {Config DEFAULT = EMPTY.withOperandSupplier(b0 ->b0.operand(LogicalProject.class).anyInputs()).as(Config.class);@Override default CSVProjectRuleWithCost toRule() {return new CSVProjectRuleWithCost(this);}}private CSVProjectRuleWithCost(Config config) {super(config);}public RelNode convert(RelNode rel) {final LogicalProject project = (LogicalProject) rel;final RelTraitSet traitSet = project.getTraitSet();return new CSVProjectWithCost(project.getCluster(), traitSet,project.getInput(), project.getProjects(),project.getRowType());}
}

CSVProject

package cn.com.ptpress.cdm.optimization.RelBuilder.csvRelNode;import com.google.common.collect.ImmutableList;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptCost;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Project;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexNode;import java.util.List;public class CSVProject extends Project {public CSVProject(RelOptCluster cluster, RelTraitSet traits, RelNode input, List<? extends RexNode> projects, RelDataType rowType) {super(cluster,traits, ImmutableList.of(),input,projects,rowType);}@Overridepublic Project copy(RelTraitSet traitSet, RelNode input, List<RexNode> projects, RelDataType rowType) {return new CSVProject(getCluster(),traitSet,input,projects,rowType);}@Overridepublic RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {return planner.getCostFactory().makeZeroCost();}
}

CSVProjectWithCost

package cn.com.ptpress.cdm.optimization.RelBuilder.csvRelNode;import com.google.common.collect.ImmutableList;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptCost;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Project;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexNode;import java.util.List;public class CSVProjectWithCost extends Project{public CSVProjectWithCost(RelOptCluster cluster, RelTraitSet traits, RelNode input, List<? extends RexNode> projects, RelDataType rowType) {super(cluster,traits, ImmutableList.of(),input,projects,rowType);}@Overridepublic Project copy(RelTraitSet traitSet, RelNode input, List<RexNode> projects, RelDataType rowType) {return new CSVProjectWithCost(getCluster(),traitSet,input,projects,rowType);}@Overridepublic RelOptCost computeSelfCost(RelOptPlanner planner, RelMetadataQuery mq) {return planner.getCostFactory().makeInfiniteCost();}
}

SqlToRelNode

package cn.com.ptpress.cdm.optimization.RelBuilder.Utils;import cn.com.ptpress.cdm.ds.csv.CsvSchema;
import org.apache.calcite.config.CalciteConnectionConfigImpl;
import org.apache.calcite.config.CalciteConnectionProperty;
import org.apache.calcite.jdbc.CalciteSchema;
import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
import org.apache.calcite.prepare.CalciteCatalogReader;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.tools.Frameworks;import java.util.Properties;public class CatalogReaderUtil {public static CalciteCatalogReader createCatalogReader(SqlParser.Config parserConfig) {SchemaPlus rootSchema = Frameworks.createRootSchema(true);rootSchema.add("csv", new CsvSchema("data.csv"));return createCatalogReader(parserConfig, rootSchema);}public static CalciteCatalogReader createCatalogReader(SqlParser.Config parserConfig, SchemaPlus rootSchema) {Properties prop = new Properties();prop.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(),String.valueOf(parserConfig.caseSensitive()));CalciteConnectionConfigImpl calciteConnectionConfig = new CalciteConnectionConfigImpl(prop);return new CalciteCatalogReader(CalciteSchema.from(rootSchema),CalciteSchema.from(rootSchema).path("csv"),new JavaTypeFactoryImpl(),calciteConnectionConfig);}
}

CatalogReaderUtil

package cn.com.ptpress.cdm.optimization.RelBuilder.Utils;import cn.com.ptpress.cdm.ds.csv.CsvSchema;
import org.apache.calcite.config.CalciteConnectionConfigImpl;
import org.apache.calcite.config.CalciteConnectionProperty;
import org.apache.calcite.jdbc.CalciteSchema;
import org.apache.calcite.jdbc.JavaTypeFactoryImpl;
import org.apache.calcite.prepare.CalciteCatalogReader;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.tools.Frameworks;import java.util.Properties;public class CatalogReaderUtil {public static CalciteCatalogReader createCatalogReader(SqlParser.Config parserConfig) {SchemaPlus rootSchema = Frameworks.createRootSchema(true);rootSchema.add("csv", new CsvSchema("data.csv"));return createCatalogReader(parserConfig, rootSchema);}public static CalciteCatalogReader createCatalogReader(SqlParser.Config parserConfig, SchemaPlus rootSchema) {Properties prop = new Properties();prop.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(),String.valueOf(parserConfig.caseSensitive()));CalciteConnectionConfigImpl calciteConnectionConfig = new CalciteConnectionConfigImpl(prop);return new CalciteCatalogReader(CalciteSchema.from(rootSchema),CalciteSchema.from(rootSchema).path("csv"),new JavaTypeFactoryImpl(),calciteConnectionConfig);}
}

PlannerTest

import cn.com.ptpress.cdm.optimization.RelBuilder.Utils.SqlToRelNode;
import cn.com.ptpress.cdm.optimization.RelBuilder.optimizer.CSVProjectRule;
import cn.com.ptpress.cdm.optimization.RelBuilder.optimizer.CSVProjectRuleWithCost;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.hep.HepPlanner;
import org.apache.calcite.plan.hep.HepProgram;
import org.apache.calcite.plan.hep.HepProgramBuilder;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.rules.FilterJoinRule;
import org.apache.calcite.sql.parser.SqlParseException;
import org.junit.jupiter.api.Test;class PlannerTest {@Testpublic void testCustomRule() throws SqlParseException {final String sql = "select Id from data ";HepProgramBuilder programBuilder = HepProgram.builder();// 测试交换 CSVProjectRule 和 CSVProjectRuleWithCost 的顺序HepPlanner hepPlanner =new HepPlanner(programBuilder.addRuleInstance(CSVProjectRule.Config.DEFAULT.toRule()).addRuleInstance(CSVProjectRuleWithCost.Config.DEFAULT.toRule()).build());//        HepPlanner hepPlanner =
//                new HepPlanner(
//                        programBuilder
//                                .addRuleInstance(CSVProjectRuleWithCost.Config.DEFAULT.toRule())
//                                .addRuleInstance(CSVProjectRule.Config.DEFAULT.toRule())
//                                .build());RelNode relNode = SqlToRelNode.getSqlNode(sql, hepPlanner);System.out.println(RelOptUtil.toString(relNode));RelOptPlanner planner = relNode.getCluster().getPlanner();planner.setRoot(relNode);RelNode bestExp = planner.findBestExp();System.out.println(RelOptUtil.toString(bestExp));RelOptPlanner relOptPlanner = relNode.getCluster().getPlanner();relOptPlanner.addRule(CSVProjectRule.Config.DEFAULT.toRule());relOptPlanner.addRule(CSVProjectRuleWithCost.Config.DEFAULT.toRule());relOptPlanner.setRoot(relNode);RelNode exp = relOptPlanner.findBestExp();System.out.println(RelOptUtil.toString(exp));}/*** 未优化算子树结构* LogicalProject(ID=[$0])*   LogicalFilter(condition=[>(CAST($0):INTEGER NOT NULL, 1)])*     LogicalJoin(condition=[=($0, $3)], joinType=[inner])*       LogicalTableScan(table=[[csv, data]])*       LogicalTableScan(table=[[csv, data]])** 优化后接结果* LogicalProject(ID=[$0])*   LogicalJoin(condition=[=($0, $3)], joinType=[inner])*     LogicalFilter(condition=[>(CAST($0):INTEGER NOT NULL, 1)])*       LogicalTableScan(table=[[csv, data]])*     LogicalTableScan(table=[[csv, data]])*/@Testpublic void testHepPlanner() throws SqlParseException {final String sql = "select a.Id from data as a join data b on a.Id = b.Id where a.Id>1";HepProgramBuilder programBuilder = HepProgram.builder();HepPlanner hepPlanner =new HepPlanner(programBuilder.addRuleInstance(FilterJoinRule.FilterIntoJoinRule.Config.DEFAULT.toRule()).build());RelNode relNode = SqlToRelNode.getSqlNode(sql, hepPlanner);//未优化算子树结构System.out.println(RelOptUtil.toString(relNode));RelOptPlanner planner = relNode.getCluster().getPlanner();planner.setRoot(relNode);RelNode bestExp = planner.findBestExp();//优化后接结果System.out.println(RelOptUtil.toString(bestExp));}/*** 未转化Dag算子树结构* LogicalProject(Id=[$0], Name=[$1], Score=[$2])*   LogicalFilter(condition=[=(CAST($0):INTEGER NOT NULL, 1)])*     LogicalTableScan(table=[[csv, data]])** 转化为Dag图* Breadth-first from root:  {*     rel#8:HepRelVertex(rel#7:LogicalProject.(input=HepRelVertex#6,inputs=0..2)) = rel#7:LogicalProject.(input=HepRelVertex#6,inputs=0..2), rowcount=15.0, cumulative cost=130.0*     rel#6:HepRelVertex(rel#5:LogicalFilter.(input=HepRelVertex#4,condition==(CAST($0):INTEGER NOT NULL, 1))) = rel#5:LogicalFilter.(input=HepRelVertex#4,condition==(CAST($0):INTEGER NOT NULL, 1)), rowcount=15.0, cumulative cost=115.0*     rel#4:HepRelVertex(rel#1:LogicalTableScan.(table=[csv, data])) = rel#1:LogicalTableScan.(table=[csv, data]), rowcount=100.0, cumulative cost=100.0* }*/@Testpublic void testGraph() throws SqlParseException {final String sql = "select * from data where Id=1";HepProgramBuilder programBuilder = HepProgram.builder();HepPlanner hepPlanner =new HepPlanner(programBuilder.build());RelNode relNode = SqlToRelNode.getSqlNode(sql, hepPlanner);//未转化Dag算子树结构System.out.println("未转化Dag算子树结构");System.out.println(RelOptUtil.toString(relNode));//转化为Dag图System.out.println("转化为Dag图");hepPlanner.setRoot(relNode);//查看需要把log4j.properties级别改为trace}
}

data.csv

Id:VARCHAR Name:VARCHAR Score:INTEGER
1,小明,90
2,小红,98
3,小亮,95

这篇关于Calcite 自定义优化器规则的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

SpringBoot3实现Gzip压缩优化的技术指南

《SpringBoot3实现Gzip压缩优化的技术指南》随着Web应用的用户量和数据量增加,网络带宽和页面加载速度逐渐成为瓶颈,为了减少数据传输量,提高用户体验,我们可以使用Gzip压缩HTTP响应,... 目录1、简述2、配置2.1 添加依赖2.2 配置 Gzip 压缩3、服务端应用4、前端应用4.1 N

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

MyBatis 动态 SQL 优化之标签的实战与技巧(常见用法)

《MyBatis动态SQL优化之标签的实战与技巧(常见用法)》本文通过详细的示例和实际应用场景,介绍了如何有效利用这些标签来优化MyBatis配置,提升开发效率,确保SQL的高效执行和安全性,感... 目录动态SQL详解一、动态SQL的核心概念1.1 什么是动态SQL?1.2 动态SQL的优点1.3 动态S

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

Python如何使用__slots__实现节省内存和性能优化

《Python如何使用__slots__实现节省内存和性能优化》你有想过,一个小小的__slots__能让你的Python类内存消耗直接减半吗,没错,今天咱们要聊的就是这个让人眼前一亮的技巧,感兴趣的... 目录背景:内存吃得满满的类__slots__:你的内存管理小助手举个大概的例子:看看效果如何?1.

一文详解SpringBoot响应压缩功能的配置与优化

《一文详解SpringBoot响应压缩功能的配置与优化》SpringBoot的响应压缩功能基于智能协商机制,需同时满足很多条件,本文主要为大家详细介绍了SpringBoot响应压缩功能的配置与优化,需... 目录一、核心工作机制1.1 自动协商触发条件1.2 压缩处理流程二、配置方案详解2.1 基础YAML

如何自定义Nginx JSON日志格式配置

《如何自定义NginxJSON日志格式配置》Nginx作为最流行的Web服务器之一,其灵活的日志配置能力允许我们根据需求定制日志格式,本文将详细介绍如何配置Nginx以JSON格式记录访问日志,这种... 目录前言为什么选择jsON格式日志?配置步骤详解1. 安装Nginx服务2. 自定义JSON日志格式各

MySQL中慢SQL优化的不同方式介绍

《MySQL中慢SQL优化的不同方式介绍》慢SQL的优化,主要从两个方面考虑,SQL语句本身的优化,以及数据库设计的优化,下面小编就来给大家介绍一下有哪些方式可以优化慢SQL吧... 目录避免不必要的列分页优化索引优化JOIN 的优化排序优化UNION 优化慢 SQL 的优化,主要从两个方面考虑,SQL 语

Android自定义Scrollbar的两种实现方式

《Android自定义Scrollbar的两种实现方式》本文介绍两种实现自定义滚动条的方法,分别通过ItemDecoration方案和独立View方案实现滚动条定制化,文章通过代码示例讲解的非常详细,... 目录方案一:ItemDecoration实现(推荐用于RecyclerView)实现原理完整代码实现

MySQL中慢SQL优化方法的完整指南

《MySQL中慢SQL优化方法的完整指南》当数据库响应时间超过500ms时,系统将面临三大灾难链式反应,所以本文将为大家介绍一下MySQL中慢SQL优化的常用方法,有需要的小伙伴可以了解下... 目录一、慢SQL的致命影响二、精准定位问题SQL1. 启用慢查询日志2. 诊断黄金三件套三、六大核心优化方案方案