Search in sources :

Example 1 with Intervals

use of org.apache.druid.java.util.common.Intervals in project druid by druid-io.

the class SqlSegmentsMetadataQuery method retrieveSegments.

private CloseableIterator<DataSegment> retrieveSegments(final String dataSource, final Collection<Interval> intervals, final IntervalMode matchMode, final boolean used) {
    // Check if the intervals all support comparing as strings. If so, bake them into the SQL.
    final boolean compareAsString = intervals.stream().allMatch(Intervals::canCompareEndpointsAsStrings);
    final StringBuilder sb = new StringBuilder();
    sb.append("SELECT payload FROM %s WHERE used = :used AND dataSource = :dataSource");
    if (compareAsString && !intervals.isEmpty()) {
        sb.append(" AND (");
        for (int i = 0; i < intervals.size(); i++) {
            sb.append(matchMode.makeSqlCondition(connector.getQuoteString(), StringUtils.format(":start%d", i), StringUtils.format(":end%d", i)));
            if (i == intervals.size() - 1) {
                sb.append(")");
            } else {
                sb.append(" OR ");
            }
        }
    }
    final Query<Map<String, Object>> sql = handle.createQuery(StringUtils.format(sb.toString(), dbTables.getSegmentsTable())).setFetchSize(connector.getStreamingFetchSize()).bind("used", used).bind("dataSource", dataSource);
    if (compareAsString) {
        final Iterator<Interval> iterator = intervals.iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            Interval interval = iterator.next();
            sql.bind(StringUtils.format("start%d", i), interval.getStart().toString()).bind(StringUtils.format("end%d", i), interval.getEnd().toString());
        }
    }
    final ResultIterator<DataSegment> resultIterator = sql.map((index, r, ctx) -> JacksonUtils.readValue(jsonMapper, r.getBytes(1), DataSegment.class)).iterator();
    return CloseableIterators.wrap(Iterators.filter(resultIterator, dataSegment -> {
        if (intervals.isEmpty()) {
            return true;
        } else {
            // segment interval like "20010/20011".)
            for (Interval interval : intervals) {
                if (matchMode.apply(interval, dataSegment.getInterval())) {
                    return true;
                }
            }
            return false;
        }
    }), resultIterator);
}
Also used : Intervals(org.apache.druid.java.util.common.Intervals) Logger(org.apache.druid.java.util.common.logger.Logger) JacksonUtils(org.apache.druid.java.util.common.jackson.JacksonUtils) Iterator(java.util.Iterator) Intervals(org.apache.druid.java.util.common.Intervals) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) StringUtils(org.apache.druid.java.util.common.StringUtils) Query(org.skife.jdbi.v2.Query) Collectors(java.util.stream.Collectors) Iterators(com.google.common.collect.Iterators) Interval(org.joda.time.Interval) List(java.util.List) CloseableIterators(org.apache.druid.java.util.common.CloseableIterators) Handle(org.skife.jdbi.v2.Handle) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) DataSegment(org.apache.druid.timeline.DataSegment) ResultIterator(org.skife.jdbi.v2.ResultIterator) PreparedBatch(org.skife.jdbi.v2.PreparedBatch) IAE(org.apache.druid.java.util.common.IAE) SegmentId(org.apache.druid.timeline.SegmentId) CloseableIterator(org.apache.druid.java.util.common.parsers.CloseableIterator) Collections(java.util.Collections) Map(java.util.Map) DataSegment(org.apache.druid.timeline.DataSegment) Interval(org.joda.time.Interval)

Example 2 with Intervals

use of org.apache.druid.java.util.common.Intervals in project druid by druid-io.

the class TimeseriesQueryRunnerTest method testTimeseriesWithTimestampResultFieldContextForMapResponse.

@Test
public void testTimeseriesWithTimestampResultFieldContextForMapResponse() {
    Granularity gran = Granularities.DAY;
    TimeseriesQuery query = Druids.newTimeseriesQueryBuilder().dataSource(QueryRunnerTestHelper.DATA_SOURCE).granularity(gran).intervals(QueryRunnerTestHelper.FULL_ON_INTERVAL_SPEC).aggregators(QueryRunnerTestHelper.ROWS_COUNT, QueryRunnerTestHelper.INDEX_DOUBLE_SUM, QueryRunnerTestHelper.QUALITY_UNIQUES).postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT).descending(descending).context(makeContext(ImmutableMap.of(TimeseriesQuery.CTX_TIMESTAMP_RESULT_FIELD, TIMESTAMP_RESULT_FIELD_NAME, TimeseriesQuery.SKIP_EMPTY_BUCKETS, true))).build();
    Assert.assertEquals(TIMESTAMP_RESULT_FIELD_NAME, query.getTimestampResultField());
    Iterable<Result<TimeseriesResultValue>> results = runner.run(QueryPlus.wrap(query)).toList();
    final String[] expectedIndex = descending ? QueryRunnerTestHelper.EXPECTED_FULL_ON_INDEX_VALUES_DESC : QueryRunnerTestHelper.EXPECTED_FULL_ON_INDEX_VALUES;
    final String[] expectedIndexToUse = Arrays.stream(expectedIndex).filter(eachIndex -> !"0.0".equals(eachIndex)).toArray(String[]::new);
    final DateTime expectedLast = descending ? QueryRunnerTestHelper.EARLIEST : QueryRunnerTestHelper.LAST;
    int count = 0;
    Result lastResult = null;
    for (Result<TimeseriesResultValue> result : results) {
        DateTime current = result.getTimestamp();
        Assert.assertFalse(StringUtils.format("Timestamp[%s] > expectedLast[%s]", current, expectedLast), descending ? current.isBefore(expectedLast) : current.isAfter(expectedLast));
        final TimeseriesResultValue value = result.getValue();
        Assert.assertEquals(value.getLongMetric(TIMESTAMP_RESULT_FIELD_NAME), current.getMillis(), 0);
        Assert.assertEquals(result.toString(), QueryRunnerTestHelper.SKIPPED_DAY.equals(current) ? 0L : 13L, value.getLongMetric("rows").longValue());
        if (!QueryRunnerTestHelper.SKIPPED_DAY.equals(current)) {
            Assert.assertEquals(result.toString(), Doubles.tryParse(expectedIndexToUse[count]).doubleValue(), value.getDoubleMetric("index").doubleValue(), value.getDoubleMetric("index").doubleValue() * 1e-6);
            Assert.assertEquals(result.toString(), new Double(expectedIndexToUse[count]) + 13L + 1L, value.getDoubleMetric("addRowsIndexConstant"), value.getDoubleMetric("addRowsIndexConstant") * 1e-6);
            Assert.assertEquals(value.getDoubleMetric("uniques"), 9.0d, 0.02);
        } else {
            if (NullHandling.replaceWithDefault()) {
                Assert.assertEquals(result.toString(), 0.0D, value.getDoubleMetric("index").doubleValue(), value.getDoubleMetric("index").doubleValue() * 1e-6);
                Assert.assertEquals(result.toString(), new Double(expectedIndexToUse[count]) + 1L, value.getDoubleMetric("addRowsIndexConstant"), value.getDoubleMetric("addRowsIndexConstant") * 1e-6);
                Assert.assertEquals(0.0D, value.getDoubleMetric("uniques"), 0.02);
            } else {
                Assert.assertNull(result.toString(), value.getDoubleMetric("index"));
                Assert.assertNull(result.toString(), value.getDoubleMetric("addRowsIndexConstant"));
                Assert.assertEquals(value.getDoubleMetric("uniques"), 0.0d, 0.02);
            }
        }
        lastResult = result;
        ++count;
    }
    Assert.assertEquals(lastResult.toString(), expectedLast, lastResult.getTimestamp());
}
Also used : QueryPlus(org.apache.druid.query.QueryPlus) DateTimeZone(org.joda.time.DateTimeZone) Arrays(java.util.Arrays) DefaultDimensionSpec(org.apache.druid.query.dimension.DefaultDimensionSpec) Druids(org.apache.druid.query.Druids) LongSumAggregatorFactory(org.apache.druid.query.aggregation.LongSumAggregatorFactory) SelectorDimFilter(org.apache.druid.query.filter.SelectorDimFilter) PeriodGranularity(org.apache.druid.java.util.common.granularity.PeriodGranularity) Map(java.util.Map) QueryRunner(org.apache.druid.query.QueryRunner) Parameterized(org.junit.runners.Parameterized) AndDimFilter(org.apache.druid.query.filter.AndDimFilter) DateTimes(org.apache.druid.java.util.common.DateTimes) Sequence(org.apache.druid.java.util.common.guava.Sequence) FinalizeResultsQueryRunner(org.apache.druid.query.FinalizeResultsQueryRunner) RegexDimFilter(org.apache.druid.query.filter.RegexDimFilter) HyperUniquesAggregatorFactory(org.apache.druid.query.aggregation.hyperloglog.HyperUniquesAggregatorFactory) ImmutableSet(com.google.common.collect.ImmutableSet) NotDimFilter(org.apache.druid.query.filter.NotDimFilter) ImmutableMap(com.google.common.collect.ImmutableMap) AggregatorFactory(org.apache.druid.query.aggregation.AggregatorFactory) StringUtils(org.apache.druid.java.util.common.StringUtils) TestExprMacroTable(org.apache.druid.query.expression.TestExprMacroTable) Collectors(java.util.stream.Collectors) QueryContexts(org.apache.druid.query.QueryContexts) List(java.util.List) QueryRunnerTestHelper(org.apache.druid.query.QueryRunnerTestHelper) Doubles(com.google.common.primitives.Doubles) DoubleFirstAggregatorFactory(org.apache.druid.query.aggregation.first.DoubleFirstAggregatorFactory) DoubleLastAggregatorFactory(org.apache.druid.query.aggregation.last.DoubleLastAggregatorFactory) Iterables(com.google.common.collect.Iterables) DoubleSumAggregatorFactory(org.apache.druid.query.aggregation.DoubleSumAggregatorFactory) Granularity(org.apache.druid.java.util.common.granularity.Granularity) Intervals(org.apache.druid.java.util.common.Intervals) FilteredAggregatorFactory(org.apache.druid.query.aggregation.FilteredAggregatorFactory) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MapLookupExtractor(org.apache.druid.query.extraction.MapLookupExtractor) HumanReadableBytes(org.apache.druid.java.util.common.HumanReadableBytes) Interval(org.joda.time.Interval) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) LookupExtractionFn(org.apache.druid.query.lookup.LookupExtractionFn) DoubleMinAggregatorFactory(org.apache.druid.query.aggregation.DoubleMinAggregatorFactory) StringComparators(org.apache.druid.query.ordering.StringComparators) MultipleIntervalSegmentSpec(org.apache.druid.query.spec.MultipleIntervalSegmentSpec) StreamSupport(java.util.stream.StreamSupport) BoundDimFilter(org.apache.druid.query.filter.BoundDimFilter) ExpressionVirtualColumn(org.apache.druid.segment.virtual.ExpressionVirtualColumn) ExpectedException(org.junit.rules.ExpectedException) CountAggregatorFactory(org.apache.druid.query.aggregation.CountAggregatorFactory) DoubleMaxAggregatorFactory(org.apache.druid.query.aggregation.DoubleMaxAggregatorFactory) CardinalityAggregatorFactory(org.apache.druid.query.aggregation.cardinality.CardinalityAggregatorFactory) Period(org.joda.time.Period) ExpressionLambdaAggregatorFactory(org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory) DateTime(org.joda.time.DateTime) QueryToolChest(org.apache.druid.query.QueryToolChest) InitializedNullHandlingTest(org.apache.druid.testing.InitializedNullHandlingTest) Test(org.junit.Test) Granularities(org.apache.druid.java.util.common.granularity.Granularities) Result(org.apache.druid.query.Result) TestHelper(org.apache.druid.segment.TestHelper) Rule(org.junit.Rule) NullHandling(org.apache.druid.common.config.NullHandling) RowSignature(org.apache.druid.segment.column.RowSignature) FieldAccessPostAggregator(org.apache.druid.query.aggregation.post.FieldAccessPostAggregator) ColumnType(org.apache.druid.segment.column.ColumnType) FloatSumAggregatorFactory(org.apache.druid.query.aggregation.FloatSumAggregatorFactory) InDimFilter(org.apache.druid.query.filter.InDimFilter) OrDimFilter(org.apache.druid.query.filter.OrDimFilter) Assert(org.junit.Assert) Collections(java.util.Collections) PeriodGranularity(org.apache.druid.java.util.common.granularity.PeriodGranularity) Granularity(org.apache.druid.java.util.common.granularity.Granularity) DateTime(org.joda.time.DateTime) Result(org.apache.druid.query.Result) InitializedNullHandlingTest(org.apache.druid.testing.InitializedNullHandlingTest) Test(org.junit.Test)

Example 3 with Intervals

use of org.apache.druid.java.util.common.Intervals in project druid by druid-io.

the class TopNQueryRunnerTest method testTopNBySegment.

@Test
public void testTopNBySegment() {
    final HashMap<String, Object> specialContext = new HashMap<String, Object>();
    specialContext.put(QueryContexts.BY_SEGMENT_KEY, "true");
    TopNQuery query = new TopNQueryBuilder().dataSource(QueryRunnerTestHelper.DATA_SOURCE).granularity(QueryRunnerTestHelper.ALL_GRAN).dimension(QueryRunnerTestHelper.MARKET_DIMENSION).metric(QueryRunnerTestHelper.INDEX_METRIC).threshold(4).intervals(QueryRunnerTestHelper.FIRST_TO_THIRD).aggregators(commonAggregators).postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT).context(specialContext).build();
    List<Result<TopNResultValue>> expectedResults = Collections.singletonList(new Result<>(DateTimes.of("2011-04-01T00:00:00.000Z"), new TopNResultValue(Arrays.<Map<String, Object>>asList(ImmutableMap.of("addRowsIndexConstant", 5356.814783D, "index", 5351.814783D, QueryRunnerTestHelper.MARKET_DIMENSION, "total_market", "uniques", QueryRunnerTestHelper.UNIQUES_2, "rows", 4L), ImmutableMap.of("addRowsIndexConstant", 4880.669692D, "index", 4875.669692D, QueryRunnerTestHelper.MARKET_DIMENSION, "upfront", "uniques", QueryRunnerTestHelper.UNIQUES_2, "rows", 4L), ImmutableMap.of("addRowsIndexConstant", 2250.876812D, "index", 2231.876812D, QueryRunnerTestHelper.MARKET_DIMENSION, "spot", "uniques", QueryRunnerTestHelper.UNIQUES_9, "rows", 18L)))));
    Sequence<Result<TopNResultValue>> results = runWithMerge(query);
    List<Result<BySegmentTopNResultValue>> resultList = results.map((Result<TopNResultValue> input) -> {
        // Stupid type erasure
        Object val = input.getValue();
        if (val instanceof BySegmentResultValue) {
            BySegmentResultValue bySegVal = (BySegmentResultValue) val;
            return new Result<>(input.getTimestamp(), new BySegmentTopNResultValue(Lists.transform(bySegVal.getResults(), res -> {
                if (Preconditions.checkNotNull(res) instanceof Result) {
                    Result theResult = (Result) res;
                    Object resVal = theResult.getValue();
                    if (resVal instanceof TopNResultValue) {
                        return new Result<>(theResult.getTimestamp(), (TopNResultValue) resVal);
                    }
                }
                throw new IAE("Bad input: [%s]", res);
            }), bySegVal.getSegmentId(), bySegVal.getInterval()));
        }
        throw new ISE("Bad type");
    }).toList();
    Result<BySegmentTopNResultValue> result = resultList.get(0);
    TestHelper.assertExpectedResults(expectedResults, result.getValue().getResults());
}
Also used : QueryPlus(org.apache.druid.query.QueryPlus) Arrays(java.util.Arrays) ExtractionFn(org.apache.druid.query.extraction.ExtractionFn) ByteBuffer(java.nio.ByteBuffer) Pair(org.apache.druid.java.util.common.Pair) DefaultDimensionSpec(org.apache.druid.query.dimension.DefaultDimensionSpec) DimExtractionFn(org.apache.druid.query.extraction.DimExtractionFn) LongSumAggregatorFactory(org.apache.druid.query.aggregation.LongSumAggregatorFactory) SelectorDimFilter(org.apache.druid.query.filter.SelectorDimFilter) Map(java.util.Map) QueryRunner(org.apache.druid.query.QueryRunner) IAE(org.apache.druid.java.util.common.IAE) ExtractionDimensionSpec(org.apache.druid.query.dimension.ExtractionDimensionSpec) Parameterized(org.junit.runners.Parameterized) AndDimFilter(org.apache.druid.query.filter.AndDimFilter) DateTimes(org.apache.druid.java.util.common.DateTimes) Sequence(org.apache.druid.java.util.common.guava.Sequence) FinalizeResultsQueryRunner(org.apache.druid.query.FinalizeResultsQueryRunner) Longs(com.google.common.primitives.Longs) HyperUniquesAggregatorFactory(org.apache.druid.query.aggregation.hyperloglog.HyperUniquesAggregatorFactory) AfterClass(org.junit.AfterClass) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Closer(org.apache.druid.java.util.common.io.Closer) AggregatorFactory(org.apache.druid.query.aggregation.AggregatorFactory) FloatMaxAggregatorFactory(org.apache.druid.query.aggregation.FloatMaxAggregatorFactory) ISE(org.apache.druid.java.util.common.ISE) TestExprMacroTable(org.apache.druid.query.expression.TestExprMacroTable) HyperUniqueFinalizingPostAggregator(org.apache.druid.query.aggregation.hyperloglog.HyperUniqueFinalizingPostAggregator) FloatLastAggregatorFactory(org.apache.druid.query.aggregation.last.FloatLastAggregatorFactory) RegexDimExtractionFn(org.apache.druid.query.extraction.RegexDimExtractionFn) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) QueryContexts(org.apache.druid.query.QueryContexts) ExprMacroTable(org.apache.druid.math.expr.ExprMacroTable) BySegmentResultValue(org.apache.druid.query.BySegmentResultValue) BySegmentResultValueClass(org.apache.druid.query.BySegmentResultValueClass) List(java.util.List) StringFormatExtractionFn(org.apache.druid.query.extraction.StringFormatExtractionFn) CloseableStupidPool(org.apache.druid.collections.CloseableStupidPool) ExpressionPostAggregator(org.apache.druid.query.aggregation.post.ExpressionPostAggregator) DimFilter(org.apache.druid.query.filter.DimFilter) QueryRunnerTestHelper(org.apache.druid.query.QueryRunnerTestHelper) DimensionSpec(org.apache.druid.query.dimension.DimensionSpec) Doubles(com.google.common.primitives.Doubles) DoubleFirstAggregatorFactory(org.apache.druid.query.aggregation.first.DoubleFirstAggregatorFactory) Iterables(com.google.common.collect.Iterables) DoubleSumAggregatorFactory(org.apache.druid.query.aggregation.DoubleSumAggregatorFactory) Intervals(org.apache.druid.java.util.common.Intervals) JavaScriptExtractionFn(org.apache.druid.query.extraction.JavaScriptExtractionFn) FilteredAggregatorFactory(org.apache.druid.query.aggregation.FilteredAggregatorFactory) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) JavaScriptConfig(org.apache.druid.js.JavaScriptConfig) ArrayList(java.util.ArrayList) MapLookupExtractor(org.apache.druid.query.extraction.MapLookupExtractor) Lists(com.google.common.collect.Lists) ColumnHolder(org.apache.druid.segment.column.ColumnHolder) ImmutableList(com.google.common.collect.ImmutableList) LookupExtractionFn(org.apache.druid.query.lookup.LookupExtractionFn) DoubleMinAggregatorFactory(org.apache.druid.query.aggregation.DoubleMinAggregatorFactory) TestQueryRunners(org.apache.druid.query.TestQueryRunners) LongLastAggregatorFactory(org.apache.druid.query.aggregation.last.LongLastAggregatorFactory) StringComparators(org.apache.druid.query.ordering.StringComparators) LongFirstAggregatorFactory(org.apache.druid.query.aggregation.first.LongFirstAggregatorFactory) MultipleIntervalSegmentSpec(org.apache.druid.query.spec.MultipleIntervalSegmentSpec) FloatMinAggregatorFactory(org.apache.druid.query.aggregation.FloatMinAggregatorFactory) ListFilteredDimensionSpec(org.apache.druid.query.dimension.ListFilteredDimensionSpec) BoundDimFilter(org.apache.druid.query.filter.BoundDimFilter) ExpressionVirtualColumn(org.apache.druid.segment.virtual.ExpressionVirtualColumn) ExpectedException(org.junit.rules.ExpectedException) CountAggregatorFactory(org.apache.druid.query.aggregation.CountAggregatorFactory) FloatFirstAggregatorFactory(org.apache.druid.query.aggregation.first.FloatFirstAggregatorFactory) Nullable(javax.annotation.Nullable) DoubleMaxAggregatorFactory(org.apache.druid.query.aggregation.DoubleMaxAggregatorFactory) CardinalityAggregatorFactory(org.apache.druid.query.aggregation.cardinality.CardinalityAggregatorFactory) ExpressionLambdaAggregatorFactory(org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory) ResponseContext(org.apache.druid.query.context.ResponseContext) TimeFormatExtractionFn(org.apache.druid.query.extraction.TimeFormatExtractionFn) InitializedNullHandlingTest(org.apache.druid.testing.InitializedNullHandlingTest) Test(org.junit.Test) IOException(java.io.IOException) ExtractionDimFilter(org.apache.druid.query.filter.ExtractionDimFilter) StrlenExtractionFn(org.apache.druid.query.extraction.StrlenExtractionFn) Granularities(org.apache.druid.java.util.common.granularity.Granularities) Result(org.apache.druid.query.Result) TestHelper(org.apache.druid.segment.TestHelper) Rule(org.junit.Rule) NullHandling(org.apache.druid.common.config.NullHandling) ColumnType(org.apache.druid.segment.column.ColumnType) Preconditions(com.google.common.base.Preconditions) Assert(org.junit.Assert) Collections(java.util.Collections) BySegmentResultValue(org.apache.druid.query.BySegmentResultValue) HashMap(java.util.HashMap) IAE(org.apache.druid.java.util.common.IAE) Result(org.apache.druid.query.Result) ISE(org.apache.druid.java.util.common.ISE) InitializedNullHandlingTest(org.apache.druid.testing.InitializedNullHandlingTest) Test(org.junit.Test)

Example 4 with Intervals

use of org.apache.druid.java.util.common.Intervals in project druid by druid-io.

the class TimeseriesQueryRunnerTest method testTimeseriesWithTimestampResultFieldContextForArrayResponse.

@Test
public void testTimeseriesWithTimestampResultFieldContextForArrayResponse() {
    Granularity gran = Granularities.DAY;
    TimeseriesQuery query = Druids.newTimeseriesQueryBuilder().dataSource(QueryRunnerTestHelper.DATA_SOURCE).granularity(gran).intervals(QueryRunnerTestHelper.FULL_ON_INTERVAL_SPEC).aggregators(QueryRunnerTestHelper.ROWS_COUNT, QueryRunnerTestHelper.INDEX_DOUBLE_SUM, QueryRunnerTestHelper.QUALITY_UNIQUES).postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT).descending(descending).context(makeContext(ImmutableMap.of(TimeseriesQuery.CTX_TIMESTAMP_RESULT_FIELD, TIMESTAMP_RESULT_FIELD_NAME, TimeseriesQuery.SKIP_EMPTY_BUCKETS, true))).build();
    Assert.assertEquals(TIMESTAMP_RESULT_FIELD_NAME, query.getTimestampResultField());
    QueryToolChest<Result<TimeseriesResultValue>, TimeseriesQuery> toolChest = new TimeseriesQueryQueryToolChest();
    RowSignature rowSignature = toolChest.resultArraySignature(query);
    Assert.assertNotNull(rowSignature);
    List<String> columnNames = rowSignature.getColumnNames();
    Assert.assertNotNull(columnNames);
    Assert.assertEquals(6, columnNames.size());
    Assert.assertEquals("__time", columnNames.get(0));
    Assert.assertEquals(TIMESTAMP_RESULT_FIELD_NAME, columnNames.get(1));
    Assert.assertEquals("rows", columnNames.get(2));
    Assert.assertEquals("index", columnNames.get(3));
    Assert.assertEquals("uniques", columnNames.get(4));
    Assert.assertEquals("addRowsIndexConstant", columnNames.get(5));
    Sequence<Result<TimeseriesResultValue>> results = runner.run(QueryPlus.wrap(query));
    Sequence<Object[]> resultsAsArrays = toolChest.resultsAsArrays(query, results);
    Assert.assertNotNull(resultsAsArrays);
    final String[] expectedIndex = descending ? QueryRunnerTestHelper.EXPECTED_FULL_ON_INDEX_VALUES_DESC : QueryRunnerTestHelper.EXPECTED_FULL_ON_INDEX_VALUES;
    final String[] expectedIndexToUse = Arrays.stream(expectedIndex).filter(eachIndex -> !"0.0".equals(eachIndex)).toArray(String[]::new);
    final Long expectedLast = descending ? QueryRunnerTestHelper.EARLIEST.getMillis() : QueryRunnerTestHelper.LAST.getMillis();
    int count = 0;
    Object[] lastResult = null;
    for (Object[] result : resultsAsArrays.toList()) {
        Long current = (Long) result[0];
        Assert.assertFalse(StringUtils.format("Timestamp[%s] > expectedLast[%s]", current, expectedLast), descending ? current < expectedLast : current > expectedLast);
        Assert.assertEquals((Long) result[1], current, 0);
        Assert.assertEquals(QueryRunnerTestHelper.SKIPPED_DAY.getMillis() == current ? (Long) 0L : (Long) 13L, result[2]);
        if (QueryRunnerTestHelper.SKIPPED_DAY.getMillis() != current) {
            Assert.assertEquals(Doubles.tryParse(expectedIndexToUse[count]).doubleValue(), (Double) result[3], (Double) result[3] * 1e-6);
            Assert.assertEquals((Double) result[4], 9.0d, 0.02);
            Assert.assertEquals(new Double(expectedIndexToUse[count]) + 13L + 1L, (Double) result[5], (Double) result[5] * 1e-6);
        } else {
            if (NullHandling.replaceWithDefault()) {
                Assert.assertEquals(0.0D, (Double) result[3], (Double) result[3] * 1e-6);
                Assert.assertEquals(0.0D, (Double) result[4], 0.02);
                Assert.assertEquals(new Double(expectedIndexToUse[count]) + 1L, (Double) result[5], (Double) result[5] * 1e-6);
            } else {
                Assert.assertNull(result[3]);
                Assert.assertEquals((Double) result[4], 0.0, 0.02);
                Assert.assertNull(result[5]);
            }
        }
        lastResult = result;
        ++count;
    }
    Assert.assertEquals(expectedLast, lastResult[0]);
}
Also used : QueryPlus(org.apache.druid.query.QueryPlus) DateTimeZone(org.joda.time.DateTimeZone) Arrays(java.util.Arrays) DefaultDimensionSpec(org.apache.druid.query.dimension.DefaultDimensionSpec) Druids(org.apache.druid.query.Druids) LongSumAggregatorFactory(org.apache.druid.query.aggregation.LongSumAggregatorFactory) SelectorDimFilter(org.apache.druid.query.filter.SelectorDimFilter) PeriodGranularity(org.apache.druid.java.util.common.granularity.PeriodGranularity) Map(java.util.Map) QueryRunner(org.apache.druid.query.QueryRunner) Parameterized(org.junit.runners.Parameterized) AndDimFilter(org.apache.druid.query.filter.AndDimFilter) DateTimes(org.apache.druid.java.util.common.DateTimes) Sequence(org.apache.druid.java.util.common.guava.Sequence) FinalizeResultsQueryRunner(org.apache.druid.query.FinalizeResultsQueryRunner) RegexDimFilter(org.apache.druid.query.filter.RegexDimFilter) HyperUniquesAggregatorFactory(org.apache.druid.query.aggregation.hyperloglog.HyperUniquesAggregatorFactory) ImmutableSet(com.google.common.collect.ImmutableSet) NotDimFilter(org.apache.druid.query.filter.NotDimFilter) ImmutableMap(com.google.common.collect.ImmutableMap) AggregatorFactory(org.apache.druid.query.aggregation.AggregatorFactory) StringUtils(org.apache.druid.java.util.common.StringUtils) TestExprMacroTable(org.apache.druid.query.expression.TestExprMacroTable) Collectors(java.util.stream.Collectors) QueryContexts(org.apache.druid.query.QueryContexts) List(java.util.List) QueryRunnerTestHelper(org.apache.druid.query.QueryRunnerTestHelper) Doubles(com.google.common.primitives.Doubles) DoubleFirstAggregatorFactory(org.apache.druid.query.aggregation.first.DoubleFirstAggregatorFactory) DoubleLastAggregatorFactory(org.apache.druid.query.aggregation.last.DoubleLastAggregatorFactory) Iterables(com.google.common.collect.Iterables) DoubleSumAggregatorFactory(org.apache.druid.query.aggregation.DoubleSumAggregatorFactory) Granularity(org.apache.druid.java.util.common.granularity.Granularity) Intervals(org.apache.druid.java.util.common.Intervals) FilteredAggregatorFactory(org.apache.druid.query.aggregation.FilteredAggregatorFactory) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MapLookupExtractor(org.apache.druid.query.extraction.MapLookupExtractor) HumanReadableBytes(org.apache.druid.java.util.common.HumanReadableBytes) Interval(org.joda.time.Interval) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) LookupExtractionFn(org.apache.druid.query.lookup.LookupExtractionFn) DoubleMinAggregatorFactory(org.apache.druid.query.aggregation.DoubleMinAggregatorFactory) StringComparators(org.apache.druid.query.ordering.StringComparators) MultipleIntervalSegmentSpec(org.apache.druid.query.spec.MultipleIntervalSegmentSpec) StreamSupport(java.util.stream.StreamSupport) BoundDimFilter(org.apache.druid.query.filter.BoundDimFilter) ExpressionVirtualColumn(org.apache.druid.segment.virtual.ExpressionVirtualColumn) ExpectedException(org.junit.rules.ExpectedException) CountAggregatorFactory(org.apache.druid.query.aggregation.CountAggregatorFactory) DoubleMaxAggregatorFactory(org.apache.druid.query.aggregation.DoubleMaxAggregatorFactory) CardinalityAggregatorFactory(org.apache.druid.query.aggregation.cardinality.CardinalityAggregatorFactory) Period(org.joda.time.Period) ExpressionLambdaAggregatorFactory(org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory) DateTime(org.joda.time.DateTime) QueryToolChest(org.apache.druid.query.QueryToolChest) InitializedNullHandlingTest(org.apache.druid.testing.InitializedNullHandlingTest) Test(org.junit.Test) Granularities(org.apache.druid.java.util.common.granularity.Granularities) Result(org.apache.druid.query.Result) TestHelper(org.apache.druid.segment.TestHelper) Rule(org.junit.Rule) NullHandling(org.apache.druid.common.config.NullHandling) RowSignature(org.apache.druid.segment.column.RowSignature) FieldAccessPostAggregator(org.apache.druid.query.aggregation.post.FieldAccessPostAggregator) ColumnType(org.apache.druid.segment.column.ColumnType) FloatSumAggregatorFactory(org.apache.druid.query.aggregation.FloatSumAggregatorFactory) InDimFilter(org.apache.druid.query.filter.InDimFilter) OrDimFilter(org.apache.druid.query.filter.OrDimFilter) Assert(org.junit.Assert) Collections(java.util.Collections) PeriodGranularity(org.apache.druid.java.util.common.granularity.PeriodGranularity) Granularity(org.apache.druid.java.util.common.granularity.Granularity) Result(org.apache.druid.query.Result) RowSignature(org.apache.druid.segment.column.RowSignature) InitializedNullHandlingTest(org.apache.druid.testing.InitializedNullHandlingTest) Test(org.junit.Test)

Example 5 with Intervals

use of org.apache.druid.java.util.common.Intervals in project druid by druid-io.

the class CompactSegmentsTest method testRunWithLockedIntervalsNoSkip.

@Test
public void testRunWithLockedIntervalsNoSkip() {
    Mockito.when(COORDINATOR_CONFIG.getCompactionSkipLockedIntervals()).thenReturn(false);
    final TestDruidLeaderClient leaderClient = new TestDruidLeaderClient(JSON_MAPPER);
    leaderClient.start();
    HttpIndexingServiceClient indexingServiceClient = new HttpIndexingServiceClient(JSON_MAPPER, leaderClient);
    // Lock all intervals for all the dataSources
    final String datasource0 = DATA_SOURCE_PREFIX + 0;
    leaderClient.lockedIntervals.computeIfAbsent(datasource0, k -> new ArrayList<>()).add(Intervals.of("2017/2018"));
    final String datasource1 = DATA_SOURCE_PREFIX + 1;
    leaderClient.lockedIntervals.computeIfAbsent(datasource1, k -> new ArrayList<>()).add(Intervals.of("2017/2018"));
    final String datasource2 = DATA_SOURCE_PREFIX + 2;
    leaderClient.lockedIntervals.computeIfAbsent(datasource2, k -> new ArrayList<>()).add(Intervals.of("2017/2018"));
    // Verify that no locked intervals are skipped
    CompactSegments compactSegments = new CompactSegments(COORDINATOR_CONFIG, JSON_MAPPER, indexingServiceClient);
    int maxTaskSlots = partitionsSpec instanceof SingleDimensionPartitionsSpec ? 5 : 3;
    final CoordinatorStats stats = doCompactSegments(compactSegments, createCompactionConfigs(1), maxTaskSlots);
    Assert.assertEquals(3, stats.getGlobalStat(CompactSegments.COMPACTION_TASK_COUNT));
    Assert.assertEquals(3, leaderClient.submittedCompactionTasks.size());
    leaderClient.submittedCompactionTasks.forEach(task -> {
        System.out.println(task.getDataSource() + " : " + task.getIoConfig().getInputSpec().getInterval());
    });
    // Verify that tasks are submitted for the latest interval of each dataSource
    final Map<String, Interval> datasourceToInterval = new HashMap<>();
    leaderClient.submittedCompactionTasks.forEach(task -> datasourceToInterval.put(task.getDataSource(), task.getIoConfig().getInputSpec().getInterval()));
    Assert.assertEquals(Intervals.of("2017-01-09T00:00:00Z/2017-01-09T12:00:00Z"), datasourceToInterval.get(datasource0));
    Assert.assertEquals(Intervals.of("2017-01-09T00:00:00Z/2017-01-09T12:00:00Z"), datasourceToInterval.get(datasource1));
    Assert.assertEquals(Intervals.of("2017-01-09T00:00:00Z/2017-01-09T12:00:00Z"), datasourceToInterval.get(datasource2));
}
Also used : HttpIndexingServiceClient(org.apache.druid.client.indexing.HttpIndexingServiceClient) DruidNodeDiscoveryProvider(org.apache.druid.discovery.DruidNodeDiscoveryProvider) ArgumentMatchers(org.mockito.ArgumentMatchers) HttpMethod(org.jboss.netty.handler.codec.http.HttpMethod) CoordinatorStats(org.apache.druid.server.coordinator.CoordinatorStats) DataSourceCompactionConfig(org.apache.druid.server.coordinator.DataSourceCompactionConfig) BooleanSupplier(java.util.function.BooleanSupplier) TaskPayloadResponse(org.apache.druid.client.indexing.TaskPayloadResponse) UserCompactionTaskQueryTuningConfig(org.apache.druid.server.coordinator.UserCompactionTaskQueryTuningConfig) Map(java.util.Map) IAE(org.apache.druid.java.util.common.IAE) ClientCompactionIOConfig(org.apache.druid.client.indexing.ClientCompactionIOConfig) IndexingTotalWorkerCapacityInfo(org.apache.druid.client.indexing.IndexingTotalWorkerCapacityInfo) ClientCompactionTaskQueryTuningConfig(org.apache.druid.client.indexing.ClientCompactionTaskQueryTuningConfig) CoordinatorCompactionConfig(org.apache.druid.server.coordinator.CoordinatorCompactionConfig) ClientCompactionIntervalSpec(org.apache.druid.client.indexing.ClientCompactionIntervalSpec) TaskStatusPlus(org.apache.druid.indexer.TaskStatusPlus) UserCompactionTaskTransformConfig(org.apache.druid.server.coordinator.UserCompactionTaskTransformConfig) StandardCharsets(java.nio.charset.StandardCharsets) TaskState(org.apache.druid.indexer.TaskState) ClientTaskQuery(org.apache.druid.client.indexing.ClientTaskQuery) HttpVersion(org.jboss.netty.handler.codec.http.HttpVersion) TransformSpec(org.apache.druid.segment.transform.TransformSpec) Streams(org.apache.druid.utils.Streams) IndexingWorkerInfo(org.apache.druid.client.indexing.IndexingWorkerInfo) InjectableValues(com.fasterxml.jackson.databind.InjectableValues) HashBasedNumberedShardSpec(org.apache.druid.timeline.partition.HashBasedNumberedShardSpec) UserCompactionTaskIOConfig(org.apache.druid.server.coordinator.UserCompactionTaskIOConfig) RunWith(org.junit.runner.RunWith) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) PartitionChunk(org.apache.druid.timeline.partition.PartitionChunk) Interval(org.joda.time.Interval) Lists(com.google.common.collect.Lists) PartitionsSpec(org.apache.druid.indexer.partitions.PartitionsSpec) ClientCompactionTaskTransformSpec(org.apache.druid.client.indexing.ClientCompactionTaskTransformSpec) Before(org.junit.Before) VersionedIntervalTimeline(org.apache.druid.timeline.VersionedIntervalTimeline) TaskLocation(org.apache.druid.indexer.TaskLocation) TimelineObjectHolder(org.apache.druid.timeline.TimelineObjectHolder) DimensionsSpec(org.apache.druid.data.input.impl.DimensionsSpec) Test(org.junit.Test) IOException(java.io.IOException) EasyMock(org.easymock.EasyMock) DefaultObjectMapper(org.apache.druid.jackson.DefaultObjectMapper) RunnerTaskState(org.apache.druid.indexer.RunnerTaskState) HttpResponseStatus(org.jboss.netty.handler.codec.http.HttpResponseStatus) ClientCompactionTaskGranularitySpec(org.apache.druid.client.indexing.ClientCompactionTaskGranularitySpec) DruidNode(org.apache.druid.server.DruidNode) Preconditions(com.google.common.base.Preconditions) Assert(org.junit.Assert) Nullable(junitparams.converters.Nullable) MutableInt(org.apache.commons.lang3.mutable.MutableInt) UserCompactionTaskDimensionsConfig(org.apache.druid.server.coordinator.UserCompactionTaskDimensionsConfig) URL(java.net.URL) BiFunction(java.util.function.BiFunction) DruidCoordinatorRuntimeParams(org.apache.druid.server.coordinator.DruidCoordinatorRuntimeParams) IndexingServiceClient(org.apache.druid.client.indexing.IndexingServiceClient) CompactionState(org.apache.druid.timeline.CompactionState) AutoCompactionSnapshot(org.apache.druid.server.coordinator.AutoCompactionSnapshot) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) SelectorDimFilter(org.apache.druid.query.filter.SelectorDimFilter) DynamicPartitionsSpec(org.apache.druid.indexer.partitions.DynamicPartitionsSpec) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Parameterized(org.junit.runners.Parameterized) DateTimes(org.apache.druid.java.util.common.DateTimes) ShardSpec(org.apache.druid.timeline.partition.ShardSpec) CoordinatorRuntimeParamsTestHelpers(org.apache.druid.server.coordinator.CoordinatorRuntimeParamsTestHelpers) ImmutableMap(com.google.common.collect.ImmutableMap) AggregatorFactory(org.apache.druid.query.aggregation.AggregatorFactory) NumberedShardSpec(org.apache.druid.timeline.partition.NumberedShardSpec) Collection(java.util.Collection) StringUtils(org.apache.druid.java.util.common.StringUtils) HashedPartitionsSpec(org.apache.druid.indexer.partitions.HashedPartitionsSpec) Collectors(java.util.stream.Collectors) List(java.util.List) DataSegment(org.apache.druid.timeline.DataSegment) NodeRole(org.apache.druid.discovery.NodeRole) DruidLeaderClient(org.apache.druid.discovery.DruidLeaderClient) Intervals(org.apache.druid.java.util.common.Intervals) ClientCompactionTaskDimensionsSpec(org.apache.druid.client.indexing.ClientCompactionTaskDimensionsSpec) HttpIndexingServiceClient(org.apache.druid.client.indexing.HttpIndexingServiceClient) HashMap(java.util.HashMap) DataSourcesSnapshot(org.apache.druid.client.DataSourcesSnapshot) IndexingWorker(org.apache.druid.client.indexing.IndexingWorker) DruidNodeDiscovery(org.apache.druid.discovery.DruidNodeDiscovery) ArgumentCaptor(org.mockito.ArgumentCaptor) ImmutableList(com.google.common.collect.ImmutableList) DruidCoordinatorConfig(org.apache.druid.server.coordinator.DruidCoordinatorConfig) Request(org.apache.druid.java.util.http.client.Request) UserCompactionTaskGranularityConfig(org.apache.druid.server.coordinator.UserCompactionTaskGranularityConfig) CountAggregatorFactory(org.apache.druid.query.aggregation.CountAggregatorFactory) Period(org.joda.time.Period) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DateTime(org.joda.time.DateTime) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ClientCompactionTaskQuery(org.apache.druid.client.indexing.ClientCompactionTaskQuery) Granularities(org.apache.druid.java.util.common.granularity.Granularities) Mockito(org.mockito.Mockito) SingleDimensionPartitionsSpec(org.apache.druid.indexer.partitions.SingleDimensionPartitionsSpec) NullHandling(org.apache.druid.common.config.NullHandling) SingleDimensionShardSpec(org.apache.druid.timeline.partition.SingleDimensionShardSpec) StringFullResponseHolder(org.apache.druid.java.util.http.client.response.StringFullResponseHolder) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) Collections(java.util.Collections) CoordinatorStats(org.apache.druid.server.coordinator.CoordinatorStats) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SingleDimensionPartitionsSpec(org.apache.druid.indexer.partitions.SingleDimensionPartitionsSpec) Interval(org.joda.time.Interval) Test(org.junit.Test)

Aggregations

Map (java.util.Map)10 Intervals (org.apache.druid.java.util.common.Intervals)10 Collections (java.util.Collections)9 List (java.util.List)9 ImmutableList (com.google.common.collect.ImmutableList)8 ArrayList (java.util.ArrayList)8 Collectors (java.util.stream.Collectors)8 Interval (org.joda.time.Interval)8 ImmutableMap (com.google.common.collect.ImmutableMap)7 NullHandling (org.apache.druid.common.config.NullHandling)7 DateTimes (org.apache.druid.java.util.common.DateTimes)7 AggregatorFactory (org.apache.druid.query.aggregation.AggregatorFactory)7 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6 Lists (com.google.common.collect.Lists)6 Arrays (java.util.Arrays)6 HashMap (java.util.HashMap)6 IOException (java.io.IOException)5 Granularities (org.apache.druid.java.util.common.granularity.Granularities)5 CountAggregatorFactory (org.apache.druid.query.aggregation.CountAggregatorFactory)5 SelectorDimFilter (org.apache.druid.query.filter.SelectorDimFilter)5