org.apache.geode.cache.query.QueryService Java Examples

The following examples show how to use org.apache.geode.cache.query.QueryService. 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: Example.java    From geode-examples with Apache License 2.0 6 votes vote down vote up
public static void doQueries(ClientCache cache) throws NameResolutionException,
    TypeMismatchException, QueryInvocationTargetException, FunctionDomainException {
  QueryService queryService = cache.getQueryService();

  // Query for every entry in the region, and print query results.
  System.out.println("\nExecuting query: " + QUERY1);
  SelectResults<EmployeeData> results =
      (SelectResults<EmployeeData>) queryService.newQuery(QUERY1).execute();
  printSetOfEmployees(results);

  // Query for all part time employees, and print query results.
  System.out.println("\nExecuting query: " + QUERY2);
  results = (SelectResults<EmployeeData>) queryService.newQuery(QUERY2).execute();
  printSetOfEmployees(results);

  // Query for last name of Jive, and print the full name and employee number.
  System.out.println("\nExecuting query: " + QUERY3);
  results =
      (SelectResults<EmployeeData>) queryService.newQuery(QUERY3).execute(new String[] {"Jive"});
  for (EmployeeData eachEmployee : results) {
    System.out.println(String.format("Employee %s %s has employee number %d",
        eachEmployee.getFirstName(), eachEmployee.getLastName(), eachEmployee.getEmplNumber()));
  }
}
 
Example #2
Source File: Example.java    From geode-examples with Apache License 2.0 6 votes vote down vote up
public static void doQueries(ClientCache cache) throws NameResolutionException,
    TypeMismatchException, QueryInvocationTargetException, FunctionDomainException {
  QueryService queryService = cache.getQueryService();

  // Query for every entry in the region, and print query results.
  System.out.println("\nExecuting query: " + QUERY1);
  SelectResults<EmployeeData> results =
      (SelectResults<EmployeeData>) queryService.newQuery(QUERY1).execute();
  printSetOfEmployees(results);

  // Query for all part time employees, and print query results.
  System.out.println("\nExecuting query: " + QUERY2);
  results = (SelectResults<EmployeeData>) queryService.newQuery(QUERY2).execute();
  printSetOfEmployees(results);

  // Query for last name of Jive, and print the full name and employee number.
  System.out.println("\nExecuting query: " + QUERY3);
  results =
      (SelectResults<EmployeeData>) queryService.newQuery(QUERY3).execute(new String[] {"Jive"});
  for (EmployeeData eachEmployee : results) {
    System.out.println(String.format("Employee %s %s has employee number %d",
        eachEmployee.getFirstName(), eachEmployee.getLastName(), eachEmployee.getEmplNumber()));
  }
}
 
Example #3
Source File: BookMasterRegionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

    ClientCache clientCache = new ClientCacheFactory()
        .addPoolLocator("localhost", 10334)
        .setPdxSerializer(new ReflectionBasedAutoSerializer("org.apache.calcite.adapter.geode.*"))
        .create();

    // Using Key/Value
    Region bookMaster = clientCache
        .createClientRegionFactory(ClientRegionShortcut.PROXY)
        .create("BookMaster");

    System.out.println("BookMaster = " + bookMaster.get(789));

    // Using OQL
    QueryService queryService = clientCache.getQueryService();
    String oql = "select itemNumber, description, retailCost from /BookMaster";
    SelectResults result = (SelectResults) queryService.newQuery(oql).execute();
    System.out.println(result.asList());
  }
 
Example #4
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  // connect to the locator using default port 10334
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  Example example = new Example();

  // create a local region that matches the server region
  ClientRegionFactory<String, Passenger> clientRegionFactory =
      cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
  Region<String, Passenger> region = clientRegionFactory.create("example-region");
  QueryService queryService = cache.getQueryService();

  RegionPopulator populator = new RegionPopulator();
  populator.populateRegion(region);

  System.out.println("Total number of passengers: "
      + example.countResults(queryService, NON_INDEXED_QUERY, new Object[] {}));
  for (String lastName : populator.lastNames) {
    System.out.println("Flights for " + lastName + ": " + example.countResults(queryService,
        TOP_LEVEL_INDEX_QUERY, new Object[] {"%" + lastName}));
  }
  for (String airline : populator.airlines) {
    System.out.println("Flights for " + airline + ": "
        + example.countResults(queryService, NESTED_INDEX_QUERY, new Object[] {airline}));
  }

  cache.close();
}
 
Example #5
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
int countResults(QueryService queryService, String queryString, Object[] params) {
  try {
    int count = 0;
    SelectResults<Passenger> results =
        (SelectResults<Passenger>) queryService.newQuery(queryString).execute(params);
    for (Passenger passenger : results) {
      ++count;
    }
    return count;
  } catch (FunctionDomainException | TypeMismatchException | NameResolutionException
      | QueryInvocationTargetException e) {
    e.printStackTrace();
    return -1;
  }
}
 
Example #6
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  // connect to the locator using default port 10334
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  Example example = new Example();

  // create a local region that matches the server region
  ClientRegionFactory<String, Passenger> clientRegionFactory =
      cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
  Region<String, Passenger> region = clientRegionFactory.create("example-region");
  QueryService queryService = cache.getQueryService();

  RegionPopulator populator = new RegionPopulator();
  populator.populateRegion(region);

  System.out.println("Total number of passengers: "
      + example.countResults(queryService, NON_INDEXED_QUERY, new Object[] {}));
  for (String lastName : populator.lastNames) {
    System.out.println("Flights for " + lastName + ": " + example.countResults(queryService,
        TOP_LEVEL_INDEX_QUERY, new Object[] {"%" + lastName}));
  }
  for (String airline : populator.airlines) {
    System.out.println("Flights for " + airline + ": "
        + example.countResults(queryService, NESTED_INDEX_QUERY, new Object[] {airline}));
  }

  cache.close();
}
 
Example #7
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
int countResults(QueryService queryService, String queryString, Object[] params) {
  try {
    int count = 0;
    SelectResults<Passenger> results =
        (SelectResults<Passenger>) queryService.newQuery(queryString).execute(params);
    for (Passenger passenger : results) {
      ++count;
    }
    return count;
  } catch (FunctionDomainException | TypeMismatchException | NameResolutionException
      | QueryInvocationTargetException e) {
    e.printStackTrace();
    return -1;
  }
}
 
Example #8
Source File: GeodeSimpleEnumerator.java    From calcite with Apache License 2.0 5 votes vote down vote up
public GeodeSimpleEnumerator(ClientCache clientCache, String regionName) {
  this.clientCache = clientCache;
  QueryService queryService = clientCache.getQueryService();
  String oql = "select * from /" + regionName.trim();
  try {
    results = ((SelectResults) queryService.newQuery(oql).execute()).iterator();
  } catch (Exception e) {
    e.printStackTrace();
    results = null;
  }
}
 
Example #9
Source File: GeodeZipsTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testWhereWithOrForLargeValueList() throws Exception {
  Cache cache = POLICY.cache();
  QueryService queryService = cache.getQueryService();
  Query query = queryService.newQuery("select state as state from /zips");
  SelectResults results = (SelectResults) query.execute();

  Set<String> stateList = (Set<String>) results.stream().map(s -> {
    StructImpl struct = (StructImpl) s;
    return struct.get("state");
  })
      .collect(Collectors.toCollection(LinkedHashSet::new));

  String stateListPredicate = stateList.stream()
      .map(s -> String.format(Locale.ROOT, "state = '%s'", s))
      .collect(Collectors.joining(" OR "));

  String stateListStr = "'" + String.join("', '", stateList) + "'";

  String queryToBeExecuted = "SELECT state as state FROM view WHERE " + stateListPredicate;

  String expectedQuery = "SELECT state AS state FROM /zips WHERE state "
      + "IN SET(" + stateListStr + ")";

  calciteAssert()
      .query(queryToBeExecuted)
      .returnsCount(149)
      .queryContains(
          GeodeAssertions.query(expectedQuery));
}
 
Example #10
Source File: DefaultQueryServiceResolver.java    From immutables with Apache License 2.0 5 votes vote down vote up
private static QueryService resolveClientQueryService(Region<?, ?> region) {
  Preconditions.checkArgument(region.getRegionService() instanceof ClientCache, "Expected to get %s got %s for region %s", ClientCache.class, region.getRegionService(), region.getFullPath());
  ClientCache clientCache = (ClientCache) region.getRegionService();

  return requiresLocalQueryService(region) ? clientCache.getLocalQueryService()
          : (requiresPooledQueryService(region) ? clientCache.getQueryService(poolNameFrom(region))
          : queryServiceFrom(region));
}
 
Example #11
Source File: GeodeContinuousQueriesHealthIndicator.java    From spring-boot-data-geode with Apache License 2.0 4 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) {

	if (getContinuousQueryListenerContainer().isPresent()) {

		Optional<QueryService> queryService = getContinuousQueryListenerContainer()
			.map(ContinuousQueryListenerContainer::getQueryService);

		List<CqQuery> continuousQueries = queryService
			.map(QueryService::getCqs)
			.map(Arrays::asList)
			.orElseGet(Collections::emptyList);

		builder.withDetail("geode.continuous-query.count", continuousQueries.size());

		queryService
			.map(QueryService::getCqStatistics)
			.ifPresent(cqServiceStatistics ->

				builder.withDetail("geode.continuous-query.number-of-active", cqServiceStatistics.numCqsActive())
					.withDetail("geode.continuous-query.number-of-closed", cqServiceStatistics.numCqsClosed())
					.withDetail("geode.continuous-query.number-of-created", cqServiceStatistics.numCqsCreated())
					.withDetail("geode.continuous-query.number-of-stopped", cqServiceStatistics.numCqsStopped())
					.withDetail("geode.continuous-query.number-on-client", cqServiceStatistics.numCqsOnClient())
			);

		continuousQueries.stream()
			.filter(Objects::nonNull)
			.forEach(continuousQuery -> {

				String continuousQueryName = continuousQuery.getName();

				builder.withDetail(continuousQueryKey(continuousQueryName,"oql-query-string"), continuousQuery.getQueryString())
					.withDetail(continuousQueryKey(continuousQueryName, "closed"), toYesNoString(continuousQuery.isClosed()))
					.withDetail(continuousQueryKey(continuousQueryName, "closing"), toYesNoString(continuousQuery.getState()))
					.withDetail(continuousQueryKey(continuousQueryName, "durable"), toYesNoString(continuousQuery.isDurable()))
					.withDetail(continuousQueryKey(continuousQueryName, "running"), toYesNoString(continuousQuery.isRunning()))
					.withDetail(continuousQueryKey(continuousQueryName, "stopped"), toYesNoString(continuousQuery.isStopped()));

				Query query = continuousQuery.getQuery();

				if (query != null) {

					QueryStatistics queryStatistics = query.getStatistics();

					if (queryStatistics != null) {
						builder.withDetail(continuousQueryQueryKey(continuousQueryName, "number-of-executions"), queryStatistics.getNumExecutions())
							.withDetail(continuousQueryQueryKey(continuousQueryName, "total-execution-time"), queryStatistics.getTotalExecutionTime());
					}
				}

				CqStatistics continuousQueryStatistics = continuousQuery.getStatistics();

				if (continuousQueryStatistics != null) {

					builder.withDetail(continuousQueryStatisticsKey(continuousQueryName, "number-of-deletes"), continuousQueryStatistics.numDeletes())
						.withDetail(continuousQueryStatisticsKey(continuousQueryName, "number-of-events"), continuousQueryStatistics.numEvents())
						.withDetail(continuousQueryStatisticsKey(continuousQueryName, "number-of-inserts"), continuousQueryStatistics.numInserts())
						.withDetail(continuousQueryStatisticsKey(continuousQueryName, "number-of-updates"), continuousQueryStatistics.numUpdates());
				}
			});

		builder.up();

		return;
	}

	builder.unknown();
}
 
Example #12
Source File: GeodeOqlInterpreter.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
QueryService getQueryService() {
  return this.queryService;
}
 
Example #13
Source File: GeodeOqlInterpreterTest.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
private void testOql(Iterator<Object> queryResponseIterator, String expectedOutput, int maxResult)
    throws Exception {

  GeodeOqlInterpreter spyGeodeOqlInterpreter = spy(new GeodeOqlInterpreter(new Properties()));

  QueryService mockQueryService = mock(QueryService.class, RETURNS_DEEP_STUBS);

  when(spyGeodeOqlInterpreter.getQueryService()).thenReturn(mockQueryService);
  when(spyGeodeOqlInterpreter.getMaxResult()).thenReturn(maxResult);

  @SuppressWarnings("unchecked")
  SelectResults<Object> mockResults = mock(SelectResults.class);

  when(mockQueryService.newQuery(eq(OQL_QUERY)).execute()).thenReturn(mockResults);

  when(mockResults.iterator()).thenReturn(queryResponseIterator);

  InterpreterResult interpreterResult = spyGeodeOqlInterpreter.interpret(OQL_QUERY, null);

  assertEquals(Code.SUCCESS, interpreterResult.code());
  assertEquals(expectedOutput, interpreterResult.message().get(0).getData());
}
 
Example #14
Source File: DefaultQueryServiceResolver.java    From immutables with Apache License 2.0 4 votes vote down vote up
private static QueryService queryServiceFrom(Region<?, ?> region) {
  return region.getRegionService().getQueryService();
}
 
Example #15
Source File: DefaultQueryServiceResolver.java    From immutables with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the {@link QueryService} used by this template in its query/finder methods.
 *
 * @param region {@link Region} used to acquire the {@link QueryService}.
 * @return the {@link QueryService} that will perform the query.
 * @see Region
 * @see Region#getRegionService()
 * @see org.apache.geode.cache.RegionService#getQueryService()
 * @see org.apache.geode.cache.client.ClientCache#getLocalQueryService()
 */
@Override
public QueryService resolve(Region<?, ?> region) {
  Objects.requireNonNull(region, "region");
  return region.getRegionService() instanceof ClientCache
          ? resolveClientQueryService(region)
          : queryServiceFrom(region);
}
 
Example #16
Source File: QueryServiceResolver.java    From immutables with Apache License 2.0 2 votes vote down vote up
/**
 * Find {@linkplain QueryService} for a region.
 */
QueryService resolve(Region<?, ?> region);