Search in sources :

Example 16 with RecordCursor

use of com.apple.foundationdb.record.RecordCursor in project fdb-record-layer by FoundationDB.

the class BitmapValueIndexTest method andOrQueryWithContinuation.

@Test
void andOrQueryWithContinuation() {
    try (FDBRecordContext context = openContext()) {
        createOrOpenRecordStore(context, metaData(REC_NO_BY_STR_NUMS_HOOK));
        saveRecords(100, 200);
        commit(context);
    }
    try (FDBRecordContext context = openContext()) {
        createOrOpenRecordStore(context, metaData(REC_NO_BY_STR_NUMS_HOOK));
        setupPlanner(null);
        final RecordQueryPlan queryPlan = plan(BITMAP_VALUE_REC_NO_BY_STR, Query.and(Query.field("str_value").equalsValue("odd"), Query.field("num_value_2").equalsValue(3), Query.or(Query.field("num_value_3").equalsValue(1), Query.field("num_value_3").equalsValue(4))));
        List<Integer> onBits = new ArrayList<>();
        int ntimes = 0;
        byte[] continuation = null;
        do {
            RecordCursor<IndexEntry> cursor = queryPlan.execute(recordStore, EvaluationContext.EMPTY, continuation, ExecuteProperties.newBuilder().setReturnedRowLimit(2).build()).map(FDBQueriedRecord::getIndexEntry);
            RecordCursorResult<IndexEntry> cursorResult = cursor.forEachResult(i -> onBits.addAll(collectOnBits(i.get()))).join();
            ntimes++;
            continuation = cursorResult.getContinuation().toBytes();
        } while (continuation != null);
        assertThat(onBits, equalTo(IntStream.range(100, 200).boxed().filter(i -> (i & 1) == 1).filter(i -> (i % 7) == 3 && ((i % 5) == 1 || (i % 5) == 4)).collect(Collectors.toList())));
        assertThat(ntimes, equalTo(4));
    }
}
Also used : RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) IndexEntry(com.apple.foundationdb.record.IndexEntry) Matchers.hasToString(org.hamcrest.Matchers.hasToString) Arrays(java.util.Arrays) FanOut(com.apple.foundationdb.record.metadata.expressions.KeyExpression.FanType.FanOut) FDBRecordContext(com.apple.foundationdb.record.provider.foundationdb.FDBRecordContext) PlanMatchers.bounds(com.apple.foundationdb.record.query.plan.match.PlanMatchers.bounds) RecordQueryPlanner(com.apple.foundationdb.record.query.plan.RecordQueryPlanner) IndexScanType(com.apple.foundationdb.record.IndexScanType) Tuple(com.apple.foundationdb.tuple.Tuple) RecordCursorResult(com.apple.foundationdb.record.RecordCursorResult) PlanMatchers.compositeBitmap(com.apple.foundationdb.record.query.plan.match.PlanMatchers.compositeBitmap) AssertionFailedError(org.opentest4j.AssertionFailedError) Expressions.concatenateFields(com.apple.foundationdb.record.metadata.Key.Expressions.concatenateFields) Map(java.util.Map) RecordIndexUniquenessViolation(com.apple.foundationdb.record.RecordIndexUniquenessViolation) Expressions.concat(com.apple.foundationdb.record.metadata.Key.Expressions.concat) GroupingKeyExpression(com.apple.foundationdb.record.metadata.expressions.GroupingKeyExpression) Tag(org.junit.jupiter.api.Tag) PlanMatchers.coveringIndexScan(com.apple.foundationdb.record.query.plan.match.PlanMatchers.coveringIndexScan) PlanMatchers.indexScanType(com.apple.foundationdb.record.query.plan.match.PlanMatchers.indexScanType) Query(com.apple.foundationdb.record.query.expressions.Query) KeyExpression(com.apple.foundationdb.record.metadata.expressions.KeyExpression) IndexOptions(com.apple.foundationdb.record.metadata.IndexOptions) ImmutableMap(com.google.common.collect.ImmutableMap) Matchers.allOf(org.hamcrest.Matchers.allOf) IndexQueryabilityFilter(com.apple.foundationdb.record.query.IndexQueryabilityFilter) Collectors(java.util.stream.Collectors) TupleRange(com.apple.foundationdb.record.TupleRange) Test(org.junit.jupiter.api.Test) PlanMatchers.hasTupleString(com.apple.foundationdb.record.query.plan.match.PlanMatchers.hasTupleString) ComposedBitmapIndexAggregate(com.apple.foundationdb.record.query.plan.bitmap.ComposedBitmapIndexAggregate) List(java.util.List) IndexAggregateFunctionCall(com.apple.foundationdb.record.metadata.IndexAggregateFunctionCall) PlanMatchers.indexName(com.apple.foundationdb.record.query.plan.match.PlanMatchers.indexName) EvaluationContext(com.apple.foundationdb.record.EvaluationContext) FDBQueriedRecord(com.apple.foundationdb.record.provider.foundationdb.FDBQueriedRecord) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexTypes(com.apple.foundationdb.record.metadata.IndexTypes) Optional(java.util.Optional) IntStream(java.util.stream.IntStream) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.fail(org.junit.jupiter.api.Assertions.fail) FunctionNames(com.apple.foundationdb.record.FunctionNames) RecordMetaData(com.apple.foundationdb.record.RecordMetaData) IndexAggregateFunction(com.apple.foundationdb.record.metadata.IndexAggregateFunction) PlanMatchers.indexScan(com.apple.foundationdb.record.query.plan.match.PlanMatchers.indexScan) RecordQuery(com.apple.foundationdb.record.query.RecordQuery) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) PlanHashable(com.apple.foundationdb.record.PlanHashable) ArrayList(java.util.ArrayList) ExecuteProperties(com.apple.foundationdb.record.ExecuteProperties) ScanProperties(com.apple.foundationdb.record.ScanProperties) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nonnull(javax.annotation.Nonnull) Expressions.field(com.apple.foundationdb.record.metadata.Key.Expressions.field) Nullable(javax.annotation.Nullable) TestRecordsBitmapProto(com.apple.foundationdb.record.TestRecordsBitmapProto) IsolationLevel(com.apple.foundationdb.record.IsolationLevel) RecordMetaDataBuilder(com.apple.foundationdb.record.RecordMetaDataBuilder) RecordTypeBuilder(com.apple.foundationdb.record.metadata.RecordTypeBuilder) Tags(com.apple.test.Tags) FDBRecordStoreTestBase(com.apple.foundationdb.record.provider.foundationdb.FDBRecordStoreTestBase) Index(com.apple.foundationdb.record.metadata.Index) RecordCursor(com.apple.foundationdb.record.RecordCursor) QueryComponent(com.apple.foundationdb.record.query.expressions.QueryComponent) Collections(java.util.Collections) FDBQueriedRecord(com.apple.foundationdb.record.provider.foundationdb.FDBQueriedRecord) FDBRecordContext(com.apple.foundationdb.record.provider.foundationdb.FDBRecordContext) ArrayList(java.util.ArrayList) IndexEntry(com.apple.foundationdb.record.IndexEntry) Test(org.junit.jupiter.api.Test)

Example 17 with RecordCursor

use of com.apple.foundationdb.record.RecordCursor in project fdb-record-layer by FoundationDB.

the class UnorderedUnionCursorTest method loopIterationWithLimit.

@Test
public void loopIterationWithLimit() throws ExecutionException, InterruptedException {
    FDBStoreTimer timer = new FDBStoreTimer();
    FirableCursor<Integer> secondCursor = new FirableCursor<>(RecordCursor.fromList(Arrays.asList(3, 4)));
    RecordCursor<Integer> cursor = UnorderedUnionCursor.create(Arrays.asList(continuation -> RecordCursor.fromList(Arrays.asList(1, 2), continuation).limitRowsTo(1), continuation -> secondCursor), null, timer);
    RecordCursorResult<Integer> cursorResult = cursor.getNext();
    assertEquals(1, (int) cursorResult.get());
    CompletableFuture<RecordCursorResult<Integer>> cursorResultFuture = cursor.onNext();
    assertFalse(cursorResultFuture.isDone());
    secondCursor.fire();
    cursorResult = cursorResultFuture.get();
    assertEquals(3, (int) cursorResult.get());
    cursorResultFuture = cursor.onNext();
    assertFalse(cursorResultFuture.isDone());
    secondCursor.fire();
    cursorResult = cursorResultFuture.get();
    assertEquals(4, (int) cursorResult.get());
    cursorResultFuture = cursor.onNext();
    assertFalse(cursorResultFuture.isDone());
    secondCursor.fire();
    cursorResult = cursorResultFuture.get();
    assertFalse(cursorResult.hasNext());
    assertEquals(RecordCursor.NoNextReason.RETURN_LIMIT_REACHED, cursorResult.getNoNextReason());
    assertThat(timer.getCount(FDBStoreTimer.Events.QUERY_INTERSECTION), lessThanOrEqualTo(5));
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Arrays(java.util.Arrays) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) FDBTestBase(com.apple.foundationdb.record.provider.foundationdb.FDBTestBase) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) RecordCursorResult(com.apple.foundationdb.record.RecordCursorResult) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) RecordCoreException(com.apple.foundationdb.record.RecordCoreException) FirableCursor(com.apple.foundationdb.record.cursors.FirableCursor) RecordCursorIterator(com.apple.foundationdb.record.RecordCursorIterator) Tag(org.junit.jupiter.api.Tag) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nonnull(javax.annotation.Nonnull) ValueSource(org.junit.jupiter.params.provider.ValueSource) Iterator(java.util.Iterator) FDBStoreTimer(com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer) Tags(com.apple.test.Tags) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) Collectors(java.util.stream.Collectors) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) Test(org.junit.jupiter.api.Test) ExecutionException(java.util.concurrent.ExecutionException) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) List(java.util.List) RecordCursor(com.apple.foundationdb.record.RecordCursor) RecordCursorTest(com.apple.foundationdb.record.RecordCursorTest) Matchers.is(org.hamcrest.Matchers.is) Collections(java.util.Collections) FirableCursor(com.apple.foundationdb.record.cursors.FirableCursor) FDBStoreTimer(com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer) RecordCursorResult(com.apple.foundationdb.record.RecordCursorResult) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) RecordCursorTest(com.apple.foundationdb.record.RecordCursorTest)

Example 18 with RecordCursor

use of com.apple.foundationdb.record.RecordCursor in project fdb-record-layer by FoundationDB.

the class GeophileQueryTest method testDistance.

@Test
@Tag(Tags.Slow)
public void testDistance() throws Exception {
    final RecordMetaDataHook hook = md -> {
        md.addIndex("City", CITY_LOCATION_COVERING_INDEX);
    };
    loadCities(hook, 0);
    final int centerId = 5391959;
    final double distance = 1;
    final int scanLimit = 5000;
    final RecordQueryPlan scanPlan = distanceFilterScan(distance);
    final Set<Integer> scanResults = new HashSet<>();
    byte[] continuation = null;
    do {
        try (FDBRecordContext context = openContext()) {
            openRecordStore(context, hook);
            EvaluationContext joinContext = bindCenter(centerId);
            ExecuteProperties executeProperties = ExecuteProperties.newBuilder().setScannedRecordsLimit(scanLimit).build();
            RecordCursor<FDBQueriedRecord<Message>> recordCursor = scanPlan.execute(recordStore, joinContext, continuation, executeProperties);
            recordCursor.forEach(city -> {
                TestRecordsGeoProto.City.Builder cityBuilder = TestRecordsGeoProto.City.newBuilder().mergeFrom(city.getRecord());
                LOGGER.debug(String.format("Scan found %s: %s", cityBuilder.getGeoNameId(), cityBuilder.getName()));
                scanResults.add(cityBuilder.getGeoNameId());
            }).join();
            continuation = recordCursor.getNext().getContinuation().toBytes();
            commit(context);
        }
    } while (continuation != null);
    final RecordQueryPlan indexPlan = distanceSpatialQuery(distance, false);
    final Set<Integer> indexResults = new HashSet<>();
    try (FDBRecordContext context = openContext()) {
        openRecordStore(context, hook);
        RecordCursor<FDBQueriedRecord<Message>> recordCursor = indexPlan.execute(recordStore, bindCenter(centerId));
        recordCursor.forEach(city -> {
            TestRecordsGeoProto.City.Builder cityBuilder = TestRecordsGeoProto.City.newBuilder().mergeFrom(city.getRecord());
            LOGGER.debug(String.format("Index found %s: %s", cityBuilder.getGeoNameId(), cityBuilder.getName()));
            indexResults.add(cityBuilder.getGeoNameId());
        }).join();
        int given = timer.getCount(FDBStoreTimer.Counts.QUERY_FILTER_GIVEN);
        int passed = timer.getCount(FDBStoreTimer.Counts.QUERY_FILTER_PASSED);
        int discarded = timer.getCount(FDBStoreTimer.Counts.QUERY_DISCARDED);
        assertThat("Should have passed more than discarded", passed, greaterThan(discarded));
        commit(context);
    }
    final RecordQueryPlan coveringPlan = distanceSpatialQuery(distance, true);
    final Set<Integer> coveringResults = new HashSet<>();
    try (FDBRecordContext context = openContext()) {
        openRecordStore(context, hook);
        RecordCursor<FDBQueriedRecord<Message>> recordCursor = indexPlan.execute(recordStore, bindCenter(centerId));
        recordCursor.forEach(city -> {
            TestRecordsGeoProto.City.Builder cityBuilder = TestRecordsGeoProto.City.newBuilder().mergeFrom(city.getRecord());
            LOGGER.debug(String.format("Covering found %s: %s", cityBuilder.getGeoNameId(), cityBuilder.getName()));
            coveringResults.add(cityBuilder.getGeoNameId());
        }).join();
        commit(context);
    }
    assertEquals(scanResults, indexResults);
    assertEquals(scanResults, coveringResults);
}
Also used : RecordQueryFilterPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryFilterPlan) LoggerFactory(org.slf4j.LoggerFactory) Coordinate(org.locationtech.jts.geom.Coordinate) Bindings(com.apple.foundationdb.record.Bindings) FDBRecordContext(com.apple.foundationdb.record.provider.foundationdb.FDBRecordContext) Tuple(com.apple.foundationdb.tuple.Tuple) Pair(org.apache.commons.lang3.tuple.Pair) Expressions.concatenateFields(com.apple.foundationdb.record.metadata.Key.Expressions.concatenateFields) RecordQueryScanPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryScanPlan) Expressions.concat(com.apple.foundationdb.record.metadata.Key.Expressions.concat) Tag(org.junit.jupiter.api.Tag) Query(com.apple.foundationdb.record.query.expressions.Query) DoubleValueOrParameter(com.apple.foundationdb.record.spatial.common.DoubleValueOrParameter) KeyExpression(com.apple.foundationdb.record.metadata.expressions.KeyExpression) FDBStoreTimer(com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer) Matchers.allOf(org.hamcrest.Matchers.allOf) Set(java.util.Set) Point(org.locationtech.jts.geom.Point) CompletionException(java.util.concurrent.CompletionException) Expressions.keyWithValue(com.apple.foundationdb.record.metadata.Key.Expressions.keyWithValue) Test(org.junit.jupiter.api.Test) GeoJsonReader(org.locationtech.jts.io.geojson.GeoJsonReader) TopologyException(org.locationtech.jts.geom.TopologyException) ParseException(org.locationtech.jts.io.ParseException) EvaluationContext(com.apple.foundationdb.record.EvaluationContext) FDBQueriedRecord(com.apple.foundationdb.record.provider.foundationdb.FDBQueriedRecord) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Geometry(org.locationtech.jts.geom.Geometry) Expressions.function(com.apple.foundationdb.record.metadata.Key.Expressions.function) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) RecordQueryTypeFilterPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryTypeFilterPlan) GeoPointWithinDistanceComponent(com.apple.foundationdb.record.spatial.common.GeoPointWithinDistanceComponent) FDBIndexedRecord(com.apple.foundationdb.record.provider.foundationdb.FDBIndexedRecord) FDBRecordStoreQueryTestBase(com.apple.foundationdb.record.provider.foundationdb.query.FDBRecordStoreQueryTestBase) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) HashSet(java.util.HashSet) Matchers.hasProperty(org.hamcrest.Matchers.hasProperty) ExecuteProperties(com.apple.foundationdb.record.ExecuteProperties) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nonnull(javax.annotation.Nonnull) Expressions.field(com.apple.foundationdb.record.metadata.Key.Expressions.field) FDBStoredRecord(com.apple.foundationdb.record.provider.foundationdb.FDBStoredRecord) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) Logger(org.slf4j.Logger) Tags(com.apple.test.Tags) Throwables(com.google.common.base.Throwables) Matchers(org.hamcrest.Matchers) ScanComparisons(com.apple.foundationdb.record.query.plan.ScanComparisons) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) Index(com.apple.foundationdb.record.metadata.Index) Expressions.value(com.apple.foundationdb.record.metadata.Key.Expressions.value) FDBException(com.apple.foundationdb.FDBException) Message(com.google.protobuf.Message) RecordCursor(com.apple.foundationdb.record.RecordCursor) BufferedReader(java.io.BufferedReader) Collections(java.util.Collections) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) Point(org.locationtech.jts.geom.Point) ExecuteProperties(com.apple.foundationdb.record.ExecuteProperties) FDBQueriedRecord(com.apple.foundationdb.record.provider.foundationdb.FDBQueriedRecord) FDBRecordContext(com.apple.foundationdb.record.provider.foundationdb.FDBRecordContext) EvaluationContext(com.apple.foundationdb.record.EvaluationContext) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test) Tag(org.junit.jupiter.api.Tag)

Example 19 with RecordCursor

use of com.apple.foundationdb.record.RecordCursor in project fdb-record-layer by FoundationDB.

the class QueryPlanCursorTest method compareSkipsAndCursors.

private void compareSkipsAndCursors(RecordQueryPlan plan, int amount) throws Exception {
    final Function<FDBQueriedRecord<Message>, Long> getRecNo = r -> {
        TestRecords1Proto.MySimpleRecord.Builder record = TestRecords1Proto.MySimpleRecord.newBuilder();
        record.mergeFrom(r.getRecord());
        return record.getRecNo();
    };
    final ExecuteProperties justLimit = ExecuteProperties.newBuilder().setReturnedRowLimit(amount).build();
    try (FDBRecordContext context = openContext()) {
        openSimpleRecordStore(context);
        final List<Long> whole;
        try (RecordCursor<FDBQueriedRecord<Message>> cursor = recordStore.executeQuery(plan)) {
            whole = cursor.map(getRecNo).asList().get();
        }
        assertTrue(whole.size() > amount, "should have more than one batch");
        final List<Long> byCursors = new ArrayList<>();
        byte[] continuation = null;
        do {
            try (RecordCursor<FDBQueriedRecord<Message>> cursor = recordStore.executeQuery(plan, continuation, justLimit)) {
                RecordCursorResult<FDBQueriedRecord<Message>> result = null;
                do {
                    result = cursor.getNext();
                    if (result.hasNext()) {
                        byCursors.add(getRecNo.apply(result.get()));
                    }
                } while (result.hasNext());
                continuation = result.getContinuation().toBytes();
            }
        } while (continuation != null);
        assertEquals(whole, byCursors);
        final List<Long> byOffsets = new ArrayList<>();
        int offset = 0;
        while (true) {
            final ExecuteProperties skipAndLimit = ExecuteProperties.newBuilder().setSkip(offset).setReturnedRowLimit(amount).setIsolationLevel(justLimit.getIsolationLevel()).build();
            try (RecordCursor<FDBQueriedRecord<Message>> cursor = recordStore.executeQuery(plan, null, skipAndLimit)) {
                final List<Long> next = cursor.map(getRecNo).asList().get();
                byOffsets.addAll(next);
                if (next.size() < amount) {
                    break;
                } else {
                    offset += next.size();
                }
            }
        }
        assertEquals(whole, byOffsets);
    }
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) RecordQueryFilterPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryFilterPlan) Arrays(java.util.Arrays) RecordQueryIntersectionPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryIntersectionPlan) LoggerFactory(org.slf4j.LoggerFactory) Bindings(com.apple.foundationdb.record.Bindings) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Key(com.apple.foundationdb.record.metadata.Key) ExecuteProperties(com.apple.foundationdb.record.ExecuteProperties) RecordCursorResult(com.apple.foundationdb.record.RecordCursorResult) RecordQueryScanPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryScanPlan) Tag(org.junit.jupiter.api.Tag) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) RecordQueryUnionPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryUnionPlan) RecordQueryIndexPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryIndexPlan) Query(com.apple.foundationdb.record.query.expressions.Query) KeyExpression(com.apple.foundationdb.record.metadata.expressions.KeyExpression) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) TestRecords1Proto(com.apple.foundationdb.record.TestRecords1Proto) Tags(com.apple.test.Tags) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) ScanComparisons(com.apple.foundationdb.record.query.plan.ScanComparisons) Test(org.junit.jupiter.api.Test) Comparisons(com.apple.foundationdb.record.query.expressions.Comparisons) List(java.util.List) EvaluationContext(com.apple.foundationdb.record.EvaluationContext) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) RecordQueryInValuesJoinPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryInValuesJoinPlan) Message(com.google.protobuf.Message) RecordCursor(com.apple.foundationdb.record.RecordCursor) QueryComponent(com.apple.foundationdb.record.query.expressions.QueryComponent) RecordQueryTypeFilterPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryTypeFilterPlan) Collections(java.util.Collections) TestRecords1Proto(com.apple.foundationdb.record.TestRecords1Proto) ArrayList(java.util.ArrayList) ExecuteProperties(com.apple.foundationdb.record.ExecuteProperties)

Example 20 with RecordCursor

use of com.apple.foundationdb.record.RecordCursor in project fdb-record-layer by FoundationDB.

the class ProbableIntersectionCursorTest method resumeFromContinuation.

/**
 * Test that the cursor can be resumed by deserializing its state from the continuation object.
 */
@Test
public void resumeFromContinuation() {
    final FDBStoreTimer timer = new FDBStoreTimer();
    final List<Integer> list1 = Arrays.asList(10, 2, 5, 6, 8, 19, 0);
    final List<Integer> list2 = Arrays.asList(9, 1, 3, 5, 2, 4, 8);
    final List<Function<byte[], RecordCursor<Integer>>> cursorFuncs = listsToFunctions(Arrays.asList(list1, list2));
    final Function<byte[], ProbableIntersectionCursor<Integer>> intersectionCursorFunction = continuation -> ProbableIntersectionCursor.create(Collections::singletonList, cursorFuncs, continuation, timer);
    final Iterator<Integer> resultIterator = Iterators.forArray(5, 2, 8);
    byte[] continuation = null;
    boolean done = false;
    List<BloomFilter<List<Object>>> lastBloomFilters = null;
    while (!done) {
        ProbableIntersectionCursor<Integer> intersectionCursor = intersectionCursorFunction.apply(continuation);
        List<BloomFilter<List<Object>>> bloomFilters = intersectionCursor.getCursorStates().stream().map(ProbableIntersectionCursorState::getBloomFilter).collect(Collectors.toList());
        if (lastBloomFilters != null) {
            assertEquals(lastBloomFilters, bloomFilters);
        }
        lastBloomFilters = bloomFilters;
        RecordCursorResult<Integer> result = intersectionCursor.getNext();
        if (resultIterator.hasNext()) {
            assertThat(result.hasNext(), is(true));
            assertEquals(resultIterator.next(), result.get());
            assertThat(result.getContinuation().isEnd(), is(false));
            assertNotNull(result.getContinuation().toBytes());
        } else {
            assertThat(result.hasNext(), is(false));
            assertEquals(RecordCursor.NoNextReason.SOURCE_EXHAUSTED, result.getNoNextReason());
            assertThat(result.getContinuation().isEnd(), is(true));
            assertNull(result.getContinuation().toBytes());
            done = true;
        }
        continuation = result.getContinuation().toBytes();
    }
    assertEquals(3, timer.getCount(FDBStoreTimer.Counts.QUERY_INTERSECTION_PLAN_MATCHES));
    assertEquals(list1.size() + list2.size() - 3, timer.getCount(FDBStoreTimer.Counts.QUERY_INTERSECTION_PLAN_NONMATCHES));
}
Also used : IntStream(java.util.stream.IntStream) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Arrays(java.util.Arrays) RowLimitedCursor(com.apple.foundationdb.record.cursors.RowLimitedCursor) LoggerFactory(org.slf4j.LoggerFactory) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) Random(java.util.Random) CompletableFuture(java.util.concurrent.CompletableFuture) AsyncUtil(com.apple.foundationdb.async.AsyncUtil) Function(java.util.function.Function) Iterators(com.google.common.collect.Iterators) HashSet(java.util.HashSet) RecordCursorResult(com.apple.foundationdb.record.RecordCursorResult) KeyValueLogMessage(com.apple.foundationdb.record.logging.KeyValueLogMessage) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) RecordCoreException(com.apple.foundationdb.record.RecordCoreException) TestLogMessageKeys(com.apple.foundationdb.record.logging.TestLogMessageKeys) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FirableCursor(com.apple.foundationdb.record.cursors.FirableCursor) Matchers.lessThan(org.hamcrest.Matchers.lessThan) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nonnull(javax.annotation.Nonnull) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) FDBStoreTimer(com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) BloomFilter(com.google.common.hash.BloomFilter) Set(java.util.Set) Collectors(java.util.stream.Collectors) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) Test(org.junit.jupiter.api.Test) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) Stream(java.util.stream.Stream) RecordCursorProto(com.apple.foundationdb.record.RecordCursorProto) RecordCursor(com.apple.foundationdb.record.RecordCursor) RecordCursorTest(com.apple.foundationdb.record.RecordCursorTest) Matchers.is(org.hamcrest.Matchers.is) Collections(java.util.Collections) BloomFilter(com.google.common.hash.BloomFilter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Function(java.util.function.Function) FDBStoreTimer(com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer) Collections(java.util.Collections) Test(org.junit.jupiter.api.Test) RecordCursorTest(com.apple.foundationdb.record.RecordCursorTest)

Aggregations

RecordCursor (com.apple.foundationdb.record.RecordCursor)66 List (java.util.List)59 Nonnull (javax.annotation.Nonnull)57 Message (com.google.protobuf.Message)50 Collections (java.util.Collections)48 Function (java.util.function.Function)48 ArrayList (java.util.ArrayList)47 ExecuteProperties (com.apple.foundationdb.record.ExecuteProperties)46 Tuple (com.apple.foundationdb.tuple.Tuple)44 Test (org.junit.jupiter.api.Test)43 ScanProperties (com.apple.foundationdb.record.ScanProperties)42 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)40 RecordCursorResult (com.apple.foundationdb.record.RecordCursorResult)39 Tags (com.apple.test.Tags)37 Collectors (java.util.stream.Collectors)37 Tag (org.junit.jupiter.api.Tag)37 Arrays (java.util.Arrays)36 Nullable (javax.annotation.Nullable)35 Index (com.apple.foundationdb.record.metadata.Index)34 KeyExpression (com.apple.foundationdb.record.metadata.expressions.KeyExpression)33