com.googlecode.cqengine.resultset.ResultSet Java Examples

The following examples show how to use com.googlecode.cqengine.resultset.ResultSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InvertedRadixTreeIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * If a query option specifying logical deduplication was supplied, wrap the given result sets in
 * {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
 * <p/>
 * An exception is if the index is built on a SimpleAttribute, we can avoid deduplication and always use
 * {@link ResultSetUnionAll}, because the same object could not exist in more than one {@link StoredResultSet}.
 *
 * @param results Provides the result sets to union
 * @param query The query for which the union is being constructed
 * @param queryOptions Specifies whether or not logical deduplication is required
 * @return A union view over the given result sets
 */
ResultSet<O> unionResultSets(Iterable<? extends ResultSet<O>> results, Query<O> query, QueryOptions queryOptions) {
    if (DeduplicationOption.isLogicalElimination(queryOptions)
            && !(getAttribute() instanceof SimpleAttribute || getAttribute() instanceof SimpleNullableAttribute)) {
        return new ResultSetUnion<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
    else {
        return new ResultSetUnionAll<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
}
 
Example #2
Source File: OffHeapPersistenceConcurrencyTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    sequenceLog.add(taskName + " started and about to access collection");
    ResultSet<Car> backgroundResults = collection.retrieve(between(Car.CAR_ID, 40, 59));
    Iterator<Car> iterator = backgroundResults.iterator();
    int count = 0;
    for (; iterator.hasNext() && count < 5; count++) {
        iterator.next();
    }
    sequenceLog.add(taskName + " pausing mid-read");
    sleep(millisecondsToPauseMidRequest);
    sequenceLog.add(taskName + " resuming read");
    while (iterator.hasNext()) {
        iterator.next();
        count++;
    }
    backgroundResults.close();
    sequenceLog.add(taskName + " finished reading " + count + " items");
}
 
Example #3
Source File: UniqueIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Override
public ResultSet<O> retrieve(final Query<O> query, final QueryOptions queryOptions) {
    Class<?> queryClass = query.getClass();
    if (queryClass.equals(Equal.class))
    {
        final ConcurrentMap<A, O> indexMap = this.indexMap;
        @SuppressWarnings("unchecked")
        Equal<O, A> equal = (Equal<O, A>) query;
        return retrieveEqual(equal, queryOptions, indexMap);
    }
    else if(queryClass.equals(In.class)){
        @SuppressWarnings("unchecked")
        In<O, A> in = (In<O, A>) query;
        return retrieveIn(in, queryOptions, indexMap);
    }
    throw new IllegalArgumentException("Unsupported query: " + query);
}
 
Example #4
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewResultSet_GetRetrievalCost() throws Exception{

    // Mocks
    ConnectionManager connectionManager = mock(ConnectionManager.class);

    // Iterator
    ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            ID_TO_OBJECT,
            "")

            .retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));

    assertEquals(SQLiteIndex.INDEX_RETRIEVAL_COST, carsWithAbs.getRetrievalCost());

}
 
Example #5
Source File: SuffixTreeIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions, final SuffixTree<StoredResultSet<O>> tree) {
    // Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
    final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
        @Override
        public Iterator<ResultSet<O>> iterator() {
            return new LazyIterator<ResultSet<O>>() {
                final Iterator<A> values = in.getValues().iterator();
                @Override
                protected ResultSet<O> computeNext() {
                    if (values.hasNext()){
                        return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions, tree);
                    }else{
                        return endOfData();
                    }
                }
            };
        }
    };
    return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
 
Example #6
Source File: SuffixTreeIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * If a query option specifying logical deduplication was supplied, wrap the given result sets in
 * {@link ResultSetUnion}, otherwise wrap in {@link ResultSetUnionAll}.
 * <p/>
 * An exception is if the index is built on a SimpleAttribute, we can avoid deduplication and always use
 * {@link ResultSetUnionAll}, because the same object could not exist in more than one {@link StoredResultSet}.
 *
 * @param results Provides the result sets to union
 * @param query The query for which the union is being constructed
 * @param queryOptions Specifies whether or not logical deduplication is required
 * @return A union view over the given result sets
 */
ResultSet<O> unionResultSets(Iterable<? extends ResultSet<O>> results, Query<O> query, QueryOptions queryOptions) {
    if (DeduplicationOption.isLogicalElimination(queryOptions)
            && !(getAttribute() instanceof SimpleAttribute || getAttribute() instanceof SimpleNullableAttribute)) {
        return new ResultSetUnion<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
    else {
        return new ResultSetUnionAll<O>(results, query, queryOptions) {
            @Override
            public int getRetrievalCost() {
                return INDEX_RETRIEVAL_COST;
            }
        };
    }
}
 
Example #7
Source File: NavigableIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions) {
    // Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
    final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
        @Override
        public Iterator<ResultSet<O>> iterator() {
            return new LazyIterator<ResultSet<O>>() {
                final Iterator<A> values = in.getValues().iterator();
                @Override
                protected ResultSet<O> computeNext() {
                    if (values.hasNext()){
                        return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions);
                    }else{
                        return endOfData();
                    }
                }
            };
        }
    };
    return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
 
Example #8
Source File: UniqueIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testUniqueIndex() {
    IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();

    // Add some indexes...
    cars.addIndex(UniqueIndex.onAttribute(Car.CAR_ID));
    cars.addIndex(HashIndex.onAttribute(Car.CAR_ID));

    // Add some objects to the collection...
    cars.add(new Car(1, "ford focus", "great condition, low mileage", Arrays.asList("spare tyre", "sunroof")));
    cars.add(new Car(2, "ford taurus", "dirty and unreliable, flat tyre", Arrays.asList("spare tyre", "radio")));
    cars.add(new Car(3, "honda civic", "has a flat tyre and high mileage", Arrays.asList("radio")));

    Query<Car> query = equal(Car.CAR_ID, 2);
    ResultSet<Car> rs = cars.retrieve(query);
    Assert.assertEquals("should prefer unique index over hash index", UniqueIndex.INDEX_RETRIEVAL_COST, rs.getRetrievalCost());

    Assert.assertEquals("should retrieve car 2", 2, rs.uniqueResult().carId);
}
 
Example #9
Source File: CQNDateMathTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testDateMath() {
    // Create a collection of Order objects, with shipDates 2015-08-01, 2015-08-02 and 2015-08-03...
    IndexedCollection<Order> collection = new ConcurrentIndexedCollection<Order>();
    collection.add(createOrder("2015-08-01"));
    collection.add(createOrder("2015-08-02"));
    collection.add(createOrder("2015-08-03"));

    // Create a parser for CQN queries on Order objects...
    CQNParser<Order> parser = CQNParser.forPojoWithAttributes(Order.class, createAttributes(Order.class));

    // Register a DateMathParser which can parse date math expressions
    // relative to the given date value for "now" ("2015-08-04").
    // The custom value for "now" can be omitted to have it always calculate relative to the current time...
    parser.registerValueParser(Date.class, new DateMathParser(createDate("2015-08-04")));

    // Retrieve orders whose ship date is between 3 days ago and 2 days ago...
    ResultSet<Order> results = parser.retrieve(collection, "between(\"shipDate\", \"-3DAYS\", \"-2DAYS\")");

    // Assert that the following two orders are returned...
    Assert.assertTrue(results.contains(createOrder("2015-08-01")));
    Assert.assertTrue(results.contains(createOrder("2015-08-02")));
    Assert.assertEquals(2, results.size());
}
 
Example #10
Source File: CompoundIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link CompoundIndex} using the given {@link Quantizer} on the given combination of attributes.
 * <p/>
 * @param indexMapFactory A factory used to create the main map-based data structure used by the index
 * @param valueSetFactory A factory used to create sets to store values in the index
 * @param attributes The combination of simple attributes on which index will be built
 * @param quantizer A {@link Quantizer} to use in this index
 * @param <O> The type of the object containing the attributes
 * @return A {@link CompoundIndex} based on these attributes
 */
public static <O> CompoundIndex<O> withQuantizerOnAttributes(Factory<ConcurrentMap<CompoundValueTuple<O>, StoredResultSet<O>>> indexMapFactory, Factory<StoredResultSet<O>> valueSetFactory, final Quantizer<CompoundValueTuple<O>> quantizer, Attribute<O, ?>... attributes) {
    List<Attribute<O, ?>> attributeList = Arrays.asList(attributes);
    CompoundAttribute<O> compoundAttribute = new CompoundAttribute<O>(attributeList);
    return new CompoundIndex<O>(indexMapFactory, valueSetFactory, compoundAttribute) {

        // ---------- Override the hook methods related to Quantizer ----------

        @Override
        protected ResultSet<O> filterForQuantization(ResultSet<O> resultSet, final Query<O> query, QueryOptions queryOptions) {
            return new QuantizedResultSet<O>(resultSet, query, queryOptions);
        }

        @Override
        protected CompoundValueTuple<O> getQuantizedValue(CompoundValueTuple<O> attributeValue) {
            return quantizer.getQuantizedValue(attributeValue);
        }

        @Override
        public boolean isQuantized() {
            return true;
        }
    };
}
 
Example #11
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewResultSet_FilterQuery_GetRetrievalCost(){

    // Mocks
    FilterQuery<Car, String> filterQuery = mockFilterQuery();
    ConnectionManager connectionManager = mock(ConnectionManager.class);

    // Iterator
    ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            ID_TO_OBJECT,
            "")

            .retrieve(filterQuery, createQueryOptions(connectionManager));

    assertEquals(carsWithAbs.getRetrievalCost(), SQLiteIndex.INDEX_RETRIEVAL_COST_FILTERING);

}
 
Example #12
Source File: CollectionQueryEngine.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve results and then sort them afterwards (if sorting is required).
 */
ResultSet<O> retrieveWithoutIndexOrdering(Query<O> query, QueryOptions queryOptions, OrderByOption<O> orderByOption) {
    ResultSet<O> resultSet;
    resultSet = retrieveRecursive(query, queryOptions);

    // Check if we need to wrap ResultSet to order and/or deduplicate results (deduplicate using MATERIAIZE rather
    // than LOGICAL_ELIMINATION strategy)...
    final boolean applyMaterializedDeduplication = DeduplicationOption.isMaterialize(queryOptions);
    if (orderByOption != null) {
        // An OrderByOption was specified, wrap the results in an MaterializedOrderedResultSet.
        // -> This will implicitly sort AND deduplicate the results returned by the ResultSet.iterator() method.
        // -> However note this does not mean we will also deduplicate the count returned by ResultSet.size()!
        // -> Deduplicating the count returned by size() is expensive, so we only do this if the client
        //    requested both ordering AND deduplication explicitly (hence we pass applyMaterializeDeduplication)...
        Comparator<O> comparator = new AttributeOrdersComparator<O>(orderByOption.getAttributeOrders(), queryOptions);
        resultSet = new MaterializedOrderedResultSet<O>(resultSet, comparator, applyMaterializedDeduplication);
    }
    else if (applyMaterializedDeduplication) {
        // A DeduplicationOption was specified, wrap the results in an MaterializedDeduplicatedResultSet,
        // which will deduplicate (but not sort) results. O(n) time complexity to subsequently iterate...
        resultSet = new MaterializedDeduplicatedResultSet<O>(resultSet);
    }
    return resultSet;
}
 
Example #13
Source File: ResultSets.java    From cqengine with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Collection-like view of the given ResultSet.
 * <p/>
 * The collection simply delegates to the ResultSet, which in turn will reflect
 * any changes made to the underlying IndexedCollection by other threads.
 * For example consecutive calls to the size() method
 * may return different values if objects are added to or removed from the IndexedCollection.
 *
 * @param resultSet The ResultSet to wrap
 * @return A Collection-like view of the given ResultSet
 */
public static <O> Collection<O> asCollection(final ResultSet<O> resultSet) {
    return new AbstractCollection<O>() {
        @Override
        public Iterator<O> iterator() {
            return resultSet.iterator();
        }
        @Override
        public int size() {
            return resultSet.size();
        }

        @Override
        public boolean contains(Object o) {
            @SuppressWarnings("unchecked")
            O object = (O)o;
            return resultSet.contains(object);
        }

        @Override
        public boolean isEmpty() {
            return resultSet.isEmpty();
        }
    };
}
 
Example #14
Source File: ReversedRadixTreeIndex.java    From cqengine with Apache License 2.0 6 votes vote down vote up
protected ResultSet<O> retrieveIn(final In<O, A> in, final QueryOptions queryOptions, final ReversedRadixTree<StoredResultSet<O>> tree) {
    // Process the IN query as the union of the EQUAL queries for the values specified by the IN query.
    final Iterable<? extends ResultSet<O>> results = new Iterable<ResultSet<O>>() {
        @Override
        public Iterator<ResultSet<O>> iterator() {
            return new LazyIterator<ResultSet<O>>() {
                final Iterator<A> values = in.getValues().iterator();
                @Override
                protected ResultSet<O> computeNext() {
                    if (values.hasNext()){
                        return retrieveEqual(new Equal<O, A>(in.getAttribute(), values.next()), queryOptions, tree);
                    }else{
                        return endOfData();
                    }
                }
            };
        }
    };
    return deduplicateIfNecessary(results, in, getAttribute(), queryOptions, INDEX_RETRIEVAL_COST);
}
 
Example #15
Source File: DeduplicationTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeduplication_Materialize() {
    IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
    cars.add(new Car(1, "Ford", "Focus", BLUE, 5, 1000.0, Collections.<String>emptyList(), Collections.emptyList()));
    cars.addIndex(HashIndex.onAttribute(Car.COLOR));
    cars.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));

    Query<Car> query = or(
            equal(COLOR, BLUE),
            equal(MANUFACTURER, "Ford")
    );
    ResultSet<Car> results;
    results = cars.retrieve(query);
    assertEquals(2, results.size());

    DeduplicationOption deduplicate = deduplicate(DeduplicationStrategy.MATERIALIZE);
    results = cars.retrieve(query, queryOptions(deduplicate));
    assertEquals(1, results.size());
}
 
Example #16
Source File: DeduplicationTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeduplication_Logical() {
    IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
    cars.add(new Car(1, "Ford", "Focus", BLUE, 5, 1000.0, Collections.<String>emptyList(), Collections.emptyList()));
    cars.addIndex(HashIndex.onAttribute(Car.COLOR));
    cars.addIndex(HashIndex.onAttribute(Car.MANUFACTURER));

    Query<Car> query = or(
            equal(COLOR, BLUE),
            equal(MANUFACTURER, "Ford")
    );
    ResultSet<Car> results;
    results = cars.retrieve(query);
    assertEquals(2, results.size());

    DeduplicationOption deduplicate = deduplicate(DeduplicationStrategy.LOGICAL_ELIMINATION);
    results = cars.retrieve(query, queryOptions(deduplicate));
    assertEquals(1, results.size());
}
 
Example #17
Source File: SQLiteObjectStore.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableIterator<O> iterator(QueryOptions queryOptions) {
    final ResultSet<O> rs = backingIndex.retrieve(has(primaryKeyAttribute), queryOptions);
    final Iterator<O> i = rs.iterator();
    class CloseableIteratorImpl extends UnmodifiableIterator<O> implements CloseableIterator<O> {

        @Override
        public boolean hasNext() {
            return i.hasNext();
        }

        @Override
        public O next() {
            return i.next();
        }

        @Override
        public void close() {
            rs.close();
        }
    }
    return new CloseableIteratorImpl();
}
 
Example #18
Source File: ResultSetUnion.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the sum of the retrieval costs of the the underlying {@code ResultSet}s.
 * @return the sum of the retrieval costs of the the underlying {@code ResultSet}s
 */
@Override
public int getRetrievalCost() {
    long retrievalCost = 0;
    for (ResultSet<O> resultSet : this.resultSets) {
        retrievalCost = retrievalCost + resultSet.getRetrievalCost();
    }
    return (int)Math.min(retrievalCost, Integer.MAX_VALUE);
}
 
Example #19
Source File: ResultSetIntersection.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the retrieval cost from the underlying {@code ResultSet} which has the lowest merge cost.
 * @return the retrieval cost from the underlying {@code ResultSet} which has the lowest merge cost
 */
@Override
public int getRetrievalCost() {
    if (resultSets.isEmpty()) {
        return 0;
    }
    else {
        ResultSet<O> lowestMergeCostResultSet = resultSets.get(0);
        return lowestMergeCostResultSet.getRetrievalCost();
    }
}
 
Example #20
Source File: ResultSetIntersection.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Closes all of the underlying {@code ResultSet}s.
 */
@Override
public void close() {
    for (ResultSet<O> resultSet : this.resultSets) {
        resultSet.close();
    }
}
 
Example #21
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewResultSet_GetMergeCost() throws Exception{

    // Mocks
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    when(connection.prepareStatement("SELECT COUNT(objectKey) FROM " + TABLE_NAME + " WHERE value = ?;")).thenReturn(preparedStatement);
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(preparedStatement);
    when(resultSet.next()).thenReturn(true);
    when(resultSet.getInt(1)).thenReturn(3);

    // Iterator
    ResultSet<Car> carsWithAbs = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            ID_TO_OBJECT,
            "")

            .retrieve(equal(Car.FEATURES, "abs"), createQueryOptions(connectionManager));

    assertNotNull(carsWithAbs);
    int size = carsWithAbs.getMergeCost();

    assertEquals(3, size);
    verify(connection, times(0)).close();

}
 
Example #22
Source File: ResultSetUnion.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the given object is contained in <b><u>any</u></b> underlying ResultSets.
 * @param object An object to check if contained
 * @return true if the given object is contained in <b><u>any</u></b> underlying ResultSets, false if it is not
 * contained in any ResultSets or if there are no underlying result sets
 */
@Override
public boolean contains(O object) {
    for (ResultSet<O> resultSet : this.resultSets) {
        if (resultSet.contains(object)) {
            return true;
        }
    }
    return false;
}
 
Example #23
Source File: CQNQueryDemo.java    From cqengine with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    CQNParser<Car> parser = CQNParser.forPojoWithAttributes(Car.class, createAttributes(Car.class));
    IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
    cars.addAll(CarFactory.createCollectionOfCars(10));

    ResultSet<Car> results = parser.retrieve(cars,
                                    "and(" +
                                        "or(equal(\"manufacturer\", \"Ford\"), equal(\"manufacturer\", \"Honda\")), " +
                                        "lessThanOrEqualTo(\"price\", 5000.0), " +
                                        "not(in(\"color\", GREEN, WHITE))" +
                                    ")");

    results.forEach(System.out::println); // Prints: Ford Focus, Ford Fusion, Honda Accord
}
 
Example #24
Source File: CollectionQueryEngine.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves a union of the objects matching {@link SimpleQuery}s.
 * <p/>
 * <i>Definitions:
 * For a definition of <u>retrieval cost</u> see {@link ResultSet#getRetrievalCost()}.
 * For a definition of <u>merge cost</u> see {@link ResultSet#getMergeCost()}.
 * </i>
 * <p/>
 * The algorithm employed by this method is as follows.
 * <p/>
 * For each {@link SimpleQuery} supplied, retrieves a {@link ResultSet} for that {@link SimpleQuery}
 * from the index with the lowest <u>retrieval cost</u> which supports that {@link SimpleQuery}.
 * <p/>
 * The method then returns these {@link ResultSet}s in either a {@link ResultSetUnion} or a
 * {@link ResultSetUnionAll} object, depending on whether {@code logicalDuplicateElimination} was specified
 * or not. These concatenate the wrapped {@link ResultSet}s when iterated. In the case of {@link ResultSetUnion},
 * this also ensures that duplicate objects are not returned more than once, by means of logical elimination via
 * set theory rather than maintaining a record of all objects iterated.
 *
 * @param queries A collection of {@link SimpleQuery} objects to be retrieved and unioned
 * @param queryOptions Optional parameters for the query
 * supplied specifying strategy {@link DeduplicationStrategy#LOGICAL_ELIMINATION}
 * @return A {@link ResultSet} which provides objects matching the union of results for each of the
 * {@link SimpleQuery}s
 */
ResultSet<O> retrieveUnionOfSimpleQueries(final Collection<SimpleQuery<O, ?>> queries, final QueryOptions queryOptions) {
    Iterable<ResultSet<O>> resultSetsToUnion = new Iterable<ResultSet<O>>() {
        @Override
        public Iterator<ResultSet<O>> iterator() {
            return new UnmodifiableIterator<ResultSet<O>>() {

                Iterator<SimpleQuery<O, ?>> queriesIterator = queries.iterator();
                @Override
                public boolean hasNext() {
                    return queriesIterator.hasNext();
                }

                @Override
                public ResultSet<O> next() {
                    return retrieveSimpleQuery(queriesIterator.next(), queryOptions);
                }
            };
        }
    };
    @SuppressWarnings("unchecked")
    Collection<Query<O>> queriesTyped = (Collection<Query<O>>)(Collection<? extends Query<O>>)queries;
    Query<O> query = queriesTyped.size() == 1 ? queriesTyped.iterator().next() : new Or<O>(queriesTyped);
    // Perform deduplication as necessary...
    if (DeduplicationOption.isLogicalElimination(queryOptions)) {
        // Use the index merge strategy if it was requested and indexes are available for all result sets...
        boolean indexMergeStrategyEnabled = isFlagEnabled(queryOptions, PREFER_INDEX_MERGE_STRATEGY);
        boolean useIndexMergeStrategy = indexMergeStrategyEnabled && indexesAvailableForAllResultSets(resultSetsToUnion);
        return new ResultSetUnion<O>(resultSetsToUnion, query, queryOptions, useIndexMergeStrategy);
    }
    else {
        return new ResultSetUnionAll<O>(resultSetsToUnion, query, queryOptions);
    }
}
 
Example #25
Source File: ResultSetUnionAll.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the sum of the retrieval costs of the the underlying {@code ResultSet}s.
 * @return the sum of the retrieval costs of the the underlying {@code ResultSet}s
 */
@Override
public int getRetrievalCost() {
    long retrievalCost = 0;
    for (ResultSet<O> resultSet : this.resultSets) {
        retrievalCost = retrievalCost + resultSet.getRetrievalCost();
    }
    return (int)Math.min(retrievalCost, Integer.MAX_VALUE);
}
 
Example #26
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewResultSet_FilterQuery_GetMergeCost() throws Exception{

    // Mocks
    FilterQuery<Car, String> filterQuery = mockFilterQuery();
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class), anyQueryOptions())).thenReturn(connection);
    when(connection.prepareStatement("SELECT COUNT(objectKey) FROM " + TABLE_NAME + " ;")).thenReturn(preparedStatement);
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(preparedStatement);
    when(resultSet.next()).thenReturn(true);
    when(resultSet.getInt(1)).thenReturn(3);

    // Iterator
    ResultSet<Car> cars = new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES,
            OBJECT_TO_ID,
            ID_TO_OBJECT,
            "")

            .retrieve(filterQuery, createQueryOptions(connectionManager));

    assertNotNull(cars);
    int mergeCost = cars.getMergeCost();

    assertEquals(3, mergeCost);
    verify(connection, times(0)).close();
}
 
Example #27
Source File: CollectionQueryEngine.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link #retrieveUnionOfSimpleQueries(Collection, QueryOptions)}
 * except for {@link ComparativeQuery}.
 */
ResultSet<O> retrieveUnionOfComparativeQueries(final Collection<ComparativeQuery<O, ?>> queries, final QueryOptions queryOptions) {
    Iterable<ResultSet<O>> resultSetsToUnion = new Iterable<ResultSet<O>>() {
        @Override
        public Iterator<ResultSet<O>> iterator() {
            return new UnmodifiableIterator<ResultSet<O>>() {

                Iterator<ComparativeQuery<O, ?>> queriesIterator = queries.iterator();
                @Override
                public boolean hasNext() {
                    return queriesIterator.hasNext();
                }

                @Override
                public ResultSet<O> next() {
                    return retrieveComparativeQuery(queriesIterator.next(), queryOptions);
                }
            };
        }
    };
    @SuppressWarnings("unchecked")
    Collection<Query<O>> queriesTyped = (Collection<Query<O>>)(Collection<? extends Query<O>>)queries;
    Query<O> query = queriesTyped.size() == 1 ? queriesTyped.iterator().next() : new Or<O>(queriesTyped);
    // Perform deduplication as necessary...
    if (DeduplicationOption.isLogicalElimination(queryOptions)) {
        // Note: we always use the index merge strategy to merge results for comparative queries...
        return new ResultSetUnion<O>(resultSetsToUnion, query, queryOptions, true);
    }
    else {
        return new ResultSetUnionAll<O>(resultSetsToUnion, query, queryOptions);
    }
}
 
Example #28
Source File: LongestPrefixTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
public void validateLongestPrefixWithCache(Query<MobileTerminating> q, IndexedCollection<MobileTerminating> cache, String expectedOperator, Integer expectedCount) {
    ResultSet<MobileTerminating> res = cache.retrieve(q, queryOptions(orderBy(ascending(MobileTerminating.OPERATOR_NAME))));
    assertEquals(expectedCount, (Integer)res.size());
    Iterator<String> expectedOperators = Arrays.asList(expectedOperator.split(",")).iterator();
    for (MobileTerminating mt : res) {
        assertEquals(expectedOperators.next(), mt.getOperatorName());
    }
}
 
Example #29
Source File: ResultSetDifference.java    From cqengine with Apache License 2.0 5 votes vote down vote up
public ResultSetDifference(ResultSet<O> firstResultSet, ResultSet<O> secondResultSet, Query<O> query, QueryOptions queryOptions, boolean indexMergeStrategyEnabled) {
    this.firstResultSet = ResultSets.wrapWithCostCachingIfNecessary(firstResultSet);
    this.secondResultSet = ResultSets.wrapWithCostCachingIfNecessary(secondResultSet);
    this.query = query;
    this.queryOptions = queryOptions;
    // If index merge strategy is enabled, validate that we can actually use it for this particular negation...
    if (indexMergeStrategyEnabled) {
        if (this.secondResultSet.getRetrievalCost() == Integer.MAX_VALUE) { //note getRetrievalCost() is on the cost-caching wrapper
            // We cannot use index merge strategy for this negation
            // because the second ResultSet is not backed by an index...
            indexMergeStrategyEnabled = false;
        }
    }
    this.indexMergeStrategyEnabled = indexMergeStrategyEnabled;
}
 
Example #30
Source File: NoneTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoneOr() {
    IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
    indexedCollection.addAll(asList(1, 2, 3, 4, 5));
    IndexedCollection<Integer> collection = indexedCollection;
    final Or<Integer> query = or(
            none(Integer.class),
            lessThan(selfAttribute(Integer.class), 3)
    );
    ResultSet<Integer> results = collection.retrieve(query);
    assertEquals(2, results.size());
    assertTrue(results.iterator().hasNext());
}