com.googlecode.cqengine.query.option.QueryOptions Java Examples

The following examples show how to use com.googlecode.cqengine.query.option.QueryOptions. 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: 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 #2
Source File: HasTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testExists() {
    // Create an indexed collection (note: could alternatively use CQEngine.copyFrom() existing collection)...
    IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();

    Attribute<Car, String> NAME = new SimpleNullableAttribute<Car, String>("name") {
        public String getValue(Car car, QueryOptions queryOptions) { return car.name; }
    };
    // Add some indexes...
    cars.addIndex(StandingQueryIndex.onQuery(has(NAME)));
    cars.addIndex(StandingQueryIndex.onQuery(not(has(NAME))));

    // 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, null, "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")));

    Assert.assertEquals(cars.retrieve(has(NAME)).size(), 2);
    Assert.assertEquals(cars.retrieve(not(has(NAME))).size(), 1);
}
 
Example #3
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 #4
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDistinctKeys_BetweenExclusiveAscending(){
    ConnectionManager connectionManager = temporaryInMemoryDatabase.getConnectionManager(true);
    SQLiteIndex<String, Car, Integer> offHeapIndex = SQLiteIndex.onAttribute(
            Car.MODEL,
            Car.CAR_ID,
            new SimpleAttribute<Integer, Car>() {
                @Override
                public Car getValue(Integer carId, QueryOptions queryOptions) {
                    return CarFactory.createCar(carId);
                }
            }
    );
    offHeapIndex.addAll(createObjectSetOfCars(10), createQueryOptions(connectionManager));
    List<String> expected, actual;

    expected = Arrays.asList("Focus", "Fusion", "Hilux");
    actual = Lists.newArrayList(offHeapIndex.getDistinctKeys("Civic", false, "Insight", false, createQueryOptions(connectionManager)));
    assertEquals(expected, actual);
}
 
Example #5
Source File: HashIndex.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 #6
Source File: SQLiteIndexTest.java    From cqengine with Apache License 2.0 6 votes vote down vote up
static FilterQuery<Car, String> mockFilterQuery(){
    @SuppressWarnings("unchecked")
    FilterQuery<Car, String> filterQuery = (FilterQuery<Car, String>)mock(FilterQuery.class);
    when(filterQuery.matchesValue(Mockito.anyString(), any(QueryOptions.class))).thenAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocationOnMock) throws Throwable {
            Object[] args = invocationOnMock.getArguments();
            if (args != null && args.length == 2 && args[0] instanceof String) {
                String value = (String) args[0];
                return "abs".equals(value) || "gps".equals(value);
            }
            throw new IllegalStateException("matchesValue invocation not expected. Args " + Arrays.toString(args));
        }
    });
    return filterQuery;
}
 
Example #7
Source File: ReversedRadixTreeIndex.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 #8
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 #9
Source File: ObjectSetTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testFromObjectStore_IteratorClose() throws Exception {
    ObjectStore<Car> objectStore = mock(ObjectStore.class);
    CloseableIterator<Car> closeableIterator = mock(CloseableIterator.class);
    when(objectStore.iterator(Mockito.<QueryOptions>any())).thenReturn(closeableIterator);

    ObjectSet<Car> objectSet = ObjectSet.fromObjectStore(objectStore, noQueryOptions());
    CloseableIterator<Car> objectSetIterator = objectSet.iterator();
    objectSetIterator.close();
    Mockito.verify(closeableIterator, times(1)).close();
}
 
Example #10
Source File: Has.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesNonSimpleAttribute(Attribute<O, A> attribute, O object, QueryOptions queryOptions) {
    for (A attributeValue : attribute.getValues(object, queryOptions)) {
        if (attributeValue != null) {
            return true;
        }
    }
    return false;
}
 
Example #11
Source File: DiskPersistence.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Closes a {@link RequestScopeConnectionManager} if it is present in the given query options with key
 * {@link ConnectionManager}.
 *
 * @param queryOptions The query options supplied with the request into CQEngine.
 */
@Override
public void closeRequestScopeResources(QueryOptions queryOptions) {
    ConnectionManager connectionManager = queryOptions.get(ConnectionManager.class);
    if (connectionManager instanceof RequestScopeConnectionManager) {
        ((RequestScopeConnectionManager) connectionManager).close();
        queryOptions.remove(ConnectionManager.class);
    }
}
 
Example #12
Source File: GreaterThan.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
    A attributeValue = attribute.getValue(object, queryOptions);
    if (valueInclusive) {
        return value.compareTo(attributeValue) <= 0;
    }
    else {
        return value.compareTo(attributeValue) < 0;
    }
}
 
Example #13
Source File: FilteringIteratorTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testHasNextDoesNotAdvanceIterator(){
    List<String> testList = Arrays.asList("abc", "bcd", "cde");
    FilteringIterator<String> iterator = new FilteringIterator<String>(testList.iterator(), noQueryOptions()) {
        @Override
        public boolean isValid(String object, QueryOptions queryOptions) {
            return true;
        }
    };
    iterator.hasNext();
    iterator.hasNext();
    iterator.hasNext();
    assertThat(iterator.next(), is("abc"));
}
 
Example #14
Source File: NestedObjectsExample.java    From cqengine with Apache License 2.0 5 votes vote down vote up
public Iterable<String> getValues(User user, QueryOptions queryOptions) {
    return concat(transform(user.orders, new Function<Order, Iterable<String>>() {
        public Iterable<String> apply(Order order) {
            return transform(order.products, new Function<Product, String>() {
                public String apply(Product product) {
                    return product.name;
                }
            });
        }
    }));
}
 
Example #15
Source File: ConcurrentIndexedCollection.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void removeIndex(Index<O> index, QueryOptions queryOptions) {
    queryOptions = openRequestScopeResourcesIfNecessary(queryOptions);
    try {
        indexEngine.removeIndex(index, queryOptions);
    }
    finally {
        closeRequestScopeResourcesIfNecessary(queryOptions);
    }
}
 
Example #16
Source File: SQLiteIndex.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ObjectStore<O> objectStore, QueryOptions queryOptions) {

    final ConnectionManager connectionManager = getConnectionManager(queryOptions);
    final Connection connection = connectionManager.getConnection(this, queryOptions);
    pragmaJournalMode = DBQueries.getPragmaJournalModeOrNull(connection);
    pragmaSynchronous = DBQueries.getPragmaSynchronousOrNull(connection);
    canModifySyncAndJournaling = pragmaJournalMode != null && pragmaSynchronous != null;

    doAddAll(ObjectSet.fromObjectStore(objectStore, queryOptions), queryOptions, true);
}
 
Example #17
Source File: RadixTreeIndex.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean addAll(ObjectSet<O> objectSet, QueryOptions queryOptions) {
    try {
        boolean modified = false;
        final RadixTree<StoredResultSet<O>> tree = this.tree;
        for (O object : objectSet) {
            Iterable<A> attributeValues = getAttribute().getValues(object, queryOptions);
            for (A attributeValue : attributeValues) {

                // Look up StoredResultSet for the value...
                StoredResultSet<O> valueSet = tree.getValueForExactKey(attributeValue);
                if (valueSet == null) {
                    // No StoredResultSet, create and add one...
                    valueSet = createValueSet();
                    StoredResultSet<O> existingValueSet = tree.putIfAbsent(attributeValue, valueSet);
                    if (existingValueSet != null) {
                        // Another thread won race to add new value set, use that one...
                        valueSet = existingValueSet;
                    }
                }
                // Add the object to the StoredResultSet for this value...
                modified |= valueSet.add(object);
            }
        }
        return modified;
    }
    finally {
        objectSet.close();
    }
}
 
Example #18
Source File: ObjectSetTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testFromObjectStore_IsEmpty_False() throws Exception {
    ObjectStore<Car> objectStore = mock(ObjectStore.class);
    CloseableIterator<Car> closeableIterator = mock(CloseableIterator.class);
    when(closeableIterator.hasNext()).thenReturn(true);
    when(objectStore.iterator(Mockito.<QueryOptions>any())).thenReturn(closeableIterator);

    ObjectSet<Car> objectSet = ObjectSet.fromObjectStore(objectStore, noQueryOptions());
    Assert.assertEquals(false, objectSet.isEmpty());
    Mockito.verify(closeableIterator, times(1)).close();
}
 
Example #19
Source File: LessThan.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSimpleAttribute(SimpleAttribute<O, A> attribute, O object, QueryOptions queryOptions) {
    A attributeValue = attribute.getValue(object, queryOptions);
    if (valueInclusive) {
        return value.compareTo(attributeValue) >= 0;
    }
    else {
        return value.compareTo(attributeValue) > 0;
    }
}
 
Example #20
Source File: ConcurrentIndexedCollection.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean addAll(Collection<? extends O> c) {
    QueryOptions queryOptions = openRequestScopeResourcesIfNecessary(null);
    try {
        @SuppressWarnings({"unchecked"})
        Collection<O> objects = (Collection<O>) c;
        boolean modified = objectStore.addAll(objects, queryOptions);
        indexEngine.addAll(ObjectSet.fromCollection(objects), queryOptions);
        return modified;
    }
    finally {
        closeRequestScopeResourcesIfNecessary(queryOptions);
    }
}
 
Example #21
Source File: CompoundQuery.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p/>
 * This implementation for {@link CompoundQuery} iterates each of the child {@link Equal} queries of the
 * {@link And} query from which the {@link CompoundQuery} was constructed, and for each child {@link Equal} query,
 * tests if the given object matches that query.
 *
 * @return True if the object matches all of the child {@link Equal} queries, false if the object does not match
 * one or more child {@link Equal} queries
 */
@Override
public boolean matches(O object, QueryOptions queryOptions) {
    for (SimpleQuery<O, ?> simpleQuery : andQuery.getSimpleQueries()) {
        Equal<O, ?> equal = (Equal<O, ?>) simpleQuery;
        if (!equal.matches(object, queryOptions)) {
            return false;
        }
    }
    return true;
}
 
Example #22
Source File: ClusteredConcurrentIndexedCollection.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void removeFromHazelcast(QueryOptions queryOptions, O objectToRemove) {
    if (this.hasRemoteStorage) {
        this.lock.lock();
        try {
            this.map.remove(getKey(objectToRemove, queryOptions));
        } finally {
            this.lock.unlock();
        }
    }
}
 
Example #23
Source File: SuffixTreeIndex.java    From cqengine with Apache License 2.0 4 votes vote down vote up
/**
 * This is a no-op for this type of index.
 * @param queryOptions Optional parameters for the update
 */
@Override
public void destroy(QueryOptions queryOptions) {
    // No-op
}
 
Example #24
Source File: SimplifiedSQLiteIndex.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(A lowerBound, boolean lowerInclusive, A upperBound, boolean upperInclusive, QueryOptions queryOptions) {
    return backingIndex().getKeysAndValuesDescending(lowerBound, lowerInclusive, upperBound, upperInclusive, queryOptions);
}
 
Example #25
Source File: ComparativeQuery.java    From cqengine with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * @throws UnsupportedOperationException always
 */
@Override
default boolean matches(O object, QueryOptions queryOptions) {
    throw new UnsupportedOperationException("This method is not supported on comparative queries");
}
 
Example #26
Source File: PartialSortedKeyStatisticsAttributeIndex.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Override
public CloseableIterable<KeyValue<A, O>> getKeysAndValuesDescending(QueryOptions queryOptions) {
    return backingIndex().getKeysAndValuesDescending(queryOptions);
}
 
Example #27
Source File: AttributeMetadata.java    From cqengine with Apache License 2.0 4 votes vote down vote up
AttributeMetadata(KeyStatisticsIndex<A, O> index, Supplier<QueryOptions> openResourcesHandler, Consumer<QueryOptions> closeResourcesHandler) {
    this.index = index;
    this.openResourcesHandler = openResourcesHandler;
    this.closeResourcesHandler = closeResourcesHandler;
}
 
Example #28
Source File: PartialIndex.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Override
public void clear(QueryOptions queryOptions) {
    backingIndex().clear(queryOptions);
}
 
Example #29
Source File: ResultSetUnion.java    From cqengine with Apache License 2.0 4 votes vote down vote up
@Override
public QueryOptions getQueryOptions() {
    return queryOptions;
}
 
Example #30
Source File: AttributeMetadata.java    From cqengine with Apache License 2.0 4 votes vote down vote up
protected QueryOptions openResources() {
    return openResourcesHandler.get();
}