Search in sources :

Example 31 with QueryService

use of org.apache.geode.cache.query.QueryService in project geode by apache.

the class IndexUseMultFrmSnglCondJUnitTest method testMultiFromWithSingleConditionUsingIndex.

@Test
public void testMultiFromWithSingleConditionUsingIndex() throws Exception {
    // create region 1 and 2
    Region region1 = CacheUtils.createRegion("portfolios1", Portfolio.class);
    Region region2 = CacheUtils.createRegion("portfolios2", Portfolio.class);
    for (int i = 0; i < 100; i++) {
        Portfolio p = null;
        if (i != 0 && i < 5) {
            p = new Portfolio(5);
        } else {
            p = new Portfolio(i);
        }
        region1.put(i, p);
        region2.put(i, p);
    }
    QueryService qs = CacheUtils.getQueryService();
    // create and execute query
    String queryString = "SELECT * from /portfolios1 P1, /portfolios2 P2 WHERE P1.ID = 5";
    Query query = qs.newQuery(queryString);
    SelectResults sr1 = (SelectResults) query.execute();
    // create index
    Index index = qs.createIndex("P1IDIndex", IndexType.FUNCTIONAL, "P1.ID", "/portfolios1 P1");
    // execute query
    SelectResults sr2 = (SelectResults) query.execute();
    assertEquals("Index result set does not match unindexed result set size", sr1.size(), sr2.size());
    // size will be number of matching in region 1 x region 2 size
    assertEquals("Query result set size does not match expected size", 5 * region2.size(), sr2.size());
}
Also used : SelectResults(org.apache.geode.cache.query.SelectResults) Query(org.apache.geode.cache.query.Query) QueryService(org.apache.geode.cache.query.QueryService) Portfolio(org.apache.geode.cache.query.data.Portfolio) Region(org.apache.geode.cache.Region) Index(org.apache.geode.cache.query.Index) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 32 with QueryService

use of org.apache.geode.cache.query.QueryService in project geode by apache.

the class LikePredicateJUnitTest method enhancedNotLike.

/**
   * Tests with combination of % and _ and NOT with LIKE Supported from 6.6
   * 
   * @throws Exception
   */
private void enhancedNotLike(boolean useBindPrms, boolean useIndex) throws Exception {
    Cache cache = CacheUtils.getCache();
    AttributesFactory attributesFactory = new AttributesFactory();
    RegionAttributes regionAttributes = attributesFactory.create();
    Region region = cache.createRegion("pos", regionAttributes);
    String[] values = new String[] { "active", "inactive" };
    String[] likePredicates1 = new String[] { "active", "act%%ve", "a%e", "activ_", "ac_ive", "act__e", "a%iv_", "a_tiv%", "ac%" };
    String[] likePredicates2 = new String[] { "%ctiv%", "%c%iv%", "%ctive", "%%ti%", "%" };
    String[] likePredicates3 = new String[] { "___ctive", "___c_iv_", "___ctiv%", "____tive" };
    for (int i = 0; i < values.length; i++) {
        region.put(new Integer(i), values[i]);
    }
    QueryService qs = cache.getQueryService();
    if (useIndex) {
        qs.createIndex("p", IndexType.FUNCTIONAL, "p", "/pos.values p");
    }
    Query q;
    SelectResults results;
    for (int i = 0; i < likePredicates1.length; i++) {
        if (!useBindPrms) {
            q = qs.newQuery("select p from /pos p where NOT (p like '" + likePredicates1[i] + "')");
            results = (SelectResults) q.execute();
        } else {
            q = qs.newQuery("select p from /pos p where NOT (p like $1)");
            results = (SelectResults) q.execute(new Object[] { likePredicates1[i] });
        }
        List r = results.asList();
        if (r.size() != 1 || !r.get(0).equals(values[1])) {
            fail("Unexprected result. expected :" + values[1] + " for the like predicate1: " + likePredicates1[i] + " found : " + (r.size() == 1 ? r.get(0) : "Result size not equal to 1"));
        }
    }
    for (int i = 0; i < likePredicates2.length; i++) {
        if (!useBindPrms) {
            q = qs.newQuery("select p from /pos p where NOT (p like '" + likePredicates2[i] + "')");
            results = (SelectResults) q.execute();
        } else {
            q = qs.newQuery("select p from /pos p where NOT (p like $1)");
            results = (SelectResults) q.execute(new Object[] { likePredicates2[i] });
        }
        List r = results.asList();
        if (r.size() != 0) {
            fail("Unexprected result. expected nothing for the like predicate2: " + likePredicates2[i] + " found : " + (r.size() != 0 ? r.get(0) + " Result size not equal to 0" : ""));
        }
    }
    for (int i = 0; i < likePredicates3.length; i++) {
        if (!useBindPrms) {
            q = qs.newQuery("select p from /pos p where NOT (p like '" + likePredicates3[i] + "')");
            results = (SelectResults) q.execute();
        } else {
            q = qs.newQuery("select p from /pos p where NOT (p like $1)");
            results = (SelectResults) q.execute(new Object[] { likePredicates3[i] });
        }
        List r = results.asList();
        if (r.size() != 1 || !r.get(0).equals(values[0])) {
            fail("Unexprected result. expected :" + values[0] + " for the like predicate3: " + likePredicates3[i] + " found : " + (r.size() == 1 ? r.get(0) : "Result size not equal to 1"));
        }
    }
}
Also used : AttributesFactory(org.apache.geode.cache.AttributesFactory) SelectResults(org.apache.geode.cache.query.SelectResults) Query(org.apache.geode.cache.query.Query) RegionAttributes(org.apache.geode.cache.RegionAttributes) QueryService(org.apache.geode.cache.query.QueryService) Region(org.apache.geode.cache.Region) List(java.util.List) Cache(org.apache.geode.cache.Cache)

Example 33 with QueryService

use of org.apache.geode.cache.query.QueryService in project geode by apache.

the class LikePredicateJUnitTest method likePercentageTerminated_5.

private void likePercentageTerminated_5(boolean useBindPrm) throws Exception {
    Cache cache = CacheUtils.getCache();
    AttributesFactory attributesFactory = new AttributesFactory();
    RegionAttributes regionAttributes = attributesFactory.create();
    Region region = cache.createRegion("pos", regionAttributes);
    char ch = 'd';
    String base = "abc";
    for (int i = 1; i < 6; ++i) {
        Portfolio pf = new Portfolio(i);
        pf.status = base + ch;
        ch += 1;
        region.put(new Integer(i), pf);
    }
    QueryService qs = cache.getQueryService();
    Query q;
    SelectResults results;
    SelectResults expectedResults;
    String predicate = "";
    if (useBindPrm) {
        predicate = "$1";
    } else {
        predicate = " 'a%c%'";
    }
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrm) {
        results = (SelectResults) q.execute(new Object[] { "a%bc%" });
    } else {
        results = (SelectResults) q.execute();
    }
    ResultsBag bag = new ResultsBag(null);
    for (int i = 1; i < 6; ++i) {
        bag.add(region.get(new Integer(i)));
    }
    expectedResults = new ResultsCollectionWrapper(new ObjectTypeImpl(Object.class), bag.asSet());
    SelectResults[][] rs = new SelectResults[][] { { results, expectedResults } };
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
    // Create Index
    qs.createIndex("status", IndexType.FUNCTIONAL, "ps.status", "/pos ps");
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrm) {
        results = (SelectResults) q.execute(new Object[] { "a%bc%" });
    } else {
        results = (SelectResults) q.execute();
    }
    rs = new SelectResults[][] { { results, expectedResults } };
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
    if (useBindPrm) {
        predicate = "$1";
    } else {
        predicate = "'abc_'";
    }
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrm) {
        results = (SelectResults) q.execute(new Object[] { "abc_" });
    } else {
        results = (SelectResults) q.execute();
    }
    rs = new SelectResults[][] { { results, expectedResults } };
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
    if (useBindPrm) {
        predicate = "$1";
    } else {
        predicate = "'_bc_'";
    }
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrm) {
        results = (SelectResults) q.execute(new Object[] { "_bc_" });
    } else {
        results = (SelectResults) q.execute();
    }
    rs = new SelectResults[][] { { results, expectedResults } };
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
}
Also used : Query(org.apache.geode.cache.query.Query) RegionAttributes(org.apache.geode.cache.RegionAttributes) Portfolio(org.apache.geode.cache.query.data.Portfolio) ObjectTypeImpl(org.apache.geode.cache.query.internal.types.ObjectTypeImpl) AttributesFactory(org.apache.geode.cache.AttributesFactory) SelectResults(org.apache.geode.cache.query.SelectResults) QueryService(org.apache.geode.cache.query.QueryService) ResultsCollectionWrapper(org.apache.geode.cache.query.internal.ResultsCollectionWrapper) Region(org.apache.geode.cache.Region) ResultsBag(org.apache.geode.cache.query.internal.ResultsBag) Cache(org.apache.geode.cache.Cache)

Example 34 with QueryService

use of org.apache.geode.cache.query.QueryService in project geode by apache.

the class IndexWithSngleFrmAndMultCondQryJUnitTest method testComparisonBetnWithAndWithoutIndexCreation.

@Test
public void testComparisonBetnWithAndWithoutIndexCreation() throws Exception {
    Region region = CacheUtils.createRegion("pos", Portfolio.class);
    for (int i = 0; i < 4; i++) {
        region.put("" + i, new Portfolio(i));
    }
    QueryService qs;
    qs = CacheUtils.getQueryService();
    String[] queries = { "SELECT DISTINCT * FROM /pos pf,  positions.values pos where pf.status='active' and pos.secId= 'IBM' and ID = 0" };
    SelectResults[][] sr = new SelectResults[queries.length][2];
    for (int i = 0; i < queries.length; i++) {
        Query q = null;
        try {
            q = CacheUtils.getQueryService().newQuery(queries[i]);
            QueryObserverImpl observer = new QueryObserverImpl();
            QueryObserverHolder.setInstance(observer);
            sr[i][0] = (SelectResults) q.execute();
            if (!observer.isIndexesUsed) {
                CacheUtils.log("NO INDEX USED");
            } else {
                fail("How could index be present when not created!?");
            }
            // CacheUtils.log(Utils.printResult(r));
            resType1 = (StructType) ((SelectResults) sr[i][0]).getCollectionType().getElementType();
            resSize1 = (((SelectResults) sr[i][0]).size());
            CacheUtils.log(resType1);
            strg1 = resType1.getFieldNames();
            set1 = (((SelectResults) sr[i][0]).asSet());
            Iterator iter = set1.iterator();
            while (iter.hasNext()) {
                Struct stc1 = (Struct) iter.next();
                valPf1 = stc1.get(strg1[0]);
                valPos1 = stc1.get(strg1[1]);
                isActive1 = ((Portfolio) stc1.get(strg1[0])).isActive();
            }
        } catch (Exception e) {
            e.printStackTrace();
            fail(q.getQueryString());
        }
    }
    // Create an Index on status and execute the same query again.
    qs = CacheUtils.getQueryService();
    Index index1 = qs.createIndex("statusIndex", IndexType.FUNCTIONAL, "pf.status", "/pos pf");
    // Index index2 = (Index)qs.createIndex("secIdIndex", IndexType.FUNCTIONAL,"pos.secId","/pos pf,
    // pf.positions.values pos");
    Index index3 = qs.createIndex("IDIndex", IndexType.FUNCTIONAL, "pf.ID", "/pos pf");
    for (int i = 0; i < queries.length; i++) {
        Query q = null;
        try {
            q = CacheUtils.getQueryService().newQuery(queries[i]);
            QueryObserverImpl observer2 = new QueryObserverImpl();
            QueryObserverHolder.setInstance(observer2);
            sr[i][1] = (SelectResults) q.execute();
            if (!observer2.isIndexesUsed) {
                fail("FAILED: Index NOT Used");
            }
            resType2 = (StructType) ((SelectResults) sr[i][1]).getCollectionType().getElementType();
            resSize2 = (((SelectResults) sr[i][1]).size());
            strg2 = resType2.getFieldNames();
            set2 = (((SelectResults) sr[i][1]).asSet());
            Iterator iter = set2.iterator();
            while (iter.hasNext()) {
                Struct stc2 = (Struct) iter.next();
                valPf2 = stc2.get(strg2[0]);
                valPos2 = stc2.get(strg2[1]);
                isActive2 = ((Portfolio) stc2.get(strg2[0])).isActive();
            }
        } catch (Exception e) {
            e.printStackTrace();
            fail(q.getQueryString());
        }
    }
    if ((resType1).equals(resType2)) {
        CacheUtils.log("Both Search Results are of the same Type i.e.--> " + resType1);
    } else {
        fail("FAILED:Search result Type is different in both the cases");
    }
    if (resSize1 == resSize2 || resSize1 != 0) {
        CacheUtils.log("Search Results size is Non Zero and equal in both cases i.e.  Size= " + resSize1);
    } else {
        fail("FAILED:Search result size is different in both the cases");
    }
    itert2 = set2.iterator();
    itert1 = set1.iterator();
    while (itert1.hasNext()) {
        Struct stc2 = (Struct) itert2.next();
        Struct stc1 = (Struct) itert1.next();
        if (stc2.get(strg2[0]) != stc1.get(strg1[0]))
            fail("FAILED: In both the Cases the first member of StructSet i.e. Portfolio are different. ");
        if (stc2.get(strg2[1]) != stc1.get(strg1[1]))
            fail("FAILED: In both the cases Positions are different");
        if (!StringUtils.equals(((Position) stc2.get(strg2[1])).secId, ((Position) stc1.get(strg1[1])).secId))
            fail("FAILED: In both the cases Positions secIds are different");
        if (((Portfolio) stc2.get(strg2[0])).isActive() != ((Portfolio) stc1.get(strg1[0])).isActive())
            fail("FAILED: Status of the Portfolios found are different");
        if (((Portfolio) stc2.get(strg2[0])).getID() != ((Portfolio) stc1.get(strg1[0])).getID())
            fail("FAILED: IDs of the Portfolios found are different");
    }
    CacheUtils.compareResultsOfWithAndWithoutIndex(sr, this);
}
Also used : Query(org.apache.geode.cache.query.Query) Position(org.apache.geode.cache.query.data.Position) Portfolio(org.apache.geode.cache.query.data.Portfolio) Index(org.apache.geode.cache.query.Index) Struct(org.apache.geode.cache.query.Struct) SelectResults(org.apache.geode.cache.query.SelectResults) QueryService(org.apache.geode.cache.query.QueryService) Iterator(java.util.Iterator) Region(org.apache.geode.cache.Region) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 35 with QueryService

use of org.apache.geode.cache.query.QueryService in project geode by apache.

the class ConcurrentIndexInitOnOverflowRegionDUnitTest method testIndexUpdateWithRegionClear.

/**
   * This tests if index updates are blocked while region.clear() is called and indexes are being
   * reinitialized.
   */
@Test
public void testIndexUpdateWithRegionClear() {
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    final String regionName = "portfolio";
    hooked = false;
    // Create region and an index on it
    vm0.invoke(new CacheSerializableRunnable("Create region and index") {

        @Override
        public void run2() throws CacheException {
            Cache cache = getCache();
            Region region = cache.createRegionFactory(RegionShortcut.LOCAL).create(regionName);
            QueryService qService = cache.getQueryService();
            try {
                qService.createIndex("idIndex", "ID", "/" + regionName);
                qService.createIndex("secIdIndex", "pos.secId", "/" + regionName + " p, p.positions.values pos");
            } catch (Exception e) {
                fail("Index creation failed." + e);
            }
        }
    });
    class LocalTestHook implements TestHook {

        @Override
        public void hook(int spot) throws RuntimeException {
            switch(spot) {
                case // processAction in IndexManager
                6:
                    hooked = true;
                    // wait untill some thread unhooks.
                    while (hooked) {
                        Wait.pause(20);
                    }
                    break;
                default:
                    break;
            }
        }
    }
    // Asynch invocation for continuous index updates
    AsyncInvocation indexUpdateAsysnch = vm0.invokeAsync(new CacheSerializableRunnable("index updates") {

        @Override
        public void run2() throws CacheException {
            Region region = getCache().getRegion(regionName);
            for (int i = 0; i < 100; i++) {
                if (i == 50)
                    IndexManager.testHook = new LocalTestHook();
                region.put(i, new Portfolio(i));
                if (i == 50)
                    Wait.pause(20);
            }
        }
    });
    // Region.clear() which should block other region updates.
    vm0.invoke(new CacheSerializableRunnable("Clear the region") {

        @Override
        public void run2() throws CacheException {
            Region region = getCache().getRegion(regionName);
            while (!hooked) {
                Wait.pause(100);
            }
            if (hooked) {
                hooked = false;
                IndexManager.testHook = null;
                region.clear();
            }
            try {
                QueryService qservice = getCache().getQueryService();
                Index index = qservice.getIndex(region, "idIndex");
                if (((CompactRangeIndex) index).getIndexStorage().size() > 1) {
                    fail("After clear region size is supposed to be zero as all index updates are blocked. Current region size is: " + region.size());
                }
            } finally {
                IndexManager.testHook = null;
            }
        }
    });
    // Kill asynch thread
    ThreadUtils.join(indexUpdateAsysnch, 20000);
    // Verify region size which must be 50
    vm0.invoke(new CacheSerializableRunnable("Check region size") {

        @Override
        public void run2() throws CacheException {
            Region region = getCache().getRegion(regionName);
            if (region.size() > 50) {
                fail("After clear region size is supposed to be 50 as all index updates are blocked " + region.size());
            }
        }
    });
}
Also used : CacheException(org.apache.geode.cache.CacheException) Portfolio(org.apache.geode.cache.query.data.Portfolio) Host(org.apache.geode.test.dunit.Host) Index(org.apache.geode.cache.query.Index) AsyncInvocation(org.apache.geode.test.dunit.AsyncInvocation) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException) IgnoredException(org.apache.geode.test.dunit.IgnoredException) TestHook(org.apache.geode.cache.query.internal.index.IndexManager.TestHook) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) QueryService(org.apache.geode.cache.query.QueryService) VM(org.apache.geode.test.dunit.VM) Region(org.apache.geode.cache.Region) Cache(org.apache.geode.cache.Cache) ClientCache(org.apache.geode.cache.client.ClientCache) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Aggregations

QueryService (org.apache.geode.cache.query.QueryService)532 Test (org.junit.Test)383 SelectResults (org.apache.geode.cache.query.SelectResults)331 Region (org.apache.geode.cache.Region)316 Query (org.apache.geode.cache.query.Query)316 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)215 Portfolio (org.apache.geode.cache.query.data.Portfolio)199 CacheException (org.apache.geode.cache.CacheException)139 CacheSerializableRunnable (org.apache.geode.cache30.CacheSerializableRunnable)118 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)110 Index (org.apache.geode.cache.query.Index)109 Host (org.apache.geode.test.dunit.Host)104 VM (org.apache.geode.test.dunit.VM)104 Iterator (java.util.Iterator)102 Cache (org.apache.geode.cache.Cache)92 DefaultQuery (org.apache.geode.cache.query.internal.DefaultQuery)86 Struct (org.apache.geode.cache.query.Struct)70 RegionNotFoundException (org.apache.geode.cache.query.RegionNotFoundException)68 IOException (java.io.IOException)67 DefaultQueryService (org.apache.geode.cache.query.internal.DefaultQueryService)65