Search in sources :

Example 16 with IIndexCursor

use of org.apache.hyracks.storage.common.IIndexCursor in project asterixdb by apache.

the class FramewriterTest method mockIndexCursors.

private IIndexCursor[] mockIndexCursors() throws HyracksDataException {
    ITupleReference[] tuples = mockTuples();
    IIndexCursor[] cursors = new IIndexCursor[tuples.length * 2];
    int j = 0;
    for (int i = 0; i < tuples.length; i++) {
        IIndexCursor cursor = Mockito.mock(IIndexCursor.class);
        Mockito.when(cursor.hasNext()).thenReturn(true, true, false);
        Mockito.when(cursor.getTuple()).thenReturn(tuples[i]);
        cursors[j] = cursor;
        j++;
        cursor = Mockito.mock(IIndexCursor.class);
        Mockito.when(cursor.hasNext()).thenReturn(true, true, false);
        Mockito.when(cursor.getTuple()).thenReturn(tuples[i]);
        Mockito.doThrow(new HyracksDataException("Failed to close cursor")).when(cursor).close();
        cursors[j] = cursor;
        j++;
    }
    return cursors;
}
Also used : ITupleReference(org.apache.hyracks.dataflow.common.data.accessors.ITupleReference) IIndexCursor(org.apache.hyracks.storage.common.IIndexCursor) HyracksDataException(org.apache.hyracks.api.exceptions.HyracksDataException)

Example 17 with IIndexCursor

use of org.apache.hyracks.storage.common.IIndexCursor in project asterixdb by apache.

the class FramewriterTest method mockIndexAccessors.

private IIndexAccessor[] mockIndexAccessors() throws HyracksDataException {
    IIndexCursor[] cursors = mockIndexCursors();
    IIndexAccessor[] accessors = new IIndexAccessor[cursors.length * 2];
    int j = 0;
    for (int i = 0; i < cursors.length; i++) {
        IIndexCursor cursor = cursors[i];
        IIndexAccessor accessor = Mockito.mock(IIndexAccessor.class);
        Mockito.when(accessor.createSearchCursor(Matchers.anyBoolean())).thenReturn(cursor);
        accessors[j] = accessor;
        j++;
        accessor = Mockito.mock(IIndexAccessor.class);
        Mockito.when(accessor.createSearchCursor(Matchers.anyBoolean())).thenReturn(cursor);
        Mockito.doAnswer(new Answer<Object>() {

            private int k = 0;

            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                k++;
                if (k % 2 == 0) {
                    throw new HyracksDataException("Couldn't search index");
                }
                return null;
            }
        }).when(accessor).search(Matchers.any(), Matchers.any());
        accessors[j] = accessor;
        j++;
    }
    return accessors;
}
Also used : InvocationOnMock(org.mockito.invocation.InvocationOnMock) IIndexCursor(org.apache.hyracks.storage.common.IIndexCursor) IIndexAccessor(org.apache.hyracks.storage.common.IIndexAccessor) HyracksDataException(org.apache.hyracks.api.exceptions.HyracksDataException)

Example 18 with IIndexCursor

use of org.apache.hyracks.storage.common.IIndexCursor in project asterixdb by apache.

the class MetadataNode method initializeDatasetIdFactory.

@Override
public void initializeDatasetIdFactory(JobId jobId) throws MetadataException, RemoteException {
    int mostRecentDatasetId = MetadataIndexImmutableProperties.FIRST_AVAILABLE_USER_DATASET_ID;
    try {
        String resourceName = MetadataPrimaryIndexes.DATASET_DATASET.getFile().getRelativePath();
        IIndex indexInstance = datasetLifecycleManager.get(resourceName);
        datasetLifecycleManager.open(resourceName);
        try {
            IIndexAccessor indexAccessor = indexInstance.createAccessor(NoOpOperationCallback.INSTANCE, NoOpOperationCallback.INSTANCE);
            IIndexCursor rangeCursor = indexAccessor.createSearchCursor(false);
            DatasetTupleTranslator tupleReaderWriter = tupleTranslatorProvider.getDatasetTupleTranslator(false);
            IValueExtractor<Dataset> valueExtractor = new MetadataEntityValueExtractor<>(tupleReaderWriter);
            RangePredicate rangePred = new RangePredicate(null, null, true, true, null, null);
            indexAccessor.search(rangeCursor, rangePred);
            int datasetId;
            try {
                while (rangeCursor.hasNext()) {
                    rangeCursor.next();
                    final ITupleReference ref = rangeCursor.getTuple();
                    final Dataset ds = valueExtractor.getValue(jobId, ref);
                    datasetId = ds.getDatasetId();
                    if (mostRecentDatasetId < datasetId) {
                        mostRecentDatasetId = datasetId;
                    }
                }
            } finally {
                rangeCursor.close();
            }
        } finally {
            datasetLifecycleManager.close(resourceName);
        }
    } catch (HyracksDataException e) {
        throw new MetadataException(e);
    }
    DatasetIdFactory.initialize(mostRecentDatasetId);
}
Also used : IIndex(org.apache.hyracks.storage.common.IIndex) RangePredicate(org.apache.hyracks.storage.am.btree.impls.RangePredicate) DatasetTupleTranslator(org.apache.asterix.metadata.entitytupletranslators.DatasetTupleTranslator) ExtensionMetadataDataset(org.apache.asterix.metadata.api.ExtensionMetadataDataset) Dataset(org.apache.asterix.metadata.entities.Dataset) AString(org.apache.asterix.om.base.AString) AMutableString(org.apache.asterix.om.base.AMutableString) IIndexAccessor(org.apache.hyracks.storage.common.IIndexAccessor) HyracksDataException(org.apache.hyracks.api.exceptions.HyracksDataException) MetadataEntityValueExtractor(org.apache.asterix.metadata.valueextractors.MetadataEntityValueExtractor) ITupleReference(org.apache.hyracks.dataflow.common.data.accessors.ITupleReference) IIndexCursor(org.apache.hyracks.storage.common.IIndexCursor)

Example 19 with IIndexCursor

use of org.apache.hyracks.storage.common.IIndexCursor in project asterixdb by apache.

the class OrderedIndexTestUtils method checkRangeSearch.

@SuppressWarnings("unchecked")
public void checkRangeSearch(IIndexTestContext ctx, ITupleReference lowKey, ITupleReference highKey, boolean lowKeyInclusive, boolean highKeyInclusive) throws Exception {
    if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.info("Testing Range Search.");
    }
    MultiComparator lowKeyCmp = BTreeUtils.getSearchMultiComparator(ctx.getComparatorFactories(), lowKey);
    MultiComparator highKeyCmp = BTreeUtils.getSearchMultiComparator(ctx.getComparatorFactories(), highKey);
    IIndexCursor searchCursor = ctx.getIndexAccessor().createSearchCursor(false);
    RangePredicate rangePred = new RangePredicate(lowKey, highKey, lowKeyInclusive, highKeyInclusive, lowKeyCmp, highKeyCmp);
    ctx.getIndexAccessor().search(searchCursor, rangePred);
    // Get the subset of elements from the expected set within given key
    // range.
    CheckTuple lowKeyCheck = createCheckTupleFromTuple(lowKey, ctx.getFieldSerdes(), lowKeyCmp.getKeyFieldCount());
    CheckTuple highKeyCheck = createCheckTupleFromTuple(highKey, ctx.getFieldSerdes(), highKeyCmp.getKeyFieldCount());
    SortedSet<CheckTuple> expectedSubset = null;
    if (lowKeyCmp.getKeyFieldCount() < ctx.getKeyFieldCount() || highKeyCmp.getKeyFieldCount() < ctx.getKeyFieldCount()) {
        // Searching on a key prefix (low key or high key or both).
        expectedSubset = getPrefixExpectedSubset((TreeSet<CheckTuple>) ctx.getCheckTuples(), lowKeyCheck, highKeyCheck);
    } else {
        // Searching on all key fields.
        expectedSubset = ((TreeSet<CheckTuple>) ctx.getCheckTuples()).subSet(lowKeyCheck, lowKeyInclusive, highKeyCheck, highKeyInclusive);
    }
    Iterator<CheckTuple> checkIter = expectedSubset.iterator();
    int actualCount = 0;
    try {
        while (searchCursor.hasNext()) {
            if (!checkIter.hasNext()) {
                fail("Range search returned more answers than expected.\nExpected: " + expectedSubset.size());
            }
            searchCursor.next();
            CheckTuple expectedTuple = checkIter.next();
            ITupleReference tuple = searchCursor.getTuple();
            compareActualAndExpected(tuple, expectedTuple, ctx.getFieldSerdes());
            actualCount++;
        }
        if (actualCount < expectedSubset.size()) {
            fail("Range search returned fewer answers than expected.\nExpected: " + expectedSubset.size() + "\nActual  : " + actualCount);
        }
    } finally {
        searchCursor.close();
    }
}
Also used : RangePredicate(org.apache.hyracks.storage.am.btree.impls.RangePredicate) CheckTuple(org.apache.hyracks.storage.am.common.CheckTuple) TreeSet(java.util.TreeSet) MultiComparator(org.apache.hyracks.storage.common.MultiComparator) ITupleReference(org.apache.hyracks.dataflow.common.data.accessors.ITupleReference) IIndexCursor(org.apache.hyracks.storage.common.IIndexCursor)

Example 20 with IIndexCursor

use of org.apache.hyracks.storage.common.IIndexCursor in project asterixdb by apache.

the class LSMInvertedIndexTestUtils method testIndexSearch.

public static void testIndexSearch(LSMInvertedIndexTestContext testCtx, TupleGenerator tupleGen, Random rnd, int numDocQueries, int numRandomQueries, IInvertedIndexSearchModifier searchModifier, int[] scanCountArray) throws IOException, HyracksDataException {
    IInvertedIndex invIndex = testCtx.invIndex;
    IInvertedIndexAccessor accessor = (IInvertedIndexAccessor) invIndex.createAccessor(NoOpOperationCallback.INSTANCE, NoOpOperationCallback.INSTANCE);
    IBinaryTokenizer tokenizer = testCtx.getTokenizerFactory().createTokenizer();
    InvertedIndexSearchPredicate searchPred = new InvertedIndexSearchPredicate(tokenizer, searchModifier);
    List<ITupleReference> documentCorpus = testCtx.getDocumentCorpus();
    // Project away the primary-key field.
    int[] fieldPermutation = new int[] { 0 };
    PermutingTupleReference searchDocument = new PermutingTupleReference(fieldPermutation);
    int numQueries = numDocQueries + numRandomQueries;
    for (int i = 0; i < numQueries; i++) {
        // If number of documents in the corpus is less than numDocQueries, then replace the remaining ones with random queries.
        if (i >= numDocQueries || i >= documentCorpus.size()) {
            // Generate a random query.
            ITupleReference randomQuery = tupleGen.next();
            searchDocument.reset(randomQuery);
        } else {
            // Pick a random document from the corpus to use as the search query.
            int queryIndex = Math.abs(rnd.nextInt() % documentCorpus.size());
            searchDocument.reset(documentCorpus.get(queryIndex));
        }
        // Set query tuple in search predicate.
        searchPred.setQueryTuple(searchDocument);
        searchPred.setQueryFieldIndex(0);
        IIndexCursor resultCursor = accessor.createSearchCursor(false);
        boolean panic = false;
        try {
            accessor.search(resultCursor, searchPred);
        } catch (HyracksDataException e) {
            // ignore panic queries.
            if (e.getErrorCode() == ErrorCode.OCCURRENCE_THRESHOLD_PANIC_EXCEPTION) {
                panic = true;
            } else {
                throw e;
            }
        }
        try {
            if (!panic) {
                // Consume cursor and deserialize results so we can sort them. Some search cursors may not deliver the result sorted (e.g., LSM search cursor).
                ArrayList<Integer> actualResults = new ArrayList<>();
                try {
                    while (resultCursor.hasNext()) {
                        resultCursor.next();
                        ITupleReference resultTuple = resultCursor.getTuple();
                        int actual = IntegerPointable.getInteger(resultTuple.getFieldData(0), resultTuple.getFieldStart(0));
                        actualResults.add(Integer.valueOf(actual));
                    }
                } catch (HyracksDataException e) {
                    if (e.getErrorCode() == ErrorCode.OCCURRENCE_THRESHOLD_PANIC_EXCEPTION) {
                        // Ignore panic queries.
                        continue;
                    } else {
                        throw e;
                    }
                }
                Collections.sort(actualResults);
                // Get expected results.
                List<Integer> expectedResults = new ArrayList<>();
                LSMInvertedIndexTestUtils.getExpectedResults(scanCountArray, testCtx.getCheckTuples(), searchDocument, tokenizer, testCtx.getFieldSerdes()[0], searchModifier, expectedResults, testCtx.getInvertedIndexType());
                Iterator<Integer> expectedIter = expectedResults.iterator();
                Iterator<Integer> actualIter = actualResults.iterator();
                while (expectedIter.hasNext() && actualIter.hasNext()) {
                    int expected = expectedIter.next();
                    int actual = actualIter.next();
                    if (actual != expected) {
                        fail("Query results do not match. Encountered: " + actual + ". Expected: " + expected + "");
                    }
                }
                if (expectedIter.hasNext()) {
                    fail("Query results do not match. Actual results missing.");
                }
                if (actualIter.hasNext()) {
                    fail("Query results do not match. Actual contains too many results.");
                }
            }
        } finally {
            resultCursor.close();
        }
    }
}
Also used : InvertedIndexSearchPredicate(org.apache.hyracks.storage.am.lsm.invertedindex.search.InvertedIndexSearchPredicate) ArrayList(java.util.ArrayList) IInvertedIndexAccessor(org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndexAccessor) HyracksDataException(org.apache.hyracks.api.exceptions.HyracksDataException) PermutingTupleReference(org.apache.hyracks.storage.am.common.tuples.PermutingTupleReference) ITupleReference(org.apache.hyracks.dataflow.common.data.accessors.ITupleReference) IIndexCursor(org.apache.hyracks.storage.common.IIndexCursor) IBinaryTokenizer(org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizer) IInvertedIndex(org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndex)

Aggregations

IIndexCursor (org.apache.hyracks.storage.common.IIndexCursor)23 ITupleReference (org.apache.hyracks.dataflow.common.data.accessors.ITupleReference)18 RangePredicate (org.apache.hyracks.storage.am.btree.impls.RangePredicate)15 ArrayList (java.util.ArrayList)8 HyracksDataException (org.apache.hyracks.api.exceptions.HyracksDataException)8 ILSMDiskComponentBulkLoader (org.apache.hyracks.storage.am.lsm.common.api.ILSMDiskComponentBulkLoader)7 ILSMIndexOperationContext (org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexOperationContext)6 MultiComparator (org.apache.hyracks.storage.common.MultiComparator)6 SearchPredicate (org.apache.hyracks.storage.am.rtree.impls.SearchPredicate)5 IIndexAccessor (org.apache.hyracks.storage.common.IIndexAccessor)5 ISearchPredicate (org.apache.hyracks.storage.common.ISearchPredicate)5 ArrayTupleBuilder (org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder)3 ArrayTupleReference (org.apache.hyracks.dataflow.common.comm.io.ArrayTupleReference)3 BTreeAccessor (org.apache.hyracks.storage.am.btree.impls.BTree.BTreeAccessor)3 CheckTuple (org.apache.hyracks.storage.am.common.CheckTuple)3 LSMIndexSearchCursor (org.apache.hyracks.storage.am.lsm.common.impls.LSMIndexSearchCursor)3 IInvertedIndexAccessor (org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndexAccessor)3 IBinaryComparatorFactory (org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory)2 ITreeIndexCursor (org.apache.hyracks.storage.am.common.api.ITreeIndexCursor)2 PermutingTupleReference (org.apache.hyracks.storage.am.common.tuples.PermutingTupleReference)2