Java Code Examples for com.googlecode.cqengine.IndexedCollection#retrieve()

The following examples show how to use com.googlecode.cqengine.IndexedCollection#retrieve() . 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: GenerateAttributeByteCode.java    From cqengine with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    // Generate an attribute from bytecode to read the Car.model field...
    Map<String, ? extends Attribute<Car, ?>> attributes = AttributeBytecodeGenerator.createAttributes(Car.class);
    Attribute<Car, String> MODEL = (Attribute<Car, String>) attributes.get("model");

    // Create a collection of 10 Car objects (Ford Focus, Honda Civic etc.)...
    IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
    cars.addAll(CarFactory.createCollectionOfCars(10));

    // Retrieve the cars whose Car.model field is "Civic" (i.e. the Honda Civic)...
    ResultSet<Car> results = cars.retrieve(equal(MODEL, "Civic"));
    for (Car car : results) {
        System.out.println(car);
    }
    // ..prints:
    // Car{carId=3, manufacturer='Honda', model='Civic', color=WHITE, doors=5, price=4000.0, features=[grade b]}
}
 
Example 2
Source File: ThreeWayJoin.java    From cqengine with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    IndexedCollection<User> users = new ConcurrentIndexedCollection<User>();
    users.add(new User(1, "Joe"));
    users.add(new User(2, "Jane"));
    users.add(new User(3, "Jesse"));

    IndexedCollection<Role> roles = new ConcurrentIndexedCollection<Role>();
    roles.add(new Role(1, "CEO"));
    roles.add(new Role(2, "Manager"));
    roles.add(new Role(3, "Employee"));

    IndexedCollection<UserRole> userRoles = new ConcurrentIndexedCollection<UserRole>();
    userRoles.add(new UserRole(1, 3)); // Joe is an Employee
    userRoles.add(new UserRole(2, 2)); // Jane is a Manager
    userRoles.add(new UserRole(3, 2)); // Jesse is a Manager

    // Retrieve Users who are managers...
    Query<User> usersWhoAreManagers =
            existsIn(userRoles, User.USER_ID, UserRole.USER_ID,
                    existsIn(roles, UserRole.ROLE_ID, Role.ROLE_ID, equal(Role.ROLE_NAME, "Manager")));

    for (User u : users.retrieve(usersWhoAreManagers)) {
        System.out.println(u.userName);
    }
    // ..prints: Jane, Jesse
}
 
Example 3
Source File: IndexOrderingDemo.java    From cqengine with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
    cars.addIndex(NavigableIndex.onAttribute(Car.FEATURES));
    cars.addIndex(NavigableIndex.onAttribute(forObjectsMissing(Car.FEATURES)));
    cars.addAll(CarFactory.createCollectionOfCars(100));

    ResultSet<Car> results = cars.retrieve(
            between(Car.CAR_ID, 40, 50),
            queryOptions(
                    orderBy(ascending(missingLast(Car.FEATURES))),
                    applyThresholds(threshold(INDEX_ORDERING_SELECTIVITY, 1.0))
            )
    );
    for (Car car : results) {
        System.out.println(car); // prints cars 40 -> 50, using the index on Car.FEATURES to accelerate ordering
    }
}
 
Example 4
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 5
Source File: SqlExists.java    From cqengine with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // Create an indexed collection of cars...
    IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
    cars.add(new Car(1, "Ford Focus", "great condition, low mileage", asList("spare tyre", "sunroof")));
    cars.add(new Car(2, "Ford Taurus", "dirty and unreliable, flat tyre", asList("spare tyre", "radio")));
    cars.add(new Car(3, "Honda Civic", "has a flat tyre and high mileage", asList("radio")));
    cars.add(new Car(4, "BMW M3", "2013 model", asList("radio", "convertible")));

    // Create an indexed collection of garages...
    final IndexedCollection<Garage> garages = new ConcurrentIndexedCollection<Garage>();
    garages.add(new Garage(1, "Joe's garage", "London", asList("Ford Focus", "Honda Civic")));
    garages.add(new Garage(2, "Jane's garage", "Dublin", asList("BMW M3")));
    garages.add(new Garage(3, "John's garage", "Dublin", asList("Ford Focus", "Ford Taurus")));
    garages.add(new Garage(4, "Jill's garage", "Dublin", asList("Ford Focus")));

    // Query: Cars which are convertible or which have a sunroof, which can be serviced in Dublin...
    Query<Car> carsQuery = and(
            in(Car.FEATURES, "sunroof", "convertible"),
            existsIn(garages,
                    Car.NAME,
                    Garage.BRANDS_SERVICED,
                    equal(Garage.LOCATION, "Dublin")
            )
    );

    for (Car car : cars.retrieve(carsQuery)) {
        System.out.println(car.name + " has a sunroof or is convertible, and can be serviced in Dublin");
    }
    /* ..prints:

        BMW M3 has a sunroof or is convertible, and can be serviced in Dublin
        Ford Focus has a sunroof or is convertible, and can be serviced in Dublin
     */
}
 
Example 6
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 7
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());
}
 
Example 8
Source File: NoneTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoneAnd() {
    IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
    indexedCollection.addAll(asList(1, 2, 3, 4, 5));
    IndexedCollection<Integer> collection = indexedCollection;
    final And<Integer> query = and(
            none(Integer.class),
            lessThan(selfAttribute(Integer.class), 3)
    );
    ResultSet<Integer> results = collection.retrieve(query);
    assertEquals(0, results.size());
    assertFalse(results.iterator().hasNext());
}
 
Example 9
Source File: NoneTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testNone() {
    IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
    indexedCollection.addAll(asList(1, 2, 3, 4, 5));
    IndexedCollection<Integer> collection = indexedCollection;
    Query<Integer> query = none(Integer.class);
    ResultSet<Integer> results = collection.retrieve(query);
    assertEquals(0, results.size());
    assertFalse(results.iterator().hasNext());
}
 
Example 10
Source File: DynamicExample.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    // Generate attributes dynamically for fields in the given POJO...
    Map<String, Attribute<Car, Comparable>> attributes = DynamicIndexer.generateAttributesForPojo(Car.class);
    // Build indexes on the dynamically generated attributes...
    IndexedCollection<Car> cars = DynamicIndexer.newAutoIndexedCollection(attributes.values());

    // Add some objects to the collection...
    cars.add(new Car(1, "ford", "focus", 4, 9000));
    cars.add(new Car(2, "ford", "mondeo", 5, 10000));
    cars.add(new Car(2, "ford", "fiesta", 3, 2000));
    cars.add(new Car(3, "honda", "civic", 5, 11000));

    Query<Car> query = and(
            equal(attributes.get("manufacturer"), "ford"),
            lessThan(attributes.get("doors"), value(5)),
            greaterThan(attributes.get("horsepower"), value(3000))
    );
    ResultSet<Car> results = cars.retrieve(query);

    System.out.println("Ford cars with less than 5 doors and horsepower greater than 3000:- ");
    System.out.println("Using NavigableIndex: " + (results.getRetrievalCost() == 40));
    for (Car car : results) {
        System.out.println(car);
    }

    // Prints:
    //    Ford cars with less than 5 doors and horsepower greater than 3000:-
    //    Using NavigableIndex: true
    //    Car{carId=1, manufacturer='ford', model='focus', doors=4, horsepower=9000}
}
 
Example 11
Source File: TransactionalIndexedCollectionDemo.java    From cqengine with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // Create example Car objects...
    Car car1 = CarFactory.createCar(1); // "Ford Fusion"
    Car car2 = CarFactory.createCar(2); // "Ford Taurus"
    Car car3 = CarFactory.createCar(3); // "Honda Civic"
    Car car4 = CarFactory.createCar(4); // "Honda Accord"

    // We will store the cars in TransactionalIndexedCollection, which provides MVCC support...
    IndexedCollection<Car> cars = new TransactionalIndexedCollection<Car>(Car.class);

    // ===== Examples of modifying the collection using MVCC transactions... =====

    // Add 4 cars in a single transaction...
    cars.addAll(asList(car1, car2, car3, car4));

    // Remove 2 cars in a single transaction...
    cars.removeAll(asList(car3, car4));

    // Replace 1 car with 2 other cars in a single transaction...
    cars.update(asList(car2), asList(car3, car4));

    // ===== Examples of querying the collection using MVCC transactions... =====

    // Retrieve with READ_COMMITTED transaction isolation...
    ResultSet<Car> results = cars.retrieve(equal(Car.MANUFACTURER, "Ford"));
    try {
        for (Car car : results) {
            System.out.println(car); // prints car 1 ("Ford Fusion")
        }
    }
    finally {
        results.close(); // ..close the ResultSet when finished reading!
    }
}
 
Example 12
Source File: Replace.java    From cqengine with Apache License 2.0 5 votes vote down vote up
static Car retrieveOnlyOneVersion(IndexedCollection<Car> cars, int carId) {
    Query<Car> query = equal(Car.CAR_ID, carId);
    ResultSet<Car> multipleCarVersions = cars.retrieve(query);
    // Wrap in a result set which will return only one car per version number...
    ResultSet<Car> deduplicatedCars = new DeduplicatingResultSet<Car, Integer>(Car.CAR_ID, multipleCarVersions, query, noQueryOptions());

    return deduplicatedCars.uniqueResult();
}
 
Example 13
Source File: AllTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllAnd() {
    IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
    indexedCollection.addAll(asList(1, 2, 3, 4, 5));
    IndexedCollection<Integer> collection = indexedCollection;
    final And<Integer> query = and(
            all(Integer.class),
            lessThan(selfAttribute(Integer.class), 3)
    );
    ResultSet<Integer> results = collection.retrieve(query);
    assertEquals(2, results.size());
    assertTrue(results.iterator().hasNext());
}
 
Example 14
Source File: WrappingPersistenceTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrappingPersistence() {
    Collection<Car> backingCollection = new LinkedHashSet<Car>();
    backingCollection.addAll(CarFactory.createCollectionOfCars(3)); // CarIds 0, 1, 2

    IndexedCollection<Car> indexedCollection = new ConcurrentIndexedCollection<Car>(
            WrappingPersistence.aroundCollection(backingCollection)
    );

    indexedCollection.addIndex(NavigableIndex.onAttribute(Car.CAR_ID));

    ResultSet<Car> results = indexedCollection.retrieve(greaterThan(Car.CAR_ID, 0));

    // Assert that the index will be used...
    assertNotEquals(Integer.MAX_VALUE, results.getRetrievalCost());

    // Assert correct results are returned...
    Set<Integer> expectedCarIds, actualCarIds;
    expectedCarIds = asSet(1, 2);
    actualCarIds = extractCarIds(results, new HashSet<Integer>());
    assertEquals(expectedCarIds, actualCarIds);

    // Add that a new object added to the IndexedCollection...
    indexedCollection.add(CarFactory.createCar(3));

    // Assert the new object was added to the backing collection...
    expectedCarIds = asSet(0, 1, 2, 3);
    actualCarIds = extractCarIds(backingCollection, new HashSet<Integer>());
    assertEquals(expectedCarIds, actualCarIds);
}
 
Example 15
Source File: ResultSetsTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsCollection() throws Exception {
    IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
    indexedCollection.addAll(asList("how", "now", "brown", "cow"));

    ResultSet<String> resultSet = indexedCollection.retrieve(all(String.class));
    Collection<String> collection = ResultSets.asCollection(resultSet);

    assertEquals(resultSet.size(), collection.size());
    assertEquals(resultSet.size(), IteratorUtil.countElements(collection));
    assertEquals(resultSet.isEmpty(), collection.isEmpty());
    assertTrue(collection.contains("now"));
    assertFalse(collection.contains("baz"));
}
 
Example 16
Source File: AllTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllOr() {
    IndexedCollection<Integer> indexedCollection = new ConcurrentIndexedCollection<Integer>();
    indexedCollection.addAll(asList(1, 2, 3, 4, 5));
    IndexedCollection<Integer> collection = indexedCollection;
    final Or<Integer> query = or(
            all(Integer.class),
            lessThan(selfAttribute(Integer.class), 3)
    );
    ResultSet<Integer> results = collection.retrieve(query, queryOptions(deduplicate(LOGICAL_ELIMINATION)));
    assertEquals(5, results.size());
    assertTrue(results.iterator().hasNext());
}
 
Example 17
Source File: StringMatchesRegexTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringMatchesRegexNegatedWithIndex() {
    Query<String> query = not(matchesRegex(selfAttribute(String.class), "[fb].*"));
    IndexedCollection<String> indexedCollection = new ConcurrentIndexedCollection<String>();
    indexedCollection.addAll(asList("foo1", "foo2", "bar", "baz", "car"));
    IndexedCollection<String> collection = indexedCollection;
    collection.addIndex(StandingQueryIndex.onQuery(query));
    ResultSet<String> results = collection.retrieve(query);
    assertEquals(1, results.size());
    assertTrue(results.iterator().hasNext());
}
 
Example 18
Source File: CompositePersistenceTest.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Tests a configuration where the collection is stored off-heap, one index is on-disk, and one index is on-heap.
 */
@Test
public void testCompositePersistence_EndToEnd() {
    OffHeapPersistence<Car, Integer> offHeapPersistence = OffHeapPersistence.onPrimaryKey(Car.CAR_ID);
    DiskPersistence<Car, Integer> diskPersistence = DiskPersistence.onPrimaryKey(Car.CAR_ID);
    IndexedCollection<Car> collection = new ConcurrentIndexedCollection<Car>(CompositePersistence.of(
            offHeapPersistence,
            diskPersistence,
            singletonList(OnHeapPersistence.onPrimaryKey(Car.CAR_ID))
    ));

    collection.addIndex(DiskIndex.onAttribute(Car.MANUFACTURER));
    collection.addIndex(OffHeapIndex.onAttribute(Car.MODEL));
    collection.addIndex(NavigableIndex.onAttribute(Car.PRICE));

    collection.addAll(CarFactory.createCollectionOfCars(1000));

    ResultSet<Car> results = null;
    try {
        results = collection.retrieve(
                and(
                        or(
                                equal(Car.MANUFACTURER, "Ford"),
                                equal(Car.MODEL, "Avensis")
                        ),
                        lessThan(Car.PRICE, 6000.0)
                )
        );
        Assert.assertEquals(300, results.size());

        Assert.assertTrue(offHeapPersistence.getBytesUsed() > 4096); // example: 163840
        Assert.assertTrue(diskPersistence.getBytesUsed() > 4096); // example: 30720
    }
    finally {
        CloseableRequestResources.closeQuietly(results);
        collection.clear();
        offHeapPersistence.close();
        diskPersistence.getFile().delete();
    }
}
 
Example 19
Source File: ExistsIn.java    From cqengine with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the given foreign collection contains objects which match the given query.
 * @param foreignCollection The foreign collection to check
 * @param query The query to check
 * @return True if the foreign collection contains one or more objects which match the query, otherwise false
 */
static <F> boolean foreignCollectionContains(IndexedCollection<F> foreignCollection, Query<F> query) {
    ResultSet<F> resultSet = foreignCollection.retrieve(query);
    try {
        return resultSet.isNotEmpty();
    }
    finally {
        resultSet.close();
    }
}
 
Example 20
Source File: SqlExistsBasedJoin.java    From cqengine with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    // Create an indexed collection of cars...
    IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>();
    cars.add(new Car(1, "Ford Focus", "great condition, low mileage", asList("spare tyre", "sunroof")));
    cars.add(new Car(2, "Ford Taurus", "dirty and unreliable, flat tyre", asList("spare tyre", "radio")));
    cars.add(new Car(3, "Honda Civic", "has a flat tyre and high mileage", asList("radio")));
    cars.add(new Car(4, "BMW M3", "2013 model", asList("radio", "convertible")));

    // Create an indexed collection of garages...
    final IndexedCollection<Garage> garages = new ConcurrentIndexedCollection<Garage>();
    garages.add(new Garage(1, "Joe's garage", "London", asList("Ford Focus", "Honda Civic")));
    garages.add(new Garage(2, "Jane's garage", "Dublin", asList("BMW M3")));
    garages.add(new Garage(3, "John's garage", "Dublin", asList("Ford Focus", "Ford Taurus")));
    garages.add(new Garage(4, "Jill's garage", "Dublin", asList("Ford Focus")));

    // Query: Cars which are convertible or which have a sunroof, which can be serviced in Dublin...
    Query<Car> carsQuery = and(
            in(Car.FEATURES, "sunroof", "convertible"),
            existsIn(garages,
                    Car.NAME,
                    Garage.BRANDS_SERVICED,
                    equal(Garage.LOCATION, "Dublin")
            )
    );

    for (Car car : cars.retrieve(carsQuery)) {
        Query<Garage> garagesWhichServiceThisCarInDublin
                = and(equal(Garage.BRANDS_SERVICED, car.name), equal(Garage.LOCATION, "Dublin"));
        boolean first = true;
        for (Garage garage : garages.retrieve(garagesWhichServiceThisCarInDublin)) {
            if (first) {
                // Print this only when we have actually retrieved the first garage, in case the
                // collection was modified removing the first garage before the inner loop :)...
                System.out.println(car.name + " has a sunroof or is convertible, " +
                        "and can be serviced in Dublin at the following garages:- " );
                first = false;
            }
            System.out.println("---> " + garage);
        }
        System.out.println();
    }
    /* ..prints:

        BMW M3 has a sunroof or is convertible, and can be serviced in Dublin at the following garages:-
        ---> Garage{garageId=2, name='Jane's garage', location='Dublin', brandsServiced=[BMW M3]}

        Ford Focus has a sunroof or is convertible, and can be serviced in Dublin at the following garages:-
        ---> Garage{garageId=3, name='John's garage', location='Dublin', brandsServiced=[Ford Focus, Ford Taurus]}
        ---> Garage{garageId=4, name='Jill's garage', location='Dublin', brandsServiced=[Ford Focus]}
     */
}