[关闭]
@liyuj 2018-01-27T07:49:27.000000Z 字数 13210 阅读 6899

Apache-Ignite-2.3.0-中文开发手册

7.Java开发向导

7.1.SQL API

Java开发者可以使用特定的SQL API来查询和修改存储于数据库中的数据。

7.1.1.SqlQuery

SqlQuery适用于查询执行完毕后需要获得返回的结果集中整个对象的场景,下面的代码片段显示了在实践中如何实现:

  1. IgniteCache<Long, Person> cache = ignite.cache("personCache");
  2. SqlQuery sql = new SqlQuery(Person.class, "salary > ?");
  3. // Find all persons earning more than 1,000.
  4. try (QueryCursor<Entry<Long, Person>> cursor = cache.query(sql.setArgs(1000))) {
  5. for (Entry<Long, Person> e : cursor)
  6. System.out.println(e.getValue().toString());
  7. }

7.1.2.SqlFieldsQuery

不需要查询整个对象,只需要指定几个特定的字段即可,这样可以最小化网络和序列化的开销。为此,Ignite实现了一个字段查询的概念。SqlFieldsQuery接受一个标准SQL查询作为它的构造器参数,然后像下面的示例那样立即执行:

  1. IgniteCache<Long, Person> cache = ignite.cache("personCache");
  2. // Execute query to get names of all employees.
  3. SqlFieldsQuery sql = new SqlFieldsQuery(
  4. "select concat(firstName, ' ', lastName) from Person");
  5. // Iterate over the result set.
  6. try (QueryCursor<List<?>> cursor = cache.query(sql) {
  7. for (List<?> row : cursor)
  8. System.out.println("personName=" + row.get(0));
  9. }

可查询字段定义
SqlQuerySqlFieldsQuery中的指定字段可以被访问之前,他们需要为SQL模式的一部分,使用标准的DDL命令,或者特定的Java注解,或者QueryEntity配置,都可以进行字段的定义。

通过SqlFieldsQuery,还可以使用DML命令进行数据的修改:
INSERT

  1. IgniteCache<Long, Person> cache = ignite.cache("personCache");
  2. cache.query(new SqlFieldsQuery(
  3. "INSERT INTO Person(id, firstName, lastName) VALUES(?, ?, ?)").
  4. setArgs(1L, "John", "Smith"));

UPDATE

  1. IgniteCache<Long, Person> cache = ignite.cache("personCache");
  2. cache.query(new SqlFieldsQuery("UPDATE Person set lastName = ? " +
  3. "WHERE id >= ?").setArgs("Jones", 2L));

DELETE

  1. IgniteCache<Long, Person> cache = ignite.cache("personCache");
  2. cache.query(new SqlFieldsQuery("DELETE FROM Person " +
  3. "WHERE id >= ?").setArgs(2L));

MERGE

  1. IgniteCache<Long, Person> cache = ignite.cache("personCache");
  2. cache.query(new SqlFieldsQuery("MERGE INTO Person(id, firstName, lastName)" +
  3. " values (1, 'John', 'Smith'), (5, 'Mary', 'Jones')"));

7.1.3.示例

Ignite的发布版包括了一个可运行的CacheQueryDmlExample.java,它是源代码的一部分,演示了上述提到的所有DML操作的使用。

7.2.模式和索引

7.2.1.摘要

不管是通过注解或者通过QueryEntity的方式,表和索引建立之后,它们所属的模式名为CacheConfiguration对象中配置的缓存名,要修改的话,需要使用CacheConfiguration.setSqlSchema方法。
但是,如果表和索引是通过DDL语句的形式定义的,那么模式名就会完全不同,这时,表和索引所属的模式名默认为PUBLIC
这时,不管使用上述的哪种方式配置的表,那么一定要确保查询时要指定正确的模式名。比如,假定80%的表都是通过DDL配置的,那么通过SqlQuery.setSchema("PUBLIC")方法将查询的默认模式配置成PUBLIC就会很有意义:
Java:

  1. IgniteCache cache = ignite.cache("Person");
  2. // Creating City table.
  3. cache.qry(new SqlFieldsQuery("CREATE TABLE City " +
  4. "(id int primary key, name varchar, region varchar)"));
  5. // Creating Organization table.
  6. cache.qry(new SqlFieldsQuery("CREATE TABLE Organization " +
  7. "(id int primary key, name varchar, cityName varchar)"));
  8. // Joining data between City, Organizaion and Person tables. The latter
  9. // was created with either annotations or QueryEntity approach.
  10. SqlFieldsQuery qry = new SqlFieldsQuery("SELECT o.name from Organization o " +
  11. "inner join \"Person\".Person p on o.id = p.orgId " +
  12. "inner join City c on c.name = o.cityName " +
  13. "where p.age > 25 and c.region <> 'Texas'");
  14. // Setting the query's default schema to PUBLIC.
  15. // Table names from the query without the schema set will be
  16. // resolved against PUBLIC schema.
  17. // Person table belongs to "Person" schema (person cache) and this is why
  18. // that schema name is set explicitly.
  19. qry.setSchema("PUBLIC");
  20. // Executing the query.
  21. cache.query(qry);

7.2.2.基于注解的配置

索引,和可查询的字段一样,是可以通过编程的方式用@QuerySqlField进行配置的。如下所示,期望的字段已经加注了该注解。
Java

  1. public class Person implements Serializable {
  2. /** Indexed field. Will be visible for SQL engine. */
  3. @QuerySqlField (index = true)
  4. private long id;
  5. /** Queryable field. Will be visible for SQL engine. */
  6. @QuerySqlField
  7. private String name;
  8. /** Will NOT be visible for SQL engine. */
  9. private int age;
  10. /**
  11. * Indexed field sorted in descending order.
  12. * Will be visible for SQL engine.
  13. */
  14. @QuerySqlField(index = true, descending = true)
  15. private float salary;
  16. }

Scala:

  1. case class Person (
  2. /** Indexed field. Will be visible for SQL engine. */
  3. @(QuerySqlField @field)(index = true) id: Long,
  4. /** Queryable field. Will be visible for SQL engine. */
  5. @(QuerySqlField @field) name: String,
  6. /** Will NOT be visisble for SQL engine. */
  7. age: Int
  8. /**
  9. * Indexed field sorted in descending order.
  10. * Will be visible for SQL engine.
  11. */
  12. @(QuerySqlField @field)(index = true, descending = true) salary: Float
  13. ) extends Serializable {
  14. ...
  15. }

在SQL查询中,类型名会被用作表名,这时,表名为Person(模式名的定义和使用前面已经描述)。
idsalary都是索引列,id字段升序排列(默认),而salary降序排列。
如果不希望索引一个字段,但是仍然想在SQL查询中使用它,那么在加注解时可以忽略index = true参数,这样的字段称为可查询字段,举例来说,上面的name就被定义为可查询字段。
最后,age既不是可查询字段也不是索引字段,在Ignite中,从SQL查询的角度看就是不可见的。
下面,就可以向下面这样执行SQL查询了:

  1. SqlFieldsQuery qry = new SqlFieldsQuery("SELECT id, name FROM Person" +
  2. "WHERE id > 1500 LIMIT 10");

运行时更新索引和可查询字段
如果需要在运行时管理索引或者使新的字段对SQL引擎可见,可以使用ALTER TABLE, CREATE/DROP INDEX命令。
索引嵌套对象
使用注解,嵌套对象的字段也可以被索引以及查询,比如,假设Person对象有一个Address对象属性:

  1. public class Person {
  2. /** Indexed field. Will be visible for SQL engine. */
  3. @QuerySqlField(index = true)
  4. private long id;
  5. /** Queryable field. Will be visible for SQL engine. */
  6. @QuerySqlField
  7. private String name;
  8. /** Will NOT be visible for SQL engine. */
  9. private int age;
  10. /** Indexed field. Will be visible for SQL engine. */
  11. @QuerySqlField(index = true)
  12. private Address address;
  13. }

Address类的结构如下:

  1. public class Address {
  2. /** Indexed field. Will be visible for SQL engine. */
  3. @QuerySqlField (index = true)
  4. private String street;
  5. /** Indexed field. Will be visible for SQL engine. */
  6. @QuerySqlField(index = true)
  7. private int zip;
  8. }

上例中,@QuerySqlField(index = true)注解加在了Address类的所有属性上,就像Person类的Address对象一样。
这样就可以执行下面这样的查询:

  1. QueryCursor<List<?>> cursor = personCache.query(new SqlFieldsQuery(
  2. "select * from Person where street = 'street1'"));

注意在查询的where子句中不需要指定address.street,这是因为Address类的字段会被合并到Person表中,这样会简化对Address中的字段的访问。

Scala注解
在Scala类中,@QuerySqlField注解必须和@Field注解一起使用,这样的话这个字段对于Ignite才是可见的,就像这样的:@(QuerySqlField @field)
也可以使用ignite-scalar模块的@ScalarCacheQuerySqlField注解作为替代,他不过是@Field注解的别名。

注册索引类型
定义了索引字段和可查询字段之后,就需要和他们所属的对象类型一起,在SQL引擎中注册。
要告诉Ignite哪些类型应该被索引,需要通过CacheConfiguration.setIndexedTypes方法传入键-值对,如下所示:

  1. // Preparing configuration.
  2. CacheConfiguration<Long, Person> ccfg = new CacheConfiguration<>();
  3. // Registering indexed type.
  4. ccfg.setIndexedTypes(Long.class, Person.class);

注意,这个方法只接收成对的类型,一个键类一个值类,基本类型需要使用包装器类。

预定义字段
除了用@QuerySqlField注解标注的所有字段,每个表都有两个特别的预定义字段:_key_val,它表示到整个键对象和值对象的链接。这很有用,比如当他们中的一个是基本类型并且希望用它的值进行过滤时。要做到这一点,执行一个SELECT * FROM Person WHERE _key = 100查询即可。

多亏了二进制编组器,不需要将索引类型类加入集群节点的类路径中,SQL查询引擎不需要对象反序列化就可以钻取索引和可查询字段的值。

分组索引
当查询条件复杂时可以使用多字段索引来加快查询的速度,这时可以用@QuerySqlField.Group注解。如果希望一个字段参与多个分组索引时也可以将多个@QuerySqlField.Group注解加入orderedGroups中。
比如,下面的Person类中age字段加入了名为age_salary_idx的分组索引,他的分组序号是0并且降序排列,同一个分组索引中还有一个字段salary,他的分组序号是3并且升序排列。最重要的是salary字段还是一个单列索引(除了orderedGroups声明之外,还加上了index = true)。分组中的order不需要是什么特别的数值,他只是用于分组内的字段排序。
Java:

  1. public class Person implements Serializable {
  2. /** Indexed in a group index with "salary". */
  3. @QuerySqlField(orderedGroups={@QuerySqlField.Group(
  4. name = "age_salary_idx", order = 0, descending = true)})
  5. private int age;
  6. /** Indexed separately and in a group index with "age". */
  7. @QuerySqlField(index = true, orderedGroups={@QuerySqlField.Group(
  8. name = "age_salary_idx", order = 3)})
  9. private double salary;
  10. }

注意,将@QuerySqlField.Group放在@QuerySqlField(orderedGroups={...})外面是无效的。

7.2.3.基于QueryEntity的配置

索引和字段也可以通过org.apache.ignite.cache.QueryEntity进行配置,它便于利用Spring进行基于XML的配置。
在上面基于注解的配置涉及的所有概念,对于基于QueryEntity的方式也都有效,深入地说,通过@QuerySqlField配置的字段的类型然后通过CacheConfiguration.setIndexedTypes注册过的,在内部也会被转换为查询实体。
下面的示例显示的是如何像可查询字段那样定义一个单一字段和分组索引。

  1. <bean class="org.apache.ignite.configuration.CacheConfiguration">
  2. <property name="name" value="mycache"/>
  3. <!-- Configure query entities -->
  4. <property name="queryEntities">
  5. <list>
  6. <bean class="org.apache.ignite.cache.QueryEntity">
  7. <!-- Setting indexed type's key class -->
  8. <property name="keyType" value="java.lang.Long"/>
  9. <!-- Setting indexed type's value class -->
  10. <property name="valueType"
  11. value="org.apache.ignite.examples.Person"/>
  12. <!-- Defining fields that will be either indexed or queryable.
  13. Indexed fields are added to 'indexes' list below.-->
  14. <property name="fields">
  15. <map>
  16. <entry key="id" value="java.lang.Long"/>
  17. <entry key="name" value="java.lang.String"/>
  18. <entry key="salary" value="java.lang.Long "/>
  19. </map>
  20. </property>
  21. <!-- Defining indexed fields.-->
  22. <property name="indexes">
  23. <list>
  24. <!-- Single field (aka. column) index -->
  25. <bean class="org.apache.ignite.cache.QueryIndex">
  26. <constructor-arg value="id"/>
  27. </bean>
  28. <!-- Group index. -->
  29. <bean class="org.apache.ignite.cache.QueryIndex">
  30. <constructor-arg>
  31. <list>
  32. <value>id</value>
  33. <value>salary</value>
  34. </list>
  35. </constructor-arg>
  36. <constructor-arg value="SORTED"/>
  37. </bean>
  38. </list>
  39. </property>
  40. </bean>
  41. </list>
  42. </property>
  43. </bean>

SQL查询中会使用valueType的简称作为表名,这时,表名为Person
QueryEntity定义之后,就可以执行下面的查询了:

  1. SqlFieldsQuery qry = new SqlFieldsQuery("SELECT id, name FROM Person" +
  2. "WHERE id > 1500 LIMIT 10");

7.2.4.自定义键

如果只使用预定义的SQL数据类型作为缓存键,那么就没必要对和DML相关的配置做额外的操作,这些数据类型在GridQueryProcessor#SQL_TYPES常量中进行定义,列举如下:

预定义SQL数据类型
1.所有的基本类型及其包装器,除了charCharacter
2.String;
3.BigDecimal;
4.byte[];
5.java.util.Date, java.sql.Date, java.sql.Timestamp;
6.java.util.UUID

然而,如果决定引入复杂的自定义缓存键,那么在DML语句中要指向这些字段就需要:

下面的例子展示了如何实现:
Java:

  1. // Preparing cache configuration.
  2. CacheConfiguration cacheCfg = new CacheConfiguration<>("personCache");
  3. // Creating the query entity.
  4. QueryEntity entity = new QueryEntity("CustomKey", "Person");
  5. // Listing all the queryable fields.
  6. LinkedHashMap<String, String> flds = new LinkedHashMap<>();
  7. flds.put("intKeyField", Integer.class.getName());
  8. flds.put("strKeyField", String.class.getName());
  9. flds.put("firstName", String.class.getName());
  10. flds.put("lastName", String.class.getName());
  11. entity.setFields(flds);
  12. // Listing a subset of the fields that belong to the key.
  13. Set<String> keyFlds = new HashSet<>();
  14. keyFlds.add("intKeyField");
  15. keyFlds.add("strKeyField");
  16. entity.setKeyFields(keyFlds);
  17. // End of new settings, nothing else here is DML related
  18. entity.setIndexes(Collections.<QueryIndex>emptyList());
  19. cacheCfg.setQueryEntities(Collections.singletonList(entity));
  20. ignite.createCache(cacheCfg);

XML:

  1. <bean class="org.apache.ignite.configuration.CacheConfiguration">
  2. <property name="name" value="personCache"/>
  3. <!-- Configure query entities -->
  4. <property name="queryEntities">
  5. <list>
  6. <bean class="org.apache.ignite.cache.QueryEntity">
  7. <!-- Registering key's class. -->
  8. <property name="keyType" value="CustomKey"/>
  9. <!-- Registering value's class. -->
  10. <property name="valueType"
  11. value="org.apache.ignite.examples.Person"/>
  12. <!--
  13. Defining all the fields that will be accessible from DML.
  14. -->
  15. <property name="fields">
  16. <map>
  17. <entry key="firstName" value="java.lang.String"/>
  18. <entry key="lastName" value="java.lang.String"/>
  19. <entry key="intKeyField" value="java.lang.Integer"/>
  20. <entry key="strKeyField" value="java.lang.String"/>
  21. </map>
  22. </property>
  23. <!-- Defining the subset of key's fields -->
  24. <property name="keyFields">
  25. <set>
  26. <value>intKeyField<value/>
  27. <value>strKeyField<value/>
  28. </set>
  29. </property>
  30. </bean>
  31. </list>
  32. </property>
  33. </bean>

哈希值自动计算和equals实现
如果自定义键可以被序列化为二进制形式,那么Ignite会自动进行哈希值的计算并且实现equals方法。
但是,如果是Externalizable类型,那么就无法序列化为二进制形式,那么就需要自行实现hashCodeequals方法。

7.2.5.空间查询

这个空间模块只对com.vividsolutions.jts类型的对象有用。
要配置索引以及/或者几何类型的可查询字段,可以使用和已有的非几何类型同样的方法,首先,可以使用org.apache.ignite.cache.QueryEntity定义索引,他对于基于Spring的XML配置文件非常方便,第二,通过@QuerySqlField注解来声明索引也可以达到同样的效果,他在内部会转化为QueryEntities
QuerySqlField:

  1. /**
  2. * Map point with indexed coordinates.
  3. */
  4. private static class MapPoint {
  5. /** Coordinates. */
  6. @QuerySqlField(index = true)
  7. private Geometry coords;
  8. /**
  9. * @param coords Coordinates.
  10. */
  11. private MapPoint(Geometry coords) {
  12. this.coords = coords;
  13. }
  14. }

QueryEntity:

  1. <bean class="org.apache.ignite.configuration.CacheConfiguration">
  2. <property name="name" value="mycache"/>
  3. <!-- Configure query entities -->
  4. <property name="queryEntities">
  5. <list>
  6. <bean class="org.apache.ignite.cache.QueryEntity">
  7. <property name="keyType" value="java.lang.Integer"/>
  8. <property name="valueType" value="org.apache.ignite.examples.MapPoint"/>
  9. <property name="fields">
  10. <map>
  11. <entry key="coords" value="com.vividsolutions.jts.geom.Geometry"/>
  12. </map>
  13. </property>
  14. <property name="indexes">
  15. <list>
  16. <bean class="org.apache.ignite.cache.QueryIndex">
  17. <constructor-arg value="coords"/>
  18. </bean>
  19. </list>
  20. </property>
  21. </bean>
  22. </list>
  23. </property>
  24. </bean>

使用上述方法定义了几何类型字段之后,就可以使用存储于这些字段中值进行查询了。

  1. // Query to find points that fit into a polygon.
  2. SqlQuery<Integer, MapPoint> query = new SqlQuery<>(MapPoint.class, "coords && ?");
  3. // Defining the polygon's boundaries.
  4. query.setArgs("POLYGON((0 0, 0 99, 400 500, 300 0, 0 0))");
  5. // Executing the query.
  6. Collection<Cache.Entry<Integer, MapPoint>> entries = cache.query(query).getAll();
  7. // Printing number of points that fit into the area defined by the polygon.
  8. System.out.println("Fetched points [" + entries.size() + ']');

完整示例
Ignite中用于演示空间查询的可以立即执行的完整示例,可以在这里找到。

7.3.自定义SQL函数

Ignite的SQL引擎支持通过额外用Java编写的自定义SQL函数,来扩展ANSI-99规范定义的SQL函数集。
一个自定义SQL函数仅仅是一个加注了@QuerySqlFunction注解的公共静态方法。

  1. // Defining a custom SQL function.
  2. public class MyFunctions {
  3. @QuerySqlFunction
  4. public static int sqr(int x) {
  5. return x * x;
  6. }
  7. }

持有自定义SQL函数的类需要使用setSqlFunctionClasses(...)方法在特定的CacheConfiguration中注册。

  1. // Preparing a cache configuration.
  2. CacheConfiguration cfg = new CacheConfiguration();
  3. // Registering the class that contains custom SQL functions.
  4. cfg.setSqlFunctionClasses(MyFunctions.class);

经过了上述配置的缓存部署之后,在SQL查询中就可以随意地调用自定义函数了,如下所示:

  1. // Preparing the query that uses customly defined 'sqr' function.
  2. SqlFieldsQuery query = new SqlFieldsQuery(
  3. "SELECT name FROM Blocks WHERE sqr(size) > 100");
  4. // Executing the query.
  5. cache.query(query).getAll();

在自定义SQL函数可能要执行的所有节点上,通过CacheConfiguration.setSqlFunctionClasses(...)注册的类都需要添加到类路径中,否则在自定义函数执行时会抛出ClassNotFoundException异常。

7.4.查询取消

Ignite中有两种方式停止长时间运行的SQL查询,SQL查询时间长的原因,比如使用了未经优化的索引等。
第一个方法是为特定的SqlQuerySqlFieldsQuery设置查询执行的超时时间。

  1. SqlQuery qry = new SqlQuery<AffinityKey<Long>, Person>(Person.class, joinSql);
  2. // Setting query execution timeout
  3. qry.setTimeout(10_000, TimeUnit.SECONDS);

第二个方法是使用QueryCursor.close()来终止查询。

  1. SqlQuery qry = new SqlQuery<AffinityKey<Long>, Person>(Person.class, joinSql);
  2. // Getting query cursor.
  3. QueryCursor<List> cursor = cache.query(qry);
  4. // Executing query.
  5. ....
  6. // Halting the query that might be still in progress.
  7. cursor.close();
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注