Search in sources :

Example 31 with OrderBy

use of io.crate.analyze.OrderBy in project crate by crate.

the class AbstractWindowFunctionTest method assertEvaluate.

@SuppressWarnings("unchecked")
protected <T> void assertEvaluate(String functionExpression, Matcher<T> expectedValue, List<ColumnIdent> rowsColumnDescription, Object[]... inputRows) throws Throwable {
    performInputSanityChecks(inputRows);
    Symbol normalizedFunctionSymbol = sqlExpressions.normalize(sqlExpressions.asSymbol(functionExpression));
    assertThat(normalizedFunctionSymbol, instanceOf(io.crate.expression.symbol.WindowFunction.class));
    var windowFunctionSymbol = (io.crate.expression.symbol.WindowFunction) normalizedFunctionSymbol;
    ReferenceResolver<InputCollectExpression> referenceResolver = r -> new InputCollectExpression(rowsColumnDescription.indexOf(r.column()));
    var sourceSymbols = Lists2.map(rowsColumnDescription, x -> sqlExpressions.normalize(sqlExpressions.asSymbol(x.sqlFqn())));
    ensureInputRowsHaveCorrectType(sourceSymbols, inputRows);
    var argsCtx = inputFactory.ctxForRefs(txnCtx, referenceResolver);
    argsCtx.add(windowFunctionSymbol.arguments());
    FunctionImplementation impl = sqlExpressions.nodeCtx.functions().getQualified(windowFunctionSymbol, txnCtx.sessionSettings().searchPath());
    assert impl instanceof WindowFunction || impl instanceof AggregationFunction : "Got " + impl + " but expected a window function";
    WindowFunction windowFunctionImpl;
    if (impl instanceof AggregationFunction) {
        windowFunctionImpl = new AggregateToWindowFunctionAdapter((AggregationFunction) impl, new ExpressionsInput<>(Literal.BOOLEAN_TRUE, List.of()), Version.CURRENT, RamAccounting.NO_ACCOUNTING, memoryManager, Version.CURRENT);
    } else {
        windowFunctionImpl = (WindowFunction) impl;
    }
    int numCellsInSourceRows = inputRows[0].length;
    var windowDef = windowFunctionSymbol.windowDefinition();
    var partitionOrderBy = windowDef.partitions().isEmpty() ? null : new OrderBy(windowDef.partitions());
    Comparator<Object[]> cmpOrderBy = createComparator(() -> inputFactory.ctxForRefs(txnCtx, referenceResolver), windowDef.orderBy());
    InputColumns.SourceSymbols inputColSources = new InputColumns.SourceSymbols(sourceSymbols);
    var mappedWindowDef = windowDef.map(s -> InputColumns.create(s, inputColSources));
    BatchIterator<Row> iterator = WindowFunctionBatchIterator.of(InMemoryBatchIterator.of(Arrays.stream(inputRows).map(RowN::new).collect(Collectors.toList()), SENTINEL, true), new IgnoreRowAccounting(), WindowProjector.createComputeStartFrameBoundary(numCellsInSourceRows, txnCtx, sqlExpressions.nodeCtx, mappedWindowDef, cmpOrderBy), WindowProjector.createComputeEndFrameBoundary(numCellsInSourceRows, txnCtx, sqlExpressions.nodeCtx, mappedWindowDef, cmpOrderBy), createComparator(() -> inputFactory.ctxForRefs(txnCtx, referenceResolver), partitionOrderBy), cmpOrderBy, numCellsInSourceRows, () -> 1, Runnable::run, List.of(windowFunctionImpl), argsCtx.expressions(), new Boolean[] { windowFunctionSymbol.ignoreNulls() }, argsCtx.topLevelInputs().toArray(new Input[0]));
    List<Object> actualResult;
    try {
        actualResult = BatchIterators.collect(iterator, Collectors.mapping(row -> row.get(numCellsInSourceRows), Collectors.toList())).get(5, TimeUnit.SECONDS);
    } catch (ExecutionException e) {
        throw e.getCause();
    }
    assertThat((T) actualResult, expectedValue);
}
Also used : Input(io.crate.data.Input) TransactionContext(io.crate.metadata.TransactionContext) SqlExpressions(io.crate.testing.SqlExpressions) Arrays(java.util.Arrays) Array(java.lang.reflect.Array) RelationName(io.crate.metadata.RelationName) SENTINEL(io.crate.data.SentinelRow.SENTINEL) BatchIterator(io.crate.data.BatchIterator) ReferenceResolver(io.crate.expression.reference.ReferenceResolver) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) RowN(io.crate.data.RowN) Map(java.util.Map) SQLExecutor(io.crate.testing.SQLExecutor) Before(org.junit.Before) DocTableInfo(io.crate.metadata.doc.DocTableInfo) User(io.crate.user.User) AbstractModule(org.elasticsearch.common.inject.AbstractModule) AggregationFunction(io.crate.execution.engine.aggregation.AggregationFunction) InMemoryBatchIterator(io.crate.data.InMemoryBatchIterator) ColumnIdent(io.crate.metadata.ColumnIdent) Comparators.createComparator(io.crate.execution.engine.sort.Comparators.createComparator) RamAccounting(io.crate.breaker.RamAccounting) Collectors(java.util.stream.Collectors) Lists2(io.crate.common.collections.Lists2) InputCollectExpression(io.crate.execution.engine.collect.InputCollectExpression) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ExpressionsInput(io.crate.expression.ExpressionsInput) List(java.util.List) OrderBy(io.crate.analyze.OrderBy) BatchIterators(io.crate.data.BatchIterators) Version(org.elasticsearch.Version) DocTableRelation(io.crate.analyze.relations.DocTableRelation) Row(io.crate.data.Row) Literal(io.crate.expression.symbol.Literal) Symbol(io.crate.expression.symbol.Symbol) FunctionImplementation(io.crate.metadata.FunctionImplementation) Matcher(org.hamcrest.Matcher) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) InputColumns(io.crate.execution.dsl.projection.builder.InputColumns) OnHeapMemoryManager(io.crate.memory.OnHeapMemoryManager) InputFactory(io.crate.expression.InputFactory) Comparator(java.util.Comparator) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) Symbol(io.crate.expression.symbol.Symbol) AggregationFunction(io.crate.execution.engine.aggregation.AggregationFunction) Input(io.crate.data.Input) ExpressionsInput(io.crate.expression.ExpressionsInput) InputCollectExpression(io.crate.execution.engine.collect.InputCollectExpression) FunctionImplementation(io.crate.metadata.FunctionImplementation) ExecutionException(java.util.concurrent.ExecutionException) OrderBy(io.crate.analyze.OrderBy) InputColumns(io.crate.execution.dsl.projection.builder.InputColumns) Row(io.crate.data.Row) ExpressionsInput(io.crate.expression.ExpressionsInput)

Example 32 with OrderBy

use of io.crate.analyze.OrderBy in project crate by crate.

the class RoutedCollectPhaseTest method testNormalizeDoesNotRemoveOrderBy.

@Test
public void testNormalizeDoesNotRemoveOrderBy() throws Exception {
    Symbol toInt10 = CastFunctionResolver.generateCastFunction(Literal.of(10L), DataTypes.INTEGER);
    RoutedCollectPhase collect = new RoutedCollectPhase(UUID.randomUUID(), 1, "collect", new Routing(Collections.emptyMap()), RowGranularity.DOC, Collections.singletonList(toInt10), Collections.emptyList(), WhereClause.MATCH_ALL.queryOrFallback(), DistributionInfo.DEFAULT_SAME_NODE);
    collect.orderBy(new OrderBy(Collections.singletonList(toInt10)));
    EvaluatingNormalizer normalizer = EvaluatingNormalizer.functionOnlyNormalizer(nodeCtx);
    RoutedCollectPhase normalizedCollect = collect.normalize(normalizer, new CoordinatorTxnCtx(SessionContext.systemSessionContext()));
    assertThat(normalizedCollect.orderBy(), notNullValue());
}
Also used : OrderBy(io.crate.analyze.OrderBy) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) Symbol(io.crate.expression.symbol.Symbol) Routing(io.crate.metadata.Routing) RoutedCollectPhase(io.crate.execution.dsl.phases.RoutedCollectPhase) Test(org.junit.Test)

Example 33 with OrderBy

use of io.crate.analyze.OrderBy in project crate by crate.

the class PositionalOrderByTest method testNewOutputMapping.

@Test
public void testNewOutputMapping() throws Exception {
    List<Symbol> oldOutputs = Arrays.asList(ref("a"), ref("b"), ref("c"), ref("d"));
    List<Symbol> newOutputs = Arrays.asList(ref("b"), ref("c"), ref("d"), ref("a"));
    OrderBy orderBy = new OrderBy(Arrays.asList(ref("a"), ref("c"), ref("b")), new boolean[] { true, false, true }, new boolean[] { true, false, false });
    PositionalOrderBy positionalOrderBy = PositionalOrderBy.of(orderBy, oldOutputs);
    PositionalOrderBy newOrderBy = positionalOrderBy.tryMapToNewOutputs(oldOutputs, newOutputs);
    PositionalOrderBy expected = PositionalOrderBy.of(orderBy, newOutputs);
    assertThat(newOrderBy.indices(), Matchers.is(expected.indices()));
    assertThat(newOrderBy.reverseFlags(), Matchers.is(expected.reverseFlags()));
    assertThat(newOrderBy.nullsFirst(), Matchers.is(expected.nullsFirst()));
}
Also used : OrderBy(io.crate.analyze.OrderBy) Symbol(io.crate.expression.symbol.Symbol) Test(org.junit.Test)

Example 34 with OrderBy

use of io.crate.analyze.OrderBy in project crate by crate.

the class OrderByAnalyzerTest method analyzeSortItems.

@Test
public void analyzeSortItems() {
    List<SortItem> sortItems = new ArrayList<>(2);
    QualifiedName tx = QualifiedName.of("t", "x");
    SortItem firstSort = new SortItem(new QualifiedNameReference(tx), SortItem.Ordering.ASCENDING, SortItem.NullOrdering.FIRST);
    sortItems.add(firstSort);
    QualifiedName ty = QualifiedName.of("t", "y");
    SortItem second = new SortItem(new QualifiedNameReference(ty), SortItem.Ordering.DESCENDING, SortItem.NullOrdering.LAST);
    sortItems.add(second);
    OrderBy orderBy = OrderyByAnalyzer.analyzeSortItems(sortItems, e -> Literal.of(((QualifiedNameReference) e).getName().toString()));
    assertThat(orderBy, is(notNullValue()));
    List<Symbol> orderBySymbols = orderBy.orderBySymbols();
    assertThat(orderBySymbols.size(), is(2));
    assertThat(orderBySymbols.get(0), SymbolMatchers.isLiteral("t.x"));
    assertThat(orderBySymbols.get(1), SymbolMatchers.isLiteral("t.y"));
    boolean[] reverseFlags = orderBy.reverseFlags();
    assertThat(reverseFlags.length, is(2));
    assertThat(reverseFlags[0], is(false));
    assertThat(reverseFlags[1], is(true));
    boolean[] nullsFirst = orderBy.nullsFirst();
    assertThat(nullsFirst.length, is(2));
    assertThat(nullsFirst[0], is(true));
    assertThat(nullsFirst[1], is(false));
}
Also used : OrderBy(io.crate.analyze.OrderBy) SortItem(io.crate.sql.tree.SortItem) Symbol(io.crate.expression.symbol.Symbol) QualifiedName(io.crate.sql.tree.QualifiedName) ArrayList(java.util.ArrayList) QualifiedNameReference(io.crate.sql.tree.QualifiedNameReference) Test(org.junit.Test)

Example 35 with OrderBy

use of io.crate.analyze.OrderBy in project crate by crate.

the class ShardCollectSource method getCollector.

@Override
public CrateCollector getCollector(CollectPhase phase, BatchConsumer lastConsumer, JobCollectContext jobCollectContext) {
    RoutedCollectPhase collectPhase = (RoutedCollectPhase) phase;
    RoutedCollectPhase normalizedPhase = collectPhase.normalize(nodeNormalizer, null);
    String localNodeId = clusterService.localNode().getId();
    BatchConsumer firstConsumer = ProjectingBatchConsumer.create(lastConsumer, Projections.nodeProjections(normalizedPhase.projections()), collectPhase.jobId(), jobCollectContext.queryPhaseRamAccountingContext(), sharedProjectorFactory);
    if (normalizedPhase.maxRowGranularity() == RowGranularity.SHARD) {
        // The getShardsCollector method always only uses a single RowReceiver and not one per shard)
        return getShardsCollector(collectPhase, normalizedPhase, localNodeId, firstConsumer);
    }
    OrderBy orderBy = normalizedPhase.orderBy();
    if (normalizedPhase.maxRowGranularity() == RowGranularity.DOC && orderBy != null) {
        return createMultiShardScoreDocCollector(normalizedPhase, firstConsumer, jobCollectContext, localNodeId);
    }
    // actual shards might be less if table is partitioned and a partition has been deleted meanwhile
    final int maxNumShards = normalizedPhase.routing().numShards(localNodeId);
    boolean hasShardProjections = Projections.hasAnyShardProjections(normalizedPhase.projections());
    Map<String, Map<String, List<Integer>>> locations = normalizedPhase.routing().locations();
    final List<CrateCollector.Builder> builders = new ArrayList<>(maxNumShards);
    Map<String, List<Integer>> indexShards = locations.get(localNodeId);
    if (indexShards != null) {
        builders.addAll(getDocCollectors(jobCollectContext, normalizedPhase, lastConsumer.requiresScroll(), indexShards));
    }
    switch(builders.size()) {
        case 0:
            return RowsCollector.empty(firstConsumer);
        case 1:
            CrateCollector.Builder collectorBuilder = builders.iterator().next();
            return collectorBuilder.build(collectorBuilder.applyProjections(firstConsumer));
        default:
            if (hasShardProjections) {
                // in order to process shard-based projections concurrently
                return new CompositeCollector(builders, firstConsumer, iterators -> new AsyncCompositeBatchIterator(executor, iterators));
            } else {
                return new CompositeCollector(builders, firstConsumer, CompositeBatchIterator::new);
            }
    }
}
Also used : OrderBy(io.crate.analyze.OrderBy) CompositeCollector(io.crate.operation.collect.collectors.CompositeCollector) LuceneQueryBuilder(io.crate.lucene.LuceneQueryBuilder) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) RoutedCollectPhase(io.crate.planner.node.dql.RoutedCollectPhase) ProjectingBatchConsumer(io.crate.operation.projectors.ProjectingBatchConsumer)

Aggregations

OrderBy (io.crate.analyze.OrderBy)64 Test (org.junit.Test)29 Symbol (io.crate.expression.symbol.Symbol)16 ArrayList (java.util.ArrayList)14 QuerySpec (io.crate.analyze.QuerySpec)13 List (java.util.List)13 Row (io.crate.data.Row)12 Reference (io.crate.metadata.Reference)10 Nullable (javax.annotation.Nullable)9 QueriedDocTable (io.crate.analyze.relations.QueriedDocTable)8 CrateDummyClusterServiceUnitTest (io.crate.test.integration.CrateDummyClusterServiceUnitTest)8 Map (java.util.Map)8 ShardId (org.elasticsearch.index.shard.ShardId)8 Symbol (io.crate.analyze.symbol.Symbol)7 InputFactory (io.crate.expression.InputFactory)7 RelationName (io.crate.metadata.RelationName)7 WindowDefinition (io.crate.analyze.WindowDefinition)6 TransactionContext (io.crate.metadata.TransactionContext)6 DataType (io.crate.types.DataType)6 Lists2 (io.crate.common.collections.Lists2)5