Skip to content

Commit

Permalink
IGNITE-190 Changed query examples.
Browse files Browse the repository at this point in the history
  • Loading branch information
niktikhonov committed Feb 6, 2015
1 parent 97a9adc commit 3ae3ed1
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 149 deletions.
2 changes: 1 addition & 1 deletion examples/config/example-cache.xml
Expand Up @@ -141,7 +141,7 @@


<!-- Allow to index primitive values. --> <!-- Allow to index primitive values. -->
<property name="queryConfiguration"> <property name="queryConfiguration">
<bean class="org.apache.ignite.cache.query.QueryConfiguration"> <bean class="org.apache.ignite.configuration.CacheQueryConfiguration">
<!-- Index primitives. --> <!-- Index primitives. -->
<property name="indexPrimitiveKey" value="true"/> <property name="indexPrimitiveKey" value="true"/>
</bean> </bean>
Expand Down
Expand Up @@ -18,12 +18,11 @@
package org.apache.ignite.examples.datagrid; package org.apache.ignite.examples.datagrid;


import org.apache.ignite.*; import org.apache.ignite.*;
import org.apache.ignite.cache.*;
import org.apache.ignite.cache.affinity.*; import org.apache.ignite.cache.affinity.*;
import org.apache.ignite.cache.query.*;
import org.apache.ignite.cache.query.annotations.*; import org.apache.ignite.cache.query.annotations.*;
import org.apache.ignite.internal.processors.cache.query.*;
import org.apache.ignite.lang.*;


import javax.cache.*;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;


Expand Down Expand Up @@ -81,7 +80,7 @@ public static void main(String[] args) throws Exception {
System.out.println(">>> Cache query example started."); System.out.println(">>> Cache query example started.");


// Clean up caches on all nodes before run. // Clean up caches on all nodes before run.
ignite.jcache(CACHE_NAME).clear(); ignite.jcache(CACHE_NAME).removeAll();


// Populate cache. // Populate cache.
initialize(); initialize();
Expand All @@ -95,13 +94,8 @@ public static void main(String[] args) throws Exception {
// Example for TEXT-based querying for a given string in peoples resumes. // Example for TEXT-based querying for a given string in peoples resumes.
textQuery(); textQuery();


// Example for SQL-based querying with custom remote and local reducers // Example for SQL-based querying to calculate average salary among all employees within a company.
// to calculate average salary among all employees within a company. sqlQueryWithAggregation();
sqlQueryWithReducers();

// Example for SQL-based querying with custom remote transformer to make sure
// that only required data without any overhead is returned to caller.
sqlQueryWithTransformer();


// Example for SQL-based fields queries that return only required // Example for SQL-based fields queries that return only required
// fields instead of whole key-value pairs. // fields instead of whole key-value pairs.
Expand All @@ -120,18 +114,20 @@ public static void main(String[] args) throws Exception {
* @throws IgniteCheckedException In case of error. * @throws IgniteCheckedException In case of error.
*/ */
private static void sqlQuery() throws IgniteCheckedException { private static void sqlQuery() throws IgniteCheckedException {
GridCache<CacheAffinityKey<UUID>, Person> cache = Ignition.ignite().cache(CACHE_NAME); IgniteCache<CacheAffinityKey<UUID>, Person> cache = Ignition.ignite().jcache(CACHE_NAME);


// Create query which selects salaries based on range. // SQL clause which selects salaries based on range.
CacheQuery<Map.Entry<CacheAffinityKey<UUID>, Person>> qry = String sql = "salary > ? and salary <= ?";
cache.queries().createSqlQuery(Person.class, "salary > ? and salary <= ?");


// Execute queries for salary ranges. // Execute queries for salary ranges.
print("People with salaries between 0 and 1000: ", qry.execute(0, 1000).get()); print("People with salaries between 0 and 1000: ",
cache.query(new QuerySqlPredicate(Person.class, sql, 0, 1000)).getAll());


print("People with salaries between 1000 and 2000: ", qry.execute(1000, 2000).get()); print("People with salaries between 1000 and 2000: ",
cache.query(new QuerySqlPredicate(Person.class, sql, 1000, 2000)).getAll());


print("People with salaries greater than 2000: ", qry.execute(2000, Integer.MAX_VALUE).get()); print("People with salaries greater than 2000: ",
cache.query(new QuerySqlPredicate(Person.class, sql, 2000, Integer.MAX_VALUE)).getAll());
} }


/** /**
Expand All @@ -140,17 +136,19 @@ private static void sqlQuery() throws IgniteCheckedException {
* @throws IgniteCheckedException In case of error. * @throws IgniteCheckedException In case of error.
*/ */
private static void sqlQueryWithJoin() throws IgniteCheckedException { private static void sqlQueryWithJoin() throws IgniteCheckedException {
GridCache<CacheAffinityKey<UUID>, Person> cache = Ignition.ignite().cache(CACHE_NAME); IgniteCache<CacheAffinityKey<UUID>, Person> cache = Ignition.ignite().jcache(CACHE_NAME);


// Create query which joins on 2 types to select people for a specific organization. // SQL clause query which joins on 2 types to select people for a specific organization.
CacheQuery<Map.Entry<CacheAffinityKey<UUID>, Person>> qry = String joinSql =
cache.queries().createSqlQuery(Person.class, "from Person, Organization " + "from Person, Organization "
"where Person.orgId = Organization.id " + + "where Person.orgId = Organization.id "
"and lower(Organization.name) = lower(?)"); + "and lower(Organization.name) = lower(?)";


// Execute queries for find employees for different organizations. // Execute queries for find employees for different organizations.
print("Following people are 'Ignite' employees: ", qry.execute("Ignite").get()); print("Following people are 'Ignite' employees: ",
print("Following people are 'Other' employees: ", qry.execute("Other").get()); cache.query(new QuerySqlPredicate(Person.class, joinSql, "Ignite")).getAll());
print("Following people are 'Other' employees: ",
cache.query(new QuerySqlPredicate(Person.class, joinSql, "Other")).getAll());
} }


/** /**
Expand All @@ -159,96 +157,35 @@ private static void sqlQueryWithJoin() throws IgniteCheckedException {
* @throws IgniteCheckedException In case of error. * @throws IgniteCheckedException In case of error.
*/ */
private static void textQuery() throws IgniteCheckedException { private static void textQuery() throws IgniteCheckedException {
GridCache<CacheAffinityKey<UUID>, Person> cache = Ignition.ignite().cache(CACHE_NAME); IgniteCache<CacheAffinityKey<UUID>, Person> cache = Ignition.ignite().jcache(CACHE_NAME);


// Query for all people with "Master Degree" in their resumes. // Query for all people with "Master Degree" in their resumes.
CacheQuery<Map.Entry<CacheAffinityKey<UUID>, Person>> masters = QueryCursor<Cache.Entry<CacheAffinityKey<UUID>, Person>> masters =
cache.queries().createFullTextQuery(Person.class, "Master"); cache.query(new QueryTextPredicate(Person.class, "Master"));


// Query for all people with "Bachelor Degree"in their resumes. // Query for all people with "Bachelor Degree" in their resumes.
CacheQuery<Map.Entry<CacheAffinityKey<UUID>, Person>> bachelors = QueryCursor<Cache.Entry<CacheAffinityKey<UUID>, Person>> bachelors =
cache.queries().createFullTextQuery(Person.class, "Bachelor"); cache.query(new QueryTextPredicate(Person.class, "Bachelor"));


print("Following people have 'Master Degree' in their resumes: ", masters.execute().get()); print("Following people have 'Master Degree' in their resumes: ", masters.getAll());
print("Following people have 'Bachelor Degree' in their resumes: ", bachelors.execute().get()); print("Following people have 'Bachelor Degree' in their resumes: ", bachelors.getAll());
} }


/** /**
* Example for SQL queries with custom remote and local reducers to calculate * Example for SQL queries to calculate average salary for a specific organization.
* average salary for a specific organization.
* *
* @throws IgniteCheckedException In case of error. * @throws IgniteCheckedException In case of error.
*/ */
private static void sqlQueryWithReducers() throws IgniteCheckedException { private static void sqlQueryWithAggregation() throws IgniteCheckedException {
CacheProjection<CacheAffinityKey<UUID>, Person> cache = Ignition.ignite().cache(CACHE_NAME); IgniteCache<CacheAffinityKey<UUID>, Person> cache = Ignition.ignite().jcache(CACHE_NAME);


// Calculate average of salary of all persons in Ignite. // Calculate average of salary of all persons in Ignite.
CacheQuery<Map.Entry<CacheAffinityKey<UUID>, Person>> qry = cache.queries().createSqlQuery( QueryCursor<List<?>> qry = cache.queryFields(new QuerySqlPredicate(
Person.class, "select avg(salary) from Person, Organization where Person.orgId = Organization.id and "
"from Person, Organization where Person.orgId = Organization.id and " + + "lower(Organization.name) = lower(?)", "Ignite"));
"lower(Organization.name) = lower(?)");

Collection<IgniteBiTuple<Double, Integer>> res = qry.execute(
new IgniteReducer<Map.Entry<CacheAffinityKey<UUID>, Person>, IgniteBiTuple<Double, Integer>>() {
private double sum;

private int cnt;

@Override public boolean collect(Map.Entry<CacheAffinityKey<UUID>, Person> e) {
sum += e.getValue().salary;

cnt++;

// Continue collecting.
return true;
}

@Override public IgniteBiTuple<Double, Integer> reduce() {
return new IgniteBiTuple<>(sum, cnt);
}
}, "Ignite").get();

double sum = 0.0d;
int cnt = 0;

for (IgniteBiTuple<Double, Integer> t : res) {
sum += t.get1();
cnt += t.get2();
}

double avg = sum / cnt;


// Calculate average salary for a specific organization. // Calculate average salary for a specific organization.
print("Average salary for 'Ignite' employees: " + avg); print("Average salary for 'Ignite' employees: " + qry.getAll());
}

/**
* Example for SQL queries with custom transformer to allow passing
* only the required set of fields back to caller.
*
* @throws IgniteCheckedException In case of error.
*/
private static void sqlQueryWithTransformer() throws IgniteCheckedException {
GridCache<CacheAffinityKey<UUID>, Person> cache = Ignition.ignite().cache(CACHE_NAME);

// Create query to get names of all employees working for some company.
CacheQuery<Map.Entry<CacheAffinityKey<UUID>, Person>> qry =
cache.queries().createSqlQuery(Person.class,
"from Person, Organization " +
"where Person.orgId = Organization.id and lower(Organization.name) = lower(?)");

// Transformer to convert Person objects to String.
// Since caller only needs employee names, we only
// send names back.
IgniteClosure<Map.Entry<CacheAffinityKey<UUID>, Person>, String> trans =
new IgniteClosure<Map.Entry<CacheAffinityKey<UUID>, Person>, String>() {
@Override public String apply(Map.Entry<CacheAffinityKey<UUID>, Person> e) {
return e.getValue().lastName;
}
};

// Query all nodes for names of all Ignite employees.
print("Names of all 'Ignite' employees: " + qry.execute(trans, "Ignite").get());
} }


/** /**
Expand All @@ -258,15 +195,15 @@ private static void sqlQueryWithTransformer() throws IgniteCheckedException {
* @throws IgniteCheckedException In case of error. * @throws IgniteCheckedException In case of error.
*/ */
private static void sqlFieldsQuery() throws IgniteCheckedException { private static void sqlFieldsQuery() throws IgniteCheckedException {
GridCache<?, ?> cache = Ignition.ignite().cache(CACHE_NAME); IgniteCache<?, ?> cache = Ignition.ignite().jcache(CACHE_NAME);


// Create query to get names of all employees. // Create query to get names of all employees.
CacheQuery<List<?>> qry1 = cache.queries().createSqlFieldsQuery( QueryCursor<List<?>> qry = cache.queryFields(
"select concat(firstName, ' ', lastName) from Person"); new QuerySqlPredicate("select concat(firstName, ' ', lastName) from Person"));


// Execute query to get collection of rows. In this particular // Execute query to get collection of rows. In this particular
// case each row will have one element with full name of an employees. // case each row will have one element with full name of an employees.
Collection<List<?>> res = qry1.execute().get(); Collection<List<?>> res = qry.getAll();


// Print names. // Print names.
print("Names of all employees:", res); print("Names of all employees:", res);
Expand All @@ -279,16 +216,16 @@ private static void sqlFieldsQuery() throws IgniteCheckedException {
* @throws IgniteCheckedException In case of error. * @throws IgniteCheckedException In case of error.
*/ */
private static void sqlFieldsQueryWithJoin() throws IgniteCheckedException { private static void sqlFieldsQueryWithJoin() throws IgniteCheckedException {
GridCache<?, ?> cache = Ignition.ignite().cache(CACHE_NAME); IgniteCache<?, ?> cache = Ignition.ignite().jcache(CACHE_NAME);


// Create query to get names of all employees. // Create query to get names of all employees.
CacheQuery<List<?>> qry1 = cache.queries().createSqlFieldsQuery( QueryCursor<List<?>> qry = cache.queryFields(new QuerySqlPredicate("select concat(firstName, ' ', lastName), "
"select concat(firstName, ' ', lastName), Organization.name from Person, Organization where " + + "Organization.name from Person, Organization where "
"Person.orgId = Organization.id"); + "Person.orgId = Organization.id"));


// Execute query to get collection of rows. In this particular // Execute query to get collection of rows. In this particular
// case each row will have one element with full name of an employees. // case each row will have one element with full name of an employees.
Collection<List<?>> res = qry1.execute().get(); Collection<List<?>> res = qry.getAll();


// Print persons' names and organizations' names. // Print persons' names and organizations' names.
print("Names of all employees and organizations they belong to:", res); print("Names of all employees and organizations they belong to:", res);
Expand All @@ -301,14 +238,7 @@ private static void sqlFieldsQueryWithJoin() throws IgniteCheckedException {
* @throws InterruptedException In case of error. * @throws InterruptedException In case of error.
*/ */
private static void initialize() throws IgniteCheckedException, InterruptedException { private static void initialize() throws IgniteCheckedException, InterruptedException {
GridCache<?, ?> cache = Ignition.ignite().cache(CACHE_NAME); IgniteCache cache = Ignition.ignite().jcache(CACHE_NAME);

// Organization projection.
CacheProjection<UUID, Organization> orgCache = cache.projection(UUID.class, Organization.class);

// Person projection.
CacheProjection<CacheAffinityKey<UUID>, Person> personCache =
cache.projection(CacheAffinityKey.class, Person.class);


// Organizations. // Organizations.
Organization org1 = new Organization("Ignite"); Organization org1 = new Organization("Ignite");
Expand All @@ -320,15 +250,15 @@ private static void initialize() throws IgniteCheckedException, InterruptedExcep
Person p3 = new Person(org2, "John", "Smith", 1000, "John Smith has Bachelor Degree."); Person p3 = new Person(org2, "John", "Smith", 1000, "John Smith has Bachelor Degree.");
Person p4 = new Person(org2, "Jane", "Smith", 2000, "Jane Smith has Master Degree."); Person p4 = new Person(org2, "Jane", "Smith", 2000, "Jane Smith has Master Degree.");


orgCache.put(org1.id, org1); cache.put(org1.id, org1);
orgCache.put(org2.id, org2); cache.put(org2.id, org2);


// Note that in this example we use custom affinity key for Person objects // Note that in this example we use custom affinity key for Person objects
// to ensure that all persons are collocated with their organizations. // to ensure that all persons are collocated with their organizations.
personCache.put(p1.key(), p1); cache.put(p1.key(), p1);
personCache.put(p2.key(), p2); cache.put(p2.key(), p2);
personCache.put(p3.key(), p3); cache.put(p3.key(), p3);
personCache.put(p4.key(), p4); cache.put(p4.key(), p4);


// Wait 1 second to be sure that all nodes processed put requests. // Wait 1 second to be sure that all nodes processed put requests.
Thread.sleep(1000); Thread.sleep(1000);
Expand Down
Expand Up @@ -19,9 +19,10 @@


import org.apache.ignite.*; import org.apache.ignite.*;
import org.apache.ignite.cache.*; import org.apache.ignite.cache.*;
import org.apache.ignite.cache.query.*;
import org.apache.ignite.examples.datagrid.*; import org.apache.ignite.examples.datagrid.*;
import org.apache.ignite.internal.processors.cache.query.*;


import javax.cache.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;


Expand Down Expand Up @@ -148,19 +149,19 @@ private static void populateFacts() throws IgniteException {
* @throws IgniteException If failed. * @throws IgniteException If failed.
*/ */
private static void queryStorePurchases() throws IgniteCheckedException { private static void queryStorePurchases() throws IgniteCheckedException {
GridCache<Integer, FactPurchase> factCache = Ignition.ignite().cache(PARTITIONED_CACHE_NAME); IgniteCache<Integer, FactPurchase> factCache = Ignition.ignite().jcache(PARTITIONED_CACHE_NAME);


// All purchases for store1. // All purchases for store1.
// ======================== // ========================


// Create cross cache query to get all purchases made at store1. // Create cross cache query to get all purchases made at store1.
CacheQuery<Map.Entry<Integer, FactPurchase>> storePurchases = factCache.queries().createSqlQuery( QueryCursor<Cache.Entry<Integer, FactPurchase>> storePurchases = factCache.query(new QuerySqlPredicate(
FactPurchase.class, FactPurchase.class,
"from \"replicated\".DimStore, \"partitioned\".FactPurchase " + "from \"replicated\".DimStore, \"partitioned\".FactPurchase "
"where DimStore.id=FactPurchase.storeId and DimStore.name=?"); + "where DimStore.id=FactPurchase.storeId and DimStore.name=?",
"Store1"));


printQueryResults("All purchases made at store1:", printQueryResults("All purchases made at store1:", storePurchases.getAll());
storePurchases.execute("Store1").get());
} }


/** /**
Expand All @@ -172,30 +173,26 @@ private static void queryStorePurchases() throws IgniteCheckedException {
* @throws IgniteException If failed. * @throws IgniteException If failed.
*/ */
private static void queryProductPurchases() throws IgniteCheckedException { private static void queryProductPurchases() throws IgniteCheckedException {
GridCache<Integer, Object> dimCache = Ignition.ignite().cache(REPLICATED_CACHE_NAME); IgniteCache<Integer, FactPurchase> factCache = Ignition.ignite().jcache(PARTITIONED_CACHE_NAME);
GridCache<Integer, FactPurchase> factCache = Ignition.ignite().cache(PARTITIONED_CACHE_NAME);

CacheProjection<Integer, DimProduct> prods = dimCache.projection(Integer.class, DimProduct.class);


// All purchases for certain product made at store2. // All purchases for certain product made at store2.
// ================================================= // =================================================


DimProduct p1 = rand(prods.values()); DimProduct p1 = rand(dataProduct.values());
DimProduct p2 = rand(prods.values()); DimProduct p2 = rand(dataProduct.values());
DimProduct p3 = rand(prods.values()); DimProduct p3 = rand(dataProduct.values());


System.out.println("IDs of products [p1=" + p1.getId() + ", p2=" + p2.getId() + ", p3=" + p3.getId() + ']'); System.out.println("IDs of products [p1=" + p1.getId() + ", p2=" + p2.getId() + ", p3=" + p3.getId() + ']');


// Create cross cache query to get all purchases made at store2 // Create cross cache query to get all purchases made at store2
// for specified products. // for specified products.
CacheQuery<Map.Entry<Integer, FactPurchase>> prodPurchases = factCache.queries().createSqlQuery( QueryCursor<Cache.Entry<Integer, FactPurchase>> prodPurchases = factCache.query(new QuerySqlPredicate(
FactPurchase.class, FactPurchase.class,
"from \"replicated\".DimStore, \"replicated\".DimProduct, \"partitioned\".FactPurchase " + "from \"replicated\".DimStore, \"replicated\".DimProduct, \"partitioned\".FactPurchase "
"where DimStore.id=FactPurchase.storeId and DimProduct.id=FactPurchase.productId " + + "where DimStore.id=FactPurchase.storeId and DimProduct.id=FactPurchase.productId "
"and DimStore.name=? and DimProduct.id in(?, ?, ?)"); + "and DimStore.name=? and DimProduct.id in(?, ?, ?)", "Store2", p1.getId(), p2.getId(), p3.getId()));


printQueryResults("All purchases made at store2 for 3 specific products:", printQueryResults("All purchases made at store2 for 3 specific products:", prodPurchases.getAll());
prodPurchases.execute("Store2", p1.getId(), p2.getId(), p3.getId()).get());
} }


/** /**
Expand All @@ -204,10 +201,10 @@ private static void queryProductPurchases() throws IgniteCheckedException {
* @param msg Initial message. * @param msg Initial message.
* @param res Results to print. * @param res Results to print.
*/ */
private static <V> void printQueryResults(String msg, Iterable<Map.Entry<Integer, V>> res) { private static <V> void printQueryResults(String msg, Iterable<Cache.Entry<Integer, V>> res) {
System.out.println(msg); System.out.println(msg);


for (Map.Entry<?, ?> e : res) for (Cache.Entry<?, ?> e : res)
System.out.println(" " + e.getValue().toString()); System.out.println(" " + e.getValue().toString());
} }


Expand Down

0 comments on commit 3ae3ed1

Please sign in to comment.