聊聊flink Table的where及filter操作

本文主要研究一下flink Table的where及filter操作

Table

flink-table_2.11-1.7.0-sources.jar!/org/apache/flink/table/api/table.scala

class Table(
    private[flink] val tableEnv: TableEnvironment,
    private[flink] val logicalPlan: LogicalNode) {

  //......

  def where(predicate: String): Table = {
    filter(predicate)
  }

  def where(predicate: Expression): Table = {
    filter(predicate)
  }

  def filter(predicate: String): Table = {
    val predicateExpr = ExpressionParser.parseExpression(predicate)
    filter(predicateExpr)
  }

  def filter(predicate: Expression): Table = {
    new Table(tableEnv, Filter(predicate, logicalPlan).validate(tableEnv))
  }

  //......
}
  • Table的where及filter操作均有两中方法,一种是String参数,一种是Expression参数;而where方法内部是调用filter方法;filter方法使用Filter(predicate, logicalPlan).validate(tableEnv)创建了新的Table;String参数最后是通过ExpressionParser.parseExpression方法转换为Expression类型

Filter

flink-table_2.11-1.7.0-sources.jar!/org/apache/flink/table/plan/logical/operators.scala

case class Filter(condition: Expression, child: LogicalNode) extends UnaryNode {
  override def output: Seq[Attribute] = child.output

  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
    child.construct(relBuilder)
    relBuilder.filter(condition.toRexNode(relBuilder))
  }

  override def validate(tableEnv: TableEnvironment): LogicalNode = {
    val resolvedFilter = super.validate(tableEnv).asInstanceOf[Filter]
    if (resolvedFilter.condition.resultType != BOOLEAN_TYPE_INFO) {
      failValidation(s"Filter operator requires a boolean expression as input," +
        s" but ${resolvedFilter.condition} is of type ${resolvedFilter.condition.resultType}")
    }
    resolvedFilter
  }
}
  • Filter对象继承了UnaryNode,它覆盖了output、construct、validate等方法;construct方法先通过Expression.toRexNode将flink的Expression转换为Apache Calcite的RexNode,然后再执行Apache Calcite的RelBuilder的filter方法

RexNode

calcite-core-1.18.0-sources.jar!/org/apache/calcite/rex/RexNode.java

public abstract class RexNode {
  //~ Instance fields --------------------------------------------------------

  // Effectively final. Set in each sub-class constructor, and never re-set.
  protected String digest;

  //~ Methods ----------------------------------------------------------------

  public abstract RelDataType getType();

  public boolean isAlwaysTrue() {
    return false;
  }

  public boolean isAlwaysFalse() {
    return false;
  }

  public boolean isA(SqlKind kind) {
    return getKind() == kind;
  }

  public boolean isA(Collection<SqlKind> kinds) {
    return getKind().belongsTo(kinds);
  }

  public SqlKind getKind() {
    return SqlKind.OTHER;
  }

  public String toString() {
    return digest;
  }

  public abstract <R> R accept(RexVisitor<R> visitor);

  public abstract <R, P> R accept(RexBiVisitor<R, P> visitor, P arg);

  @Override public abstract boolean equals(Object obj);

  @Override public abstract int hashCode();
}
  • RexNode是Row expression,可以通过RexBuilder来创建;它有很多子类,比如RexCall、RexVariable、RexFieldAccess等

RelBuilder.filter

calcite-core-1.18.0-sources.jar!/org/apache/calcite/tools/RelBuilder.java

public class RelBuilder {
  protected final RelOptCluster cluster;
  protected final RelOptSchema relOptSchema;
  private final RelFactories.FilterFactory filterFactory;
  private final RelFactories.ProjectFactory projectFactory;
  private final RelFactories.AggregateFactory aggregateFactory;
  private final RelFactories.SortFactory sortFactory;
  private final RelFactories.ExchangeFactory exchangeFactory;
  private final RelFactories.SortExchangeFactory sortExchangeFactory;
  private final RelFactories.SetOpFactory setOpFactory;
  private final RelFactories.JoinFactory joinFactory;
  private final RelFactories.SemiJoinFactory semiJoinFactory;
  private final RelFactories.CorrelateFactory correlateFactory;
  private final RelFactories.ValuesFactory valuesFactory;
  private final RelFactories.TableScanFactory scanFactory;
  private final RelFactories.MatchFactory matchFactory;
  private final Deque<Frame> stack = new ArrayDeque<>();
  private final boolean simplify;
  private final RexSimplify simplifier;

  protected RelBuilder(Context context, RelOptCluster cluster,
      RelOptSchema relOptSchema) {
    this.cluster = cluster;
    this.relOptSchema = relOptSchema;
    if (context == null) {
      context = Contexts.EMPTY_CONTEXT;
    }
    this.simplify = Hook.REL_BUILDER_SIMPLIFY.get(true);
    this.aggregateFactory =
        Util.first(context.unwrap(RelFactories.AggregateFactory.class),
            RelFactories.DEFAULT_AGGREGATE_FACTORY);
    this.filterFactory =
        Util.first(context.unwrap(RelFactories.FilterFactory.class),
            RelFactories.DEFAULT_FILTER_FACTORY);
    this.projectFactory =
        Util.first(context.unwrap(RelFactories.ProjectFactory.class),
            RelFactories.DEFAULT_PROJECT_FACTORY);
    this.sortFactory =
        Util.first(context.unwrap(RelFactories.SortFactory.class),
            RelFactories.DEFAULT_SORT_FACTORY);
    this.exchangeFactory =
        Util.first(context.unwrap(RelFactories.ExchangeFactory.class),
            RelFactories.DEFAULT_EXCHANGE_FACTORY);
    this.sortExchangeFactory =
        Util.first(context.unwrap(RelFactories.SortExchangeFactory.class),
            RelFactories.DEFAULT_SORT_EXCHANGE_FACTORY);
    this.setOpFactory =
        Util.first(context.unwrap(RelFactories.SetOpFactory.class),
            RelFactories.DEFAULT_SET_OP_FACTORY);
    this.joinFactory =
        Util.first(context.unwrap(RelFactories.JoinFactory.class),
            RelFactories.DEFAULT_JOIN_FACTORY);
    this.semiJoinFactory =
        Util.first(context.unwrap(RelFactories.SemiJoinFactory.class),
            RelFactories.DEFAULT_SEMI_JOIN_FACTORY);
    this.correlateFactory =
        Util.first(context.unwrap(RelFactories.CorrelateFactory.class),
            RelFactories.DEFAULT_CORRELATE_FACTORY);
    this.valuesFactory =
        Util.first(context.unwrap(RelFactories.ValuesFactory.class),
            RelFactories.DEFAULT_VALUES_FACTORY);
    this.scanFactory =
        Util.first(context.unwrap(RelFactories.TableScanFactory.class),
            RelFactories.DEFAULT_TABLE_SCAN_FACTORY);
    this.matchFactory =
        Util.first(context.unwrap(RelFactories.MatchFactory.class),
            RelFactories.DEFAULT_MATCH_FACTORY);
    final RexExecutor executor =
        Util.first(context.unwrap(RexExecutor.class),
            Util.first(cluster.getPlanner().getExecutor(), RexUtil.EXECUTOR));
    final RelOptPredicateList predicates = RelOptPredicateList.EMPTY;
    this.simplifier =
        new RexSimplify(cluster.getRexBuilder(), predicates, executor);
  }

  public RelBuilder filter(RexNode... predicates) {
    return filter(ImmutableList.copyOf(predicates));
  }

  public RelBuilder filter(Iterable<? extends RexNode> predicates) {
    final RexNode simplifiedPredicates =
        simplifier.simplifyFilterPredicates(predicates);
    if (simplifiedPredicates == null) {
      return empty();
    }

    if (!simplifiedPredicates.isAlwaysTrue()) {
      final Frame frame = stack.pop();
      final RelNode filter = filterFactory.createFilter(frame.rel, simplifiedPredicates);
      stack.push(new Frame(filter, frame.fields));
    }
    return this;
  }

  //......

}
  • RelBuilder在构造器里头创建了RelFactories.FilterFactory,它提供了两个filter方法,一个是RexNode变长数组参数,一个是RexNode类型的Iterable参数;filter方法首先使用simplifier.simplifyFilterPredicates将RexNode类型的Iterable转为simplifiedPredicates(RexNode),之后只要simplifiedPredicates.isAlwaysTrue()为false,则取出deque中队首的Frame(LIFO (Last-In-First-Out) stacks),调用filterFactory.createFilter创建RelNode构造新的Frame,然后重新放入deque的队首

Frame

calcite-core-1.18.0-sources.jar!/org/apache/calcite/tools/RelBuilder.java

  private static class Frame {
    final RelNode rel;
    final ImmutableList<Field> fields;

    private Frame(RelNode rel, ImmutableList<Field> fields) {
      this.rel = rel;
      this.fields = fields;
    }

    private Frame(RelNode rel) {
      String tableAlias = deriveAlias(rel);
      ImmutableList.Builder<Field> builder = ImmutableList.builder();
      ImmutableSet<String> aliases = tableAlias == null
          ? ImmutableSet.of()
          : ImmutableSet.of(tableAlias);
      for (RelDataTypeField field : rel.getRowType().getFieldList()) {
        builder.add(new Field(aliases, field));
      }
      this.rel = rel;
      this.fields = builder.build();
    }

    private static String deriveAlias(RelNode rel) {
      if (rel instanceof TableScan) {
        final List<String> names = rel.getTable().getQualifiedName();
        if (!names.isEmpty()) {
          return Util.last(names);
        }
      }
      return null;
    }

    List<RelDataTypeField> fields() {
      return Pair.right(fields);
    }
  }
  • Frame被存放于ArrayDeque中,实际是用于描述上一个操作的关系表达式以及table的别名怎么映射到row type中

RelFactories.FilterFactory.createFilter

calcite-core-1.18.0-sources.jar!/org/apache/calcite/rel/core/RelFactories.java

  public interface FilterFactory {
    /** Creates a filter. */
    RelNode createFilter(RelNode input, RexNode condition);
  }

  private static class FilterFactoryImpl implements FilterFactory {
    public RelNode createFilter(RelNode input, RexNode condition) {
      return LogicalFilter.create(input, condition);
    }
  }
  • FilterFactoryImpl实现了FilterFactory接口,createFilter方法执行的是LogicalFilter.create(input, condition),这里input是RelNode类型(RelNode取的是Frame的rel),condition是RexNode类型

LogicalFilter

calcite-core-1.18.0-sources.jar!/org/apache/calcite/rel/logical/LogicalFilter.java

public final class LogicalFilter extends Filter {
  private final ImmutableSet<CorrelationId> variablesSet;

  /** Creates a LogicalFilter. */
  public static LogicalFilter create(final RelNode input, RexNode condition) {
    return create(input, condition, ImmutableSet.of());
  }

  /** Creates a LogicalFilter. */
  public static LogicalFilter create(final RelNode input, RexNode condition,
      ImmutableSet<CorrelationId> variablesSet) {
    final RelOptCluster cluster = input.getCluster();
    final RelMetadataQuery mq = cluster.getMetadataQuery();
    final RelTraitSet traitSet = cluster.traitSetOf(Convention.NONE)
        .replaceIfs(RelCollationTraitDef.INSTANCE,
            () -> RelMdCollation.filter(mq, input))
        .replaceIf(RelDistributionTraitDef.INSTANCE,
            () -> RelMdDistribution.filter(mq, input));
    return new LogicalFilter(cluster, traitSet, input, condition, variablesSet);
  }

  //......
}
  • LogicalFilter继承了抽象类Filter,Filter继承了SingleRel,SingleRel继承了AbstractRelNode,AbstractRelNode实现了RelNode接口

小结

  • Table的where及filter操作均有两中方法,一种是String参数,一种是Expression参数;而where方法内部是调用filter方法;filter方法使用Filter(predicate, logicalPlan).validate(tableEnv)创建了新的Table;String参数最后是通过ExpressionParser.parseExpression方法转换为Expression类型
  • Filter对象继承了UnaryNode,它覆盖了output、construct、validate等方法;construct方法先通过Expression.toRexNode将flink的Expression转换为Apache Calcite的RexNode(RexNode是Row expression,可以通过RexBuilder来创建;它有很多子类,比如RexCall、RexVariable、RexFieldAccess等),然后再执行Apache Calcite的RelBuilder的filter方法
  • RelBuilder在构造器里头创建了RelFactories.FilterFactory,它提供了两个filter方法,一个是RexNode变长数组参数,一个是RexNode类型的Iterable参数;filter方法首先使用simplifier.simplifyFilterPredicates将RexNode类型的Iterable转为simplifiedPredicates(RexNode),之后只要simplifiedPredicates.isAlwaysTrue()为false,则取出deque中队首的Frame(LIFO (Last-In-First-Out) stacks,Frame被存放于ArrayDeque中,实际是用于描述上一个操作的关系表达式以及table的别名怎么映射到row type中),调用filterFactory.createFilter创建RelNode构造新的Frame,然后重新放入deque的队首;FilterFactoryImpl实现了FilterFactory接口,createFilter方法执行的是LogicalFilter.create(input, condition),这里input是RelNode类型(RelNode取的是Frame的rel),condition是RexNode类型(RexNode是Row expression,可以通过RexBuilder来创建;它有很多子类,比如RexCall、RexVariable、RexFieldAccess等);LogicalFilter继承了抽象类Filter,Filter继承了SingleRel,SingleRel继承了AbstractRelNode,AbstractRelNode实现了RelNode接口

doc

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,658评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,482评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,213评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,395评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,487评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,523评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,525评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,300评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,753评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,048评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,223评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,905评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,541评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,168评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,417评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,094评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,088评论 2 352

推荐阅读更多精彩内容