@Override public void onMatch(RelOptRuleCall call) {
    final Join join = call.rel(0);

    if (join.getJoinType() != JoinRelType.SEMI && join.getJoinType() != JoinRelType.ANTI) {
      return;
    }

    final RelNode left = call.rel(1);
    final Aggregate rightAggregate= call.rel(2);

    // if grouping sets are involved do early return
    if(rightAggregate.getGroupType() != Aggregate.Group.SIMPLE) {
      return;
    }

    if(rightAggregate.indicator) {
      return;
    }

    // if there is any aggregate function this group by is not un-necessary
    if(!rightAggregate.getAggCallList().isEmpty()) {
      return;
    }

    JoinPredicateInfo joinPredInfo;
    try {
      joinPredInfo = HiveCalciteUtil.JoinPredicateInfo.constructJoinPredicateInfo(join);
    } catch (CalciteSemanticException e) {
      LOG.warn("Exception while extracting predicate info from {}", join);
      return;
    }
    if (!joinPredInfo.getNonEquiJoinPredicateElements().isEmpty()) {
      return;
    }
    ImmutableBitSet.Builder rightKeys = ImmutableBitSet.builder();
    for (JoinLeafPredicateInfo leftPredInfo : joinPredInfo.getEquiJoinPredicateElements()) {
      rightKeys.addAll(leftPredInfo.getProjsFromRightPartOfJoinKeysInChildSchema());
    }
    boolean shouldTransform = rightKeys.build().equals(
        ImmutableBitSet.range(rightAggregate.getGroupCount()));
    if(shouldTransform) {
      final RelBuilder relBuilder = call.builder();
      RelNode newRightInput = relBuilder.project(relBuilder.push(rightAggregate.getInput()).
          fields(rightAggregate.getGroupSet().asList())).build();
      RelNode newJoin;
      if (join.getJoinType() == JoinRelType.SEMI) {
        newJoin = call.builder().push(left).push(newRightInput)
                .semiJoin(join.getCondition()).build();
      } else {
        newJoin = call.builder().push(left).push(newRightInput)
                .antiJoin(join.getCondition()).build();
      }
      call.transformTo(newJoin);
    }
  }
Planner rule that removes a {@code Aggregate} from a HiveSemiJoin/HiveAntiJoin
right input.
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveRemoveGBYSemiJoinRule.java