Search in sources :

Example 41 with QueryCursor

use of org.apache.ignite.cache.query.QueryCursor in project ignite by apache.

the class TcpDiscoveryMultiThreadedTest method _testCustomEventOnJoinCoordinatorStop.

/**
 * @throws Exception If failed.
 */
public void _testCustomEventOnJoinCoordinatorStop() throws Exception {
    for (int k = 0; k < 10; k++) {
        log.info("Iteration: " + k);
        clientFlagGlobal = false;
        final int START_NODES = 5;
        final int JOIN_NODES = 5;
        startGrids(START_NODES);
        final AtomicInteger startIdx = new AtomicInteger(START_NODES);
        final AtomicBoolean stop = new AtomicBoolean();
        IgniteInternalFuture<?> fut1 = GridTestUtils.runAsync(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
                Ignite ignite = ignite(START_NODES - 1);
                while (!stop.get()) {
                    ignite.createCache(ccfg);
                    ignite.destroyCache(ccfg.getName());
                }
                return null;
            }
        });
        try {
            final CyclicBarrier barrier = new CyclicBarrier(JOIN_NODES + 1);
            IgniteInternalFuture<?> fut2 = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    int idx = startIdx.getAndIncrement();
                    Thread.currentThread().setName("start-thread-" + idx);
                    barrier.await();
                    Ignite ignite = startGrid(idx);
                    assertFalse(ignite.configuration().isClientMode());
                    log.info("Started node: " + ignite.name());
                    IgniteCache<Object, Object> cache = ignite.getOrCreateCache(DEFAULT_CACHE_NAME);
                    ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
                    qry.setLocalListener(new CacheEntryUpdatedListener<Object, Object>() {

                        @Override
                        public void onUpdated(Iterable<CacheEntryEvent<?, ?>> evts) {
                        // No-op.
                        }
                    });
                    QueryCursor<Cache.Entry<Object, Object>> cur = cache.query(qry);
                    cur.close();
                    return null;
                }
            }, JOIN_NODES, "start-thread");
            barrier.await();
            U.sleep(ThreadLocalRandom.current().nextInt(10, 100));
            for (int i = 0; i < START_NODES - 1; i++) {
                GridTestUtils.invoke(ignite(i).configuration().getDiscoverySpi(), "simulateNodeFailure");
                stopGrid(i);
            }
            stop.set(true);
            fut1.get();
            fut2.get();
        } finally {
            stop.set(true);
            fut1.get();
        }
        stopAllGrids();
    }
}
Also used : IgniteCache(org.apache.ignite.IgniteCache) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheEntryUpdatedListener(javax.cache.event.CacheEntryUpdatedListener) Ignite(org.apache.ignite.Ignite) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) QueryCursor(org.apache.ignite.cache.query.QueryCursor) Cache(javax.cache.Cache) IgniteCache(org.apache.ignite.IgniteCache)

Example 42 with QueryCursor

use of org.apache.ignite.cache.query.QueryCursor in project ignite by apache.

the class CacheContinuousQueryWithTransformerExample method main.

/**
 * Executes example.
 *
 * @param args Command line arguments, none required.
 * @throws Exception If example execution failed.
 */
public static void main(String[] args) throws Exception {
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println();
        System.out.println(">>> Cache continuous query with transformer example started.");
        // Auto-close cache at the end of the example.
        try (IgniteCache<Integer, Organization> cache = ignite.getOrCreateCache(CACHE_NAME).withKeepBinary()) {
            // Create new continuous query with transformer.
            ContinuousQueryWithTransformer<Integer, Organization, String> qry = new ContinuousQueryWithTransformer<>();
            // Factory to create transformers.
            qry.setRemoteTransformerFactory(() -> {
                // Only this field will be sent over to a local node over the network.
                return event -> ((BinaryObject) event.getValue()).field("name");
            });
            // Listener that will receive transformed data.
            qry.setLocalListener(names -> {
                for (String name : names) System.out.println("New organization name: " + name);
            });
            // Execute query.
            try (QueryCursor<Cache.Entry<Integer, Organization>> cur = cache.query(qry)) {
                populateCache(cache);
                // Wait for a while while callback is notified about remaining puts.
                Thread.sleep(2000);
            }
        } finally {
            // Distributed cache could be removed from cluster only by #destroyCache() call.
            ignite.destroyCache(CACHE_NAME);
        }
    }
}
Also used : BinaryObject(org.apache.ignite.binary.BinaryObject) Timestamp(java.sql.Timestamp) HashMap(java.util.HashMap) Ignite(org.apache.ignite.Ignite) ExampleNodeStartup(org.apache.ignite.examples.ExampleNodeStartup) Address(org.apache.ignite.examples.model.Address) IgniteCache(org.apache.ignite.IgniteCache) OrganizationType(org.apache.ignite.examples.model.OrganizationType) Ignition(org.apache.ignite.Ignition) Organization(org.apache.ignite.examples.model.Organization) Map(java.util.Map) QueryCursor(org.apache.ignite.cache.query.QueryCursor) Cache(javax.cache.Cache) ContinuousQueryWithTransformer(org.apache.ignite.cache.query.ContinuousQueryWithTransformer) ContinuousQueryWithTransformer(org.apache.ignite.cache.query.ContinuousQueryWithTransformer) Organization(org.apache.ignite.examples.model.Organization) BinaryObject(org.apache.ignite.binary.BinaryObject) Ignite(org.apache.ignite.Ignite)

Example 43 with QueryCursor

use of org.apache.ignite.cache.query.QueryCursor in project ignite by apache.

the class UsingContinuousQueries method initialQueryExample.

public static void initialQueryExample() {
    try (Ignite ignite = Ignition.start()) {
        // tag::initialQry[]
        IgniteCache<Integer, String> cache = ignite.getOrCreateCache("myCache");
        // end::initialQry[]
        cache.put(100, "100");
        // tag::initialQry[]
        ContinuousQuery<Integer, String> query = new ContinuousQuery<>();
        // Setting an optional initial query.
        // The query will return entries for the keys greater than 10.
        query.setInitialQuery(new ScanQuery<>((k, v) -> k > 10));
        // mandatory local listener
        query.setLocalListener(events -> {
        });
        try (QueryCursor<Cache.Entry<Integer, String>> cursor = cache.query(query)) {
            // Iterating over the entries returned by the initial query
            for (Cache.Entry<Integer, String> e : cursor) System.out.println("key=" + e.getKey() + ", val=" + e.getValue());
        }
    // end::initialQry[]
    }
}
Also used : Factory(javax.cache.configuration.Factory) FactoryBuilder(javax.cache.configuration.FactoryBuilder) Ignite(org.apache.ignite.Ignite) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) IgniteCache(org.apache.ignite.IgniteCache) CacheEntryEvent(javax.cache.event.CacheEntryEvent) CacheEntryEventFilter(javax.cache.event.CacheEntryEventFilter) Ignition(org.apache.ignite.Ignition) IgniteClosure(org.apache.ignite.lang.IgniteClosure) CacheEntryListenerException(javax.cache.event.CacheEntryListenerException) QueryCursor(org.apache.ignite.cache.query.QueryCursor) Cache(javax.cache.Cache) ContinuousQueryWithTransformer(org.apache.ignite.cache.query.ContinuousQueryWithTransformer) CacheEntryUpdatedListener(javax.cache.event.CacheEntryUpdatedListener) ScanQuery(org.apache.ignite.cache.query.ScanQuery) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) Ignite(org.apache.ignite.Ignite) IgniteCache(org.apache.ignite.IgniteCache) Cache(javax.cache.Cache)

Example 44 with QueryCursor

use of org.apache.ignite.cache.query.QueryCursor in project ignite by apache.

the class UsingScanQueries method executingScanQueriesExample.

@Test
void executingScanQueriesExample() {
    try (Ignite ignite = Ignition.start()) {
        // tag::scanQry[]
        // tag::predicate[]
        // tag::transformer[]
        IgniteCache<Integer, Person> cache = ignite.getOrCreateCache("myCache");
        // end::scanQry[]
        // end::predicate[]
        // end::transformer[]
        Person person = new Person(1, "Vasya Ivanov");
        person.setSalary(2000);
        cache.put(1, person);
        // tag::scanQry[]
        QueryCursor<Cache.Entry<Integer, Person>> cursor = cache.query(new ScanQuery<>());
        // end::scanQry[]
        System.out.println("Scan query output:" + cursor.getAll().get(0).getValue().getName());
        // tag::predicate[]
        // Find the persons who earn more than 1,000.
        IgniteBiPredicate<Integer, Person> filter = (key, p) -> p.getSalary() > 1000;
        try (QueryCursor<Cache.Entry<Integer, Person>> qryCursor = cache.query(new ScanQuery<>(filter))) {
            qryCursor.forEach(entry -> System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()));
        }
        // end::predicate[]
        // tag::transformer[]
        // Get only keys for persons earning more than 1,000.
        List<Integer> keys = cache.query(new ScanQuery<>(// Remote filter
        (IgniteBiPredicate<Integer, Person>) (k, p) -> p.getSalary() > 1000), // Transformer
        (IgniteClosure<Cache.Entry<Integer, Person>, Integer>) Cache.Entry::getKey).getAll();
        // end::transformer[]
        System.out.println("Transformer example output:" + keys.get(0));
    }
}
Also used : QueryIndexType(org.apache.ignite.cache.QueryIndexType) Arrays(java.util.Arrays) IndexQueryCriteriaBuilder.gt(org.apache.ignite.cache.query.IndexQueryCriteriaBuilder.gt) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) IndexQueryCriteriaBuilder.eq(org.apache.ignite.cache.query.IndexQueryCriteriaBuilder.eq) Ignite(org.apache.ignite.Ignite) IndexQuery(org.apache.ignite.cache.query.IndexQuery) IgniteCache(org.apache.ignite.IgniteCache) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.jupiter.api.Test) List(java.util.List) Ignition(org.apache.ignite.Ignition) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) IgniteClosure(org.apache.ignite.lang.IgniteClosure) QueryCursor(org.apache.ignite.cache.query.QueryCursor) Cache(javax.cache.Cache) QueryEntity(org.apache.ignite.cache.QueryEntity) Collections(java.util.Collections) QueryIndex(org.apache.ignite.cache.QueryIndex) ScanQuery(org.apache.ignite.cache.query.ScanQuery) IgniteClosure(org.apache.ignite.lang.IgniteClosure) ScanQuery(org.apache.ignite.cache.query.ScanQuery) Ignite(org.apache.ignite.Ignite) IgniteCache(org.apache.ignite.IgniteCache) Cache(javax.cache.Cache) Test(org.junit.jupiter.api.Test)

Example 45 with QueryCursor

use of org.apache.ignite.cache.query.QueryCursor in project ignite by apache.

the class UsingScanQueries method executingIndexQueriesExample.

@Test
void executingIndexQueriesExample() {
    try (Ignite ignite = Ignition.start()) {
        // tag::idxQry[]
        // Create index by 2 fields (orgId, salary).
        QueryEntity personEntity = new QueryEntity(Integer.class, Person.class).setFields(new LinkedHashMap<String, String>() {

            {
                put("orgId", Integer.class.getName());
                put("salary", Integer.class.getName());
            }
        }).setIndexes(Collections.singletonList(new QueryIndex(Arrays.asList("orgId", "salary"), QueryIndexType.SORTED).setName("ORG_SALARY_IDX")));
        CacheConfiguration<Integer, Person> ccfg = new CacheConfiguration<Integer, Person>("entityCache").setQueryEntities(Collections.singletonList(personEntity));
        IgniteCache<Integer, Person> cache = ignite.getOrCreateCache(ccfg);
        // end::idxQry[]
        {
            // tag::idxQry[]
            // Find the persons who work in Organization 1.
            QueryCursor<Cache.Entry<Integer, Person>> cursor = cache.query(new IndexQuery<Integer, Person>(Person.class, "ORG_SALARY_IDX").setCriteria(eq("orgId", 1)));
        // end::idxQry[]
        }
        {
            // tag::idxQryMultipleCriteria[]
            // Find the persons who work in Organization 1 and have salary more than 1,000.
            QueryCursor<Cache.Entry<Integer, Person>> cursor = cache.query(new IndexQuery<Integer, Person>(Person.class, "ORG_SALARY_IDX").setCriteria(eq("orgId", 1), gt("salary", 1000)));
        // end::idxQryMultipleCriteria[]
        }
        {
            // tag::idxQryNoIdxName[]
            // Ignite finds suitable index "ORG_SALARY_IDX" by specified criterion field "orgId".
            QueryCursor<Cache.Entry<Integer, Person>> cursor = cache.query(new IndexQuery<Integer, Person>(Person.class).setCriteria(eq("orgId", 1)));
        // end::idxQryNoIdxName[]
        }
        {
            // tag::idxQryFilter[]
            // Find the persons who work in Organization 1 and whose name contains 'Vasya'.
            QueryCursor<Cache.Entry<Integer, Person>> cursor = cache.query(new IndexQuery<Integer, Person>(Person.class).setCriteria(eq("orgId", 1)).setFilter((k, v) -> v.getName().contains("Vasya")));
        // end::idxQryFilter[]
        }
    }
}
Also used : IndexQuery(org.apache.ignite.cache.query.IndexQuery) QueryIndex(org.apache.ignite.cache.QueryIndex) Ignite(org.apache.ignite.Ignite) QueryEntity(org.apache.ignite.cache.QueryEntity) QueryCursor(org.apache.ignite.cache.query.QueryCursor) LinkedHashMap(java.util.LinkedHashMap) IgniteCache(org.apache.ignite.IgniteCache) Cache(javax.cache.Cache) Test(org.junit.jupiter.api.Test)

Aggregations

QueryCursor (org.apache.ignite.cache.query.QueryCursor)72 IgniteCache (org.apache.ignite.IgniteCache)44 Ignite (org.apache.ignite.Ignite)38 ContinuousQuery (org.apache.ignite.cache.query.ContinuousQuery)36 Cache (javax.cache.Cache)33 Test (org.junit.Test)29 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)28 ScanQuery (org.apache.ignite.cache.query.ScanQuery)26 ArrayList (java.util.ArrayList)24 IgniteException (org.apache.ignite.IgniteException)22 List (java.util.List)19 SqlFieldsQuery (org.apache.ignite.cache.query.SqlFieldsQuery)19 Map (java.util.Map)17 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)17 CacheConfiguration (org.apache.ignite.configuration.CacheConfiguration)17 CacheException (javax.cache.CacheException)16 GridTestUtils (org.apache.ignite.testframework.GridTestUtils)16 Collection (java.util.Collection)15 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)15 Transaction (org.apache.ignite.transactions.Transaction)15