Download presentation
Presentation is loading. Please wait.
1
Oracle Spatial 10g: Advanced
Introduction
2
Oracle Spatial 10g: Advanced 1-2
Overview This seminar introduces you to the advanced concepts of Oracle Spatial 10g. Prior experience with Oracle Spatial 9i or Oracle Spatial 10g: Fundamentals is assumed. Overview This course introduces you to the advanced features of Oracle Spatial 10g, therefore prior Oracle Spatial experience is assumed. This can be run back-to-back with the Oracle Database 10g: Fundamentals course, or as a standalone course for those students with previous Oracle 9i Spatial experience. Oracle Spatial 10g: Advanced 1-2
3
Oracle Spatial 10g: Advanced 1-3
Course Objectives After completing this lesson, you should be able to understand the following advanced Oracle Spatial 10g enhancements: Identify the basic changes between Oracle9i Spatial and Oracle Spatial 10g Export and import transportable tablespaces that include spatial indexes Describe the Oracle Spatial GeoRaster storage model Use MapViewer to publish raster (and vector) data over the web Course Objectives Here you see a list of the objectives covered within this course. This course will take the full two days of tuition for completion of the lessons and the practices. You will gain an appreciation of the advanced features of Oracle Spatial 10g through the completion of the lessons and hands-on practices. Oracle Spatial 10g: Advanced 1-3
4
Oracle Spatial 10g: Advanced 1-4
Course Objectives Describe Oracle Spatial Geocoder in the server and the Geocoding Architecture Identify how to use the Oracle Spatial Geocoding Functions Describe Oracle Spatial Router and the Routing Architecture Discuss Route Requests and Route Responses Describe the Oracle Spatial Topology Data Model Discuss how to create and load a Topology Oracle Spatial 10g: Advanced 1-4
5
Oracle Spatial 10g: Advanced 1-5
Course Objectives Edit a topology and topology caches Describe the Oracle Spatial Network Data Model and Network Concepts Describe the Node, Link, and Path Tables used with the Network Data Model Use the Network Data Model to perform graph analysis Discuss Oracle Spatial Analysis and Mining features Oracle Spatial 10g: Advanced 1-5
6
Oracle Spatial 10g: Advanced 1-6
Course Agenda – Day 1 Lesson Title 1 Introduction 2 Advanced Spatial Indexing 3 Oracle Spatial GeoRaster 4 Oracle Spatial Geocoding 5 Oracle Spatial Routing Engine Oracle Spatial 10g: Advanced 1-6
7
Oracle Spatial 10g: Advanced 1-7
Course Agenda – Day 2 Lesson Title 6 Oracle Spatial Topology Data Model 7 Oracle Spatial Network Data Model 8 Spatial Analysis and Mining App A Oracle Spatial 10g Enhancements App B Workspace Manager (Optional) Oracle Spatial 10g: Advanced 1-7
8
Advanced Spatial Indexing
9
Oracle Spatial 10g: Advanced 1-9
Objectives After completing this lesson, you should be able to do the following: Create partitioned spatial indexes Discuss spatial partitioning of data Export and import transportable tablespaces that include spatial indexes Create function-based indexes Embed and index spatial objects within objects Oracle Spatial 10g: Advanced 1-9
10
Spatial Index Partitioning
Oracle Spatial 10g: Advanced
11
Oracle Table Partitioning and Oracle Spatial
Oracle table partitioning is a key feature of the Oracle database. One logical table: Decomposes to multiple physical tables, called partitions The decomposition is based on the value of a partitioning key: Single Column Multicolumn Oracle Table Partitioning and Oracle Spatial Oracle table partitioning is an Oracle database feature, and is not specific to Oracle Spatial. Using table partitioning you can break a single logical table into smaller physical pieces called partitions, based on a value called a partition key. The value of the partition key determines which of the partitions each row is stored in. Queries are written to use a table, and the Oracle database determines which partitions it needs to search. Oracle Spatial 10g: Advanced
12
Oracle Table Partitioning and Oracle Spatial
A partitioned index is one logical index: Decomposes to one physical index per partition Tables with SDO_GEOMETRY columns can be partitioned: Partitioned spatial indexes are also supported Transparent to applications Oracle Table Partitioning and Oracle Spatial (continued) As of the Oracle9i database, local (or partitioned) spatial indexes on partitioned data are supported. Oracle Spatial 10g: Advanced
13
Benefits of Partitioned Spatial Indexes
Performance: Reduce response times for long-running queries: local index scan Reduce response times for concurrent queries: parallel I/O on each partition’s index Single queries that search multiple index partitions can be parallelized Maintenance: Partition-level index rebuilds Partition-level table and index archives Partition-level table and index exchanges, splits, merges Benefits of Partitioned Spatial Indexes There are several reasons why you may want to partition spatial indexes. Some performance reasons for partitioning spatial indexes include: The time to execute long-running queries can be reduced by examining only the indexes that are associated with necessary partitions. The time to execute queries run in parallel can be reduced because: Examining the index associated with the necessary partition is faster I/O contention can be reduced because separate partitions can be examined concurrently Index partitions can be searched in parallel when more than one index partition is required to satisfy a query. Long-term administration and maintenance of spatial indexes is easier because of the following reasons: The spatial index associated with a single partition can be rebuilt. The spatial index associated with a single partition can be archived or restored. Partition-level table and index exchanges are also supported. Oracle Spatial 10g: Advanced
14
Oracle Spatial Partitioning
Addresses the problem of supporting very large tables and indexes: Decomposes tables and indexes into smaller pieces called partitions SQL statements can access and manipulate the partitions rather than entire tables Table partitions and index partitions can be mapped to different tablespaces Oracle Spatial Partitioning Partitioning helps address many of the problems associated with supporting very large tables and indexes. Tables and indexes are broken up into smaller pieces called partitions. SQL statements can then access and manipulate data on a partition-by-partition basis rather than the entire tables and indexes. Table partitions and index partitions can be mapped to different tablespaces and hardware controllers. Oracle Spatial 10g: Advanced
15
Data Set Description for Partitioned Spatial Index Examples
Oracle Spatial 10g: Advanced
16
Fabricated Yellow Pages Data (Businesses in New York)
( , ) ( , ) ( , ) ( , ) ( , ) All business locations stored in longitude/latitude Businesses on the same latitude are decimal degrees apart Latitudes increase by decimal degrees 360,600 businesses in table Fabricated Yellow Pages Data (Businesses in New York) Some yellow pages data has been fabricated to demonstrate partitioned spatial indexes. All business locations are stored in longitude/latitude (WGS 84). Businesses on the same latitude are decimal degrees apart. Latitudes also increase by decimal degrees. There are a total of 360,600 businesses in this fabricated data set. The longitude/latitude values chosen for the businesses are in the vicinity of New York City. Oracle Spatial 10g: Advanced
17
The YELLOW_PAGES Table
ID Name Category Location 1 2 3 4 5 6 7 25 ITALIAN RESTAURANT 1 CHASE BANK 1 MOBIL GAS 1 PATH MARK GROCERY 1 SHERATON HOTEL 1 FORD AUTOS 1 THAI RESTAURANT 1 ITALIAN RESTAURANT 2 1 2 3 4 5 6 ( , ) ( , ) ( , ) ( , ) ( , ) ( , ) ( , ) ( , ) Six categories are defined that correspond to: 1 for restaurants 2 for banks 3 for gas stations 4 for grocery stores 5 for hotels 6 for auto dealers The Yellow_Pages Table The table has the following four columns: ID: This is a unique ID associated with each business. Category: Each business is assigned to a category. There are six possible values for category (1-6). The value corresponding to the various categories are as follows: 1 for restaurants 2 for banks 3 for gas stations 4 for grocery stores 5 for hotels 6 for auto dealers Name: This is a name associated with each business. In this data set, a name is never repeated. You can see that the businesses with ID=1 and ID=25 are both Italian restaurants, but a unique number is appended to the name to differentiate the two by name. Location: This is an SDO_GEOMETRY column, and contains the longitude/latitude values associated with the business. Oracle Spatial 10g: Advanced
18
Creating a Partitioned Spatial Index
Oracle Spatial 10g: Advanced
19
Spatial Index Partitioning Parameters
Storage parameters for spatial index partitions should be treated in the same way as those for other partitioned indexes. For best performance, storage parameters can (and should) be different for each partition: TABLESPACE for spatial index placement These parameters can help reduce the I/O contention between different spatial index partitions, thus ensuring: Better performance with parallelism Better performance with concurrency Spatial Index Partitioning Parameters Storage parameters are parameters relating to where and how the index data is stored. For optimal performance, storage parameters, and in particular the TABLESPACE parameter should be different for each partition. Specifying a different tablespace for each partition reduces I/O conflicts between partitions, which in turn allows for better performance with parallelism and concurrent workloads. Oracle Spatial 10g: Advanced
20
Spatial Index Partitioning Parameters
Some spatial index parameters must be the same for all partitions SDO_INDX_DIMS Spatial Index Partitioning Parameters (continued) Some spatial index parameters must be the same across all partitions in the spatial index. For example, SDO_INDX_DIMS must be the same for all partitions. Oracle Spatial 10g: Advanced
21
Oracle Spatial Index Partitioning
Only range partitioning of base table is supported: Not hash, composite, or list Extensible indexing limitation Partition key cannot be the SDO_GEOMETRY column Choose a partition key that: Is likely to be in the WHERE clause Creates meaningful partitions when geometries are separated based on the partition key value Oracle Spatial Index Partitioning You can use Oracle Spatial index partitioning only if the base table is partitioned by range. Range partitions are populated according to the value in the partition key column. Valid range partition key columns must contain scalar values, such as number, text, or date. Raw, LOB, BLOB, or object type columns are not valid range partition keys. Hash partitioning (based on a hash function applied to the values in a column), composite partitioning (where first a range partition is done, then a hash partition is done), and list partitioning (based on discrete scalar values) are not currently supported for spatial partitioned indexes. Based on the restrictions noted previously, a partition key cannot be of type SDO_GEOMETRY, but it is possible to partition by location, which is discussed in the section titled “Parallel Partitioned Spatial Index Creation and Query.” Oracle Spatial 10g: Advanced
22
Oracle Spatial Index Partitioning
With an effective partition key, performance gains attributed to partitioning are greater on larger tables. CREATE TABLE yellow_pages_part (id NUMBER, name VARCHAR2(50), category NUMBER, location SDO_GEOMETRY) PARTITION BY RANGE (category) (PARTITION p1 VALUES LESS THAN (2), PARTITION p2 VALUES LESS THAN (3), PARTITION p3 VALUES LESS THAN (4), PARTITION p4 VALUES LESS THAN (5), PARTITION p5 VALUES LESS THAN (6), PARTITION p6 VALUES LESS THAN (MAXVALUE)); Oracle Spatial Index Partitioning (continued) With an effective partitioning key, performance gains attributable to partitioning are greater on larger tables. The example shows the creation of a partitioned table called YELLOW_PAGES_PART. YELLOW_PAGES_PART is partitioned by range on the CATEGORY column, and has six partitions named P1 through P6. The following describes which rows are stored in each partition: P1 contains rows for businesses that have a category value less than 2. P2 contains rows for businesses that have a category value less than 3. P3 contains rows for businesses that have a category value less than 4. P4 contains rows for businesses that have a category value less than 5. P5 contains rows for businesses that have a category value less than 6. P6 contains rows for businesses that have a category value greater than or equal to 6. The partition key must be present in the WHERE clause for performance benefits attributed to partitioning. Also, you should choose a partition key that groups your geometries into partitions in a meaningful way. In this example, the data is partitioned by CATEGORY. Placing CATEGORY in the WHERE clause ensures that a spatial operator searches index entries for geometries associated only with that category. Oracle Spatial 10g: Advanced
23
Spatial Index Partitioning Syntax
CREATE INDEX yp_part_sidx ON yellow_pages_part (location) INDEXTYPE IS MDSYS.SPATIAL_INDEX PARAMETERS ('LAYER_GTYPE=POINT') LOCAL (PARTITION ip1 PARAMETERS ('TABLESPACE=TBS_1'), PARTITION ip2 PARAMETERS ('TABLESPACE=TBS_2'), PARTITION ip3, PARTITION ip4, PARTITION ip5, PARTITION ip6); The LOCAL keyword is required to create a partitioned index. If the LOCAL keyword is not specified, a global index is created. Spatial Index Partitioning Syntax The syntax to create a partitioned spatial index on a partitioned table is very similar to the syntax required to create a spatial index. The syntax starts identically. Where the nonpartitioned CREATE INDEX syntax ends, the keyword LOCAL is specified, then optional partitioning information is specified on a per-partition basis (if no optional parameters are specified, the statement can end after the LOCAL keyword). The parameters work the same way as the parameters in the CREATE INDEX statement. In the example above, the index partitions are named IP1 through IP6, corresponding to index partitions P1 through P6. Note that initial partitioning information comes from the first PARAMETERS clause in the CREATE INDEX statement. Each of the PARAMETERS clauses for the local partitions overrides the initial spatial index parameter information. If a partition’s PARAMETERS clause is omitted, then the index parameters in the first PARAMETERS clause are used. Oracle Spatial 10g: Advanced
24
Spatial Index Partitioning Best Practices
Some customers who use Oracle Spatial have several hundreds of partitions. In the previous CREATE INDEX statement, if any partition’s index fails to build, the whole index build fails, and the whole index needs to be rebuilt A better way would be: Create the spatial index with the UNUSABLE keyword Creates all of the index metadata without actually creating the index Next, do an ALTER INDEX … REBUILD PARTITION Can do this in parallel from different sessions If any partition’s index fails to build, you can rebuild only that partition’s index Spatial Index Partitioning Best Practices Sometimes, a partition’s index may fail to build. For instance, this may happen due to lack of space. In the previous CREATE INDEX statement, if any partition’s index fails to build, the entire index needs to be rebuilt. To enhance availability, the Oracle database enables you to create indexes with the UNUSABLE keyword, which sets up the metadata for the index without actually building it. Then you can use the ALTER INDEX … REBUILD PARTITION command to individually create each of the partition’s indexes. If any partition’s index fails to build, then just that partition’s index can be rebuilt. As long as queries do not access that partition’s index, the rest of the index is available. Using the following query, you can find out if any partition’s index has not been built properly: SELECT status, partition_name FROM user_ind_partitions WHERE index_name = 'YP_PART_SIDX' AND status <> 'USABLE'; Oracle Spatial 10g: Advanced
25
Spatial Index Partitioning Best Practices
CREATE INDEX yp_part_sidx ON yellow_pages_part (location) INDEXTYPE IS MDSYS.SPATIAL_INDEX PARAMETERS ('LAYER_GTYPE=POINT') LOCAL (PARTITION ip1 PARAMETERS ('TABLESPACE=TBS_1'), PARTITION ip2 PARAMETERS ('TABLESPACE=TBS_2'), PARTITION ip3, PARTITION ip4, PARTITION ip5, PARTITION ip6) UNUSABLE; ALTER INDEX yp_part_sidx REBUILD PARTITION ip1; ALTER INDEX yp_part_sidx REBUILD PARTITION ip2; ALTER INDEX yp_part_sidx REBUILD PARTITION ip3; ALTER INDEX yp_part_sidx REBUILD PARTITION ip4; ALTER INDEX yp_part_sidx REBUILD PARTITION ip5; ALTER INDEX yp_part_sidx REBUILD PARTITION ip6; Spatial Index Partitioning Best Practices (continued) The example above shows the creation of an UNUSABLE spatial index. Note that the syntax is the same as previously shown, with the UNUSABLE keyword added to the CREATE INDEX statement. After the index is created with the UNUSABLE keyword, each partition’s local index is built using the ALTER INDEX … REBUILD PARTITION syntax shown. Oracle Spatial 10g: Advanced
26
Spatial Index Partitioning Restrictions
The partition key must be a scalar value. Hash, composite, and list partitioning are not supported. The SDO_INDX_DIMS and SDO_RTR_PCTFREE index parameters must be the same across all partitions. Other parameters, such as storage parameters, can and should be different for each partition. The ALTER TABLE partitioning functionality works: Can exchange a partition with another table and its index Can split and merge table partitions Split/merge requires a rebuild of associated spatial indexes Spatial Index Partitioning Restrictions Oracle Spatial index partitioning can be used only if the base table is partitioned by range. Range partitions are populated according to the value in the partition key column. Valid range partition key columns must contain scalar values, such as number, text, or date. Raw, LOB, BLOB, or object type columns are not valid range partition keys. Hash (based on a hash function applied to the values in a column), composite (where first a range partition is done, then a hash partition is done) and list (based on specific values) partitioning are not supported for spatial partitioned indexes. The SDO_INDX_DIMS spatial index parameter must be the same for each partition. The exchange partition alter table functionality is enabled with partitioned spatial indexes. Exchange partition exchanges data and indexes from a nonpartitioned table with the data and indexes from one partition of a partitioned table. Partitions with spatial indexes may be split or merged. Split partition takes a single partition and subdivides it based on finer granularity associated with the partitioning key. Merge partition takes multiple partitions and merges them together, and, therefore, there are fewer partitions. When partitions are merged, the partitioning key encompasses more data. If partitions are split/merged, the spatial index associated with each partition must be rebuilt. Oracle Spatial 10g: Advanced
27
Query Examples Using Partitioned and Nonpartitioned Tables
Oracle Spatial 10g: Advanced
28
Nonpartitioned Example
How many restaurants are within eight miles of a given location? Note: Sometimes, no_index hints can help performance, irrespective of partitioning. -- nonpartitioned case SELECT count(*) FROM yellow_pages a WHERE sdo_within_distance (a.location, sdo_geometry (2001, 8307, sdo_point_type (-73.8, 40.7, null), null, null), 'distance=8 unit=mile') = 'TRUE' AND category = 1; -- runs in 1.70 seconds -- nonpartitioned case SELECT /*+ no_index (a yp_category_idx) */ count(*) FROM yellow_pages a WHERE sdo_within_distance (a.location, sdo_geometry (2001, 8307, sdo_point_type (-73.8, 40.7, null), null, null), 'distance=8 unit=mile') = 'TRUE' AND category = 1; -- runs in 0.44 seconds Nonpartitioned Example Both queries in this slide are answering the following question, “How many restaurants are within eight miles of a given location?” Both queries are executed using a nonpartitioned yellow pages table. The nonpartitioned table has an index on CATEGORY (yp_category_idx) and a spatial index on LOCATION. Category 1 corresponds to restaurants. Note: The second query ran faster when the yp_category_idx index is disabled with the no_index hint. Sometimes, it is faster to reduce the selected set returned from a spatial operator without using other indexes. This holds true for nonpartitioned as well as partitioned tables. But, remember that when joining to other tables, that nonspatial indexes are critical for optimal performance. The examples above are not of those joining to other tables. Oracle Spatial 10g: Advanced
29
Oracle Spatial 10g: Advanced 1-29
Partitioned Example How many restaurants are within eight miles of a given location? -- partitioned case SELECT count(*) FROM yellow_pages_part a WHERE sdo_within_distance (a.location, sdo_geometry (2001, 8307, sdo_point_type (-73.8, 40.7, null), null, null), 'distance=8 unit=mile') = 'TRUE' AND category = 1; -- runs in 0.08 seconds Partitioned Example This query above answers the same question posed in the previous slide, “How many restaurants are within eight miles of a given location?” This query is executed against the partitioned yellow pages table, and the partition key (CATEGORY) is in the WHERE clause. This query ran faster than the queries against the nonpartitioned table in the previous slide. Oracle Spatial 10g: Advanced
30
Partitioned Example: SDO_NN
Find the three closest businesses (any kind) to a given location: SDO_NN executes once per partition. This example does not include a partition key, so all the six partitions are searched. This example sets ‘SDO_NUM_RES=3’, but returns 18 rows (three rows per partition). The next slide shows how to answer the question above (that is, return only three rows). -- This query does not answer the question above -- (returns more than three rows) SELECT name, sdo_nn_distance(1) distance FROM yellow_pages_part a WHERE sdo_nn (a.location, sdo_geometry (2001, 8307, sdo_point_type ( , , null), null, null), 'sdo_num_res=3 unit=mile', 1) = 'TRUE' ORDER BY distance; Partitioned Example: SDO_NN The requirement posed in this slide is to find the three closest businesses to a given location. The yellow pages table is partitioned by business category, but this query cannot benefit from the partition key (all partitions must be searched). The SDO_NN operator executes once per partition. The query shown above sets ‘SDO_NUM_RES=3’, but returns 18 rows (3 rows multiplied by 6 partitions). This query does not meet the requirement specified, which is to find the three closest businesses to a given location. The next slide shows you how to find the three closest businesses. Oracle Spatial 10g: Advanced
31
Partitioned Example: SDO_NN
Find the three closest businesses (any kind) to a given location. The example below ensures only three rows are returned. When more than one partition is searched, and a specific number of results are desired, SDO_NN must use an inline view with rownum < some_value) outside of the inline view. In the example below, the inline view returns 18 rows (three rows per partition) and rownum < 4 reduces the result set to three rows: -- partitioned table - query does not include partition key SELECT name, distance FROM (SELECT name, sdo_nn_distance(1) distance FROM yellow_pages_part a WHERE sdo_nn (a.location, sdo_geometry (2001, 8307, sdo_point_type ( , ,null), null, null), 'sdo_num_res=3 unit=mile', 1) = 'TRUE' ORDER BY distance) WHERE rownum < 4; Partitioned Example: SDO_NN (continued) This query returns the three closest businesses to the specified point. When more than one partition is searched, and a specific number of results are desired, SDO_NN must use an inline view with rownum < (some_value) outside the inline view. In this query, the inline view contains the SQL statement shown in the previous slide (that returns 18 rows), and the result is constrained to three rows by specifying WHERE rownum < 4 outside of the inline view. Oracle Spatial 10g: Advanced
32
Partitioned Example: SDO_NN
Find the three closest restaurants to a given location: If looking only for restaurants, include the restaurant category partition key Restaurant category partition key ensures only one partition is searched; inline view is not necessary This query returns the three closest restaurants: -- partitioned table - query includes partition key and -- use of the inline view is not necessary SELECT name, sdo_nn_distance(1) distance FROM yellow_pages_part a WHERE a.category = 1 AND sdo_nn (a.location, sdo_geometry (2001, 8307, sdo_point_type ( , , null), null, null), 'sdo_num_res=3 unit=mile', 1) = 'TRUE' ORDER BY distance; Partitioned Example: SDO_NN (continued) This query returns the three closest restaurants to a specified point. Because restaurants correspond to a partition key value (category = 1), this query can be narrowed down to search a single partition. Because a single partition is searched, no inline view is necessary to ensure that ‘SDO_NUM_RES’ results are returned. Oracle Spatial 10g: Advanced
33
Partitioned Example: SDO_NN
Find the three closest Italian restaurants to a given location If looking only for restaurants, include the restaurant category partition key Restaurant category partition key ensures only one partition is searched This query returns the three closest Italian restaurants: -- partitioned table - query includes the partition key -- and uses sdo_batch_size instead of sdo_num_res SELECT name, sdo_nn_distance(1) distance FROM yellow_pages_part a WHERE a.category = 1 AND sdo_nn (a.location, sdo_geometry (2001, 8307, sdo_point_type ( , , null), null, null), 'sdo_batch_size=0 unit=mile', 1) = 'TRUE' AND a.name like '%ITALIAN%' AND rownum < 4 ORDER BY distance; Partitioned Example: SDO_NN (continued) This query returns the three Italian restaurants closest to a specified point. Because restaurants correspond to a partition key value (category = 1), this query can be narrowed down to search a single partition. As discussed in the lesson “Oracle Spatial 10g Enhancement” where SDO_NN was introduced, to locate nearest neighbors and also constrain by other attributes (that is, name like ‘%ITALIAN%’), SDO_BATCH_SIZE must be used (not SDO_NUM_RES). As discussed in the previous lesson, it is okay to have rownum < (some_value) followed by an ORDER BY distance clause when using SDO_NN. Traditionally, rownum < (some_value) followed by an ORDER BY clause will not guarantee correct results, but SDO_NN returns candidates in distance order to the WHERE clause, and correct results are guaranteed. Oracle Spatial 10g: Advanced
34
Parallel Partitioned Spatial Index Creation
When the PARALLEL keyword is specified: Multiple partitions are indexed in parallel. The number of parallel processes is determined by: Degree in PARALLEL [<DEGREE>] syntax Oracle algorithms when PARALLEL is specified without <DEGREE> Intra-partition parallelism is not supported: Within each partition there is no parallelism, unlike nonpartitioned tables Instead, PARALLEL [<DEGREE>] partition’s indexes are built in parallel Parallel Partitioned Spatial Index Creation Currently, Oracle Spatial supports inter-partition parallelism (multiple partitions indexed in parallel). Oracle Spatial does not support intra-partition parallelism (no further parallelism is done for the individual partitions). If there are four index partitions and Oracle Spatial is set up with the capability of allowing a parallel degree of four, then all index partitions are created concurrently using parallelism. Within each partition there is no parallelism. Oracle Spatial 10g: Advanced
35
Parallel Partitioned Spatial Index: Query
After the spatial index is created: Parallel query (across partitions) is supported Only useful if more than one partition is searched If spatial index is created without the parallel keyword, you can add parallelism: ALTER INDEX <index_name> PARALLEL [<degree>]; Parallel Partitioned Spatial Index: Query Parallel query across partitions is supported when the spatial index is created with the parallel keyword. Parallelism is used only when more than one partition is searched. Parallel query can also be enabled by altering the index as follows: alter index <index_name> parallel [<degree>]; Up to <degree> number of processes are used to search the index contents. If <degree> is not specified, the Oracle database calculates the best value based on the system. The Oracle database configures all parallel related parameters for a system automatically. For more information about tuning for parallelism, see the lesson “Using Parallel Execution” in the Oracle Database Data Warehousing Guide 10g. Oracle Spatial 10g: Advanced
36
Spatial Partitioning of Data
Oracle Spatial 10g: Advanced
37
Parallel Partitioned Spatial Index Creation and Query
Spatial data can be partitioned based on its location Some spatial customers have a regional partition key: All of the benefits of spatial partitioning that are discussed in this section are automatically included. Can partition on X (Longitude) or Y (Latitude) Can partition using both X and Y Can partition using a traditional partition key such as date and location partitioning Parallel Partitioned Spatial Index Creation and Query Spatial data can be partitioned on the basis of its location. Some customers partition data on the basis of a regional partition key. Other customers partition data on the basis of county. No matter how a partition key is derived, if it is location based, then the functionality described in this section is automatically used. You can also physically set up data to be partitioned by location. For instance, you can partition on the X and Y coordinates, or the X and Y coordinates with another partition key. Oracle Spatial 10g: Advanced
38
Spatial Partition Pruning
The Oracle optimizer does partition elimination on the basis of a partition key. In a similar fashion, Oracle Spatial can automatically eliminate partitions by using spatial partition pruning. Included in spatial index metadata is SDO_ROOT_MBR The minimum-bounding rectangle encompassing the spatial data in that indexed partition. At query time, Oracle Spatial compares the query window minimum bounding rectangle (MBR) with the partition’s SDO_ROOT_MBR. If there is no overlap, then no further processing is done on that partition. Spatial Partition Pruning Similar to the way the Oracle optimizer can do partition elimination based on a partition key, Oracle Spatial can automatically eliminate partitions based on the location of the query window. Each partition’s index metadata includes a column named SDO_ROOT_MBR. This column contains the minimum-bounding rectangle (MBR) around all of the geometries in that partition. When a spatial query is executed, Oracle Spatial compares the query window MBR with the contents of SDO_ROOT_MBR for each partition. If there is no overlap, then Oracle Spatial does no further processing associated with that partition. Oracle Spatial 10g: Advanced
39
Spatial Partition Pruning
Used with these Spatial operators SDO_WITHIN_DISTANCE SDO_FILTER SDO_RELATE and relationship operators such as SDO_ANYINTERACT Completely transparent and automatic Requires no partition key in the WHERE clause Including a spatial partition key can be incorrect Occurs at run time Spatial Partition Pruning (continued) Spatial partition pruning is used with the operators SDO_FILTER, SDO_RELATE and the relationship operators such as SDO_ANYINTERACT and SDO_INSIDE, and SDO_WITHIN_DISTANCE. Spatial partition pruning is completely automatic within Oracle Spatial. You are not required to include a partition key, and in many cases using a partition key can be incorrect. Spatial partition pruning occurs at run time. Oracle Spatial 10g: Advanced
40
Spatially Partitioned Table and Index: Multicolumn Key
data partitioned index root MBR (not all shown) query window MBR Spatially Partitioned Table and Index: Multicolumn Key This example shows 16 partitions based on X and Y. The small dotted rectangles are stored geometries. When the index is built, each partition’s metadata includes SDO_ROOT_MBR, which has values that are represented by the dashed lines (not all of the SDO_ROOT_MBR contents are shown in this slide). When a query is executed, the query window MBR is compared with the stored SDO_ROOT_MBR in the index. If there is an overlap between the query window and the SDO_ROOT_MBR value, then the partition is checked for a spatial interaction. Otherwise, Oracle Spatial prunes the partition, and no further processing occurs. You can see that some polygons cross the partition boundaries. The partition these geometries are stored in is dependent on the function used for partitioning. For this reason, even though the query window is in a specific partition, do not specify a spatial partition key or the results may not include all the desired data. Oracle Spatial 10g: Advanced
42
Performance Considerations of Spatial Partitioning
Large geometries (in area or length) that cross multiple partitions cause the SDO_ROOT_MBR to expand: Reduces the effectiveness of spatial partitioning If only a few, can create a separate partition: You can use geometry length or area or MBR area as a criteria to determine if data should be pushed off to a special partition. Performance Considerations of Spatial Partitioning Large geometries that cross multiple partitions can cause the SDO_ROOT_MBR to expand. If the SDO_ROOT_MBR is very large, it reduces the effectiveness of the spatial partitioning. If there are not too many of these geometries, a separate partition can be created to hold these special case geometries. You should determine algorithmically when to put geometries in the special partition, possibly using length, area, or MBR area. Oracle Spatial 10g: Advanced
43
Performance Considerations of Spatial Partitioning
Overhead associated with checking each partition: A little bit over one millisecond/partition on 1.5 Ghz Itanium box If a very large number of partitions, overhead can be substantial Performance Considerations of Spatial Partitioning (continued) There is some overhead associated with checking each spatial partition. This has been shown to be approximately one millisecond on a 1.5 Ghz Itanium Linux box. If there are a large number of partitions, the overhead can be substantial. For instance, if one spatially partitioned the Earth into one degree by one degree cells, then there would be over 64,000 partitions. That means any spatial query would have an overhead of about 64 seconds. Note if the Oracle optimizer does partition elimination, then there is no extra overhead associated with partitions that are eliminated at that level. The Oracle Spatial team is working with other development groups to reduce this overhead. Oracle Spatial 10g: Advanced
44
Transportable Tablespaces and Spatial Indexes
Oracle Spatial 10g: Advanced
45
Transportable Tablespaces
Transportable tablespaces allow you to copy database files from one system to another system. Use Oracle Export and Import utilities Specific setup must be done before and after transporting spatial data with spatial indexes Oracle database allows you to copy database files from one endian platform to a different endian platform. Spatial data can be moved Spatial indexes cannot be transported across endian platforms Transportable Tablespaces Transportable tablespaces is an Oracle database feature that allows you to copy database files from one system to another system. This is done using Oracle’s Export and Import utilities. Transportable tablespaces that include spatial indexes are supported starting in Oracle Database 10g. The Oracle database also has a feature called Cross Platform Transportable Tablespaces that allows you to copy database files from one type of endian platform (for example, an Intel processor-based machine) to another type of endian platform (for instance, Sun SPARC). Spatial data can be transported across platforms, but currently spatial indexes cannot be transported across platforms. To see all available platforms and their endian formats, enter: SQL> SELECT * FROM V$TRANSPORTABLE_PLATFORM; Example results are: PLATFORM_ID PLATFORM_NAME ENDIAN_FORMAT Solaris[tm] OE (32-bit) Big Linux IA (32-bit) Little Apple Mac OS Big Oracle Spatial 10g: Advanced
46
Transportable Tablespace Support for Spatial Indexes
Oracle10g Spatial includes transportable tablespace support for spatial indexes: Each user with a spatial index in the tablespace to be transported executes SDO_UTIL.PREPARE_FOR_TTS (TABLESPACE_NAME) before the export. After import, each user with transported spatial indexes must run SDO_UTIL.INITIALIZE_INDEXES_FOR_TTS. EXECUTE SDO_UTIL.PREPARE_FOR_TTS('TABLESPACE_NAME'); Transportable Tablespace Support for Spatial Indexes Transportable tablespaces with spatial indexes are supported in Oracle Database 10g. You must run SDO_UTIL.PREPARE_FOR_TTS before exporting the tablespace if you have spatial indexes in the tablespace to be transported. After importing the tablespace, you must run SDO_UTIL.INITIALIZE_INDEXES_FOR_TTS if you have transported spatial indexes. Oracle Spatial 10g: Advanced
47
Transportable Tablespace: Example
-- Each user with spatial indexes associated with tables -- in transportable tablespace TTBS_DAT that will also be -- moved as part of the transport set will need to do the -- following. This example is for user SCOTT. SCOTT has -- tables in TTBS_DAT and indexes in TTBS_IDX. CONNECT SYSTEM/PW4SYSTEM -- First, make sure SCOTT’s default tablespace is in the -- transport set, because SDO_UTIL.PREPARE_FOR_TTS will -- create a table to be moved in the tablespace. ALTER USER SCOTT DEFAULT TABLESPACE TTBS_DAT; -- CONNECT SCOTT/TIGER EXECUTE SDO_UTIL.PREPARE_FOR_TTS('TTBS_DAT'); -- Connect as sysdba to check if tablespace is OK to move CONNECT SYSTEM/PW4SYSTEM AS SYSDBA -- Execute procedure which checks transportability EXECUTE DBMS_TTS.TRANSPORT_SET_CHECK('TTBS_DAT,TTBS_IDX',TRUE); Transportable Tablespace: Example This is an example of using the transportable tablespace procedures before and after transporting tablespaces. Oracle Spatial 10g: Advanced
48
Transportable Tablespace: Example
-- Valid transport set if the following returns no rows SELECT * FROM TRANSPORT_SET_VIOLATIONS; -- Set tablespace to read only ALTER TABLESPACE ttbs_dat READ ONLY; ALTER TABLESPACE ttbs_idx READ ONLY; -- Using data pump export, the directory to write the dump -- file (which will contain metadata only) has be be created -- and write privileges have to be granted to the user. -- Additionally, any user who will export transportable -- tablespaces needs to be granted EXP_FULL_DATABASE privilege CREATE DIRECTORY dumpdir AS '/usr/dir/dumpfiles'; GRANT READ,WRITE ON DIRECTORY dumpdir TO scott; GRANT EXP_FULL_DATABASE TO scott; -- When transportable tablespace export is done, data gets -- written in a tablespace associated with the user exporting -- the data, so set SCOTT’s default tablespace to one that -- can be written to. Transportable Tablespace: Example (continued) This is a continuation of the example of using the transportable tablespace procedures before and after transporting tablespaces. Oracle Spatial 10g: Advanced
49
Transportable Tablespace: Example
ALTER USER SCOTT DEFAULT TABLESPACE USERS; exit; -- export (note all params must be on the same line) EXPDP SCOTT/TIGER DIRECTORY=DUMPDIR DUMPFILE=ttbs_md.dmp TRANSPORT_TABLESPACES=TTBS_DAT,TTBS_IDX -- Copy dump and tablespace files to other Oracle 10g instance -- The tablespace files can go to their destination directory -- The user who does the import needs to be granted READ and -- WRITE privileges to the directory containing the export -- file, and also requires the IMP_FULL_DATABASE privilege -- Cross-endian transportable tablespaces are supported with -- spatial data and not supported with spatial indexes CONNECT SYSTEM/PW4OTHERSYSTEM CREATE DIRECTORY otherdumpdir AS '/usr/otherdir/dumpfiles'; GRANT READ,WRITE ON DIRECTORY otherdumpdir TO scott; GRANT IMP_FULL_DATABASE TO scott; EXIT; Transportable Tablespace: Example (continued) This is a continuation of the example of using the transportable tablespace procedures before and after transporting tablespaces. The source and target hardware Endian encoding must be the same when transporting tablespaces that include spatially indexed columns. Oracle Spatial 10g: Advanced
50
Transportable Tablespace: Example
-- Import using data pump. All parameters below should be -- on the same line, or in a parameter file impdp scott/tiger DIRECTORY=otherdumpdir DUMPFILE=ttbs_md.dmp TRANSPORT_DATAFILES='/usr/orcl10g/ttbs/course_dat.dbf', '/usr/orcl10g/ttbs/course_idx.dbf' -- Allow reads and writes on new tablespaces (just imported) SQLPLUS system/pw4othersystem ALTER TABLESPACE ttbs_dat READ WRITE; ALTER TABLESPACE ttbs_idx READ WRITE; -- For each user who has spatial indexes in transportable -- tablespace: CONNECT scott/tiger; EXEC sdo_util.initialize_indexes_for_tts; Transportable Tablespace: Example (continued) This is a continuation of the example of using the transportable tablespace procedures before and after transporting tablespaces. Oracle Spatial 10g: Advanced
51
Function-Based Indexes
Oracle Spatial 10g: Advanced
52
Function-Based Indexes
In the Oracle database, function-based indexes allow you to build an index on the results of a function. If a search by last name was often done using a substring function (for example, to find the last names that begin with ‘SMI’), a function-based index can be built using SUBSTR(LAST_NAME,1,3). Function-based indexes allow a spatial index to be built on the result of a function that returns a geometry: Offers a powerful mechanism to enable Oracle Spatial functionality without an SDO_GEOMETRY column in the table. Function-Based Indexes Function-based indexes are not unique to Oracle Spatial. For example, a table called EMPLOYEES may have a column called LAST_NAME of type VARCHAR2(30). An index on LAST_NAME can help to quickly find all of the employees with LAST_NAME=‘SMITH’. If an application requires that a search be done on LAST_NAME starting with ‘SMI’ (where searches are required to look at only the first three characters of the last name), for example, SUBSTR(LAST_NAME,1,3)=‘SMI’, the application would not utilize the index on LAST_NAME. To overcome this, a function-based index can be created on SUBSTR(LAST_NAME,1,3). Before Oracle9i Spatial, all spatial operators (that is, SDO_FILTER, SDO_RELATE, SDO_NN, and SDO_WITHIN_DISTANCE) required a column of type SDO_GEOMETRY in a table. Beginning with Oracle9i, Oracle Spatial can benefit from function-based indexes. Function-based indexes allow you to create spatial indexes on a function that returns an SDO_GEOMETRY object. Spatial operators can search function-based indexes as well as traditional spatial indexes. Having function-based indexes is an extremely powerful feature, which gives you the ability to have complete Oracle Spatial functionality with no column of type SDO_GEOMETRY in the table. This is important for many users, where an existing table includes location information stored without an SDO_GEOMETRY type and no changes are allowed to the table. Oracle Spatial 10g: Advanced
53
Function-Based Indexes
Sometimes used with legacy tables that have longitude and latitude columns Does not require an SDO_GEOMETRY column in the base table Function-Based Indexes (continued) One usage for function-based indexes is for legacy tables that have individual longitude and latitude columns that represent point locations, instead of an SDO_GEOMETRY column. For this scenario, a function can be written that puts the longitude/latitude data into the SDO_GEOMETRY type and returns it as a geometry object. There is no need to add and populate an SDO_GEOMETRY column in the legacy table. Oracle Spatial 10g: Advanced
54
Steps to Create Function-Based Indexes
Create the function that returns an SDO_GEOMETRY object: The function must be declared as DETERMINISTIC. Insert metadata into the USER_SDO_GEOM_METADATA view. Create the spatial index. Perform spatial queries on the data. Steps to Create Function-Based Indexes There are four steps required to use function-based indexes: 1. Create a function that returns an SDO_GEOMETRY object. The function must be declared DETERMINISTIC. 2. Insert metadata into the USER_SDO_GEOM_METADATA view. 3. Create a spatial index on the function. 4. Perform spatial queries using spatial operators. Spatial operators can search the function-based spatial index. Oracle Spatial 10g: Advanced
55
Function-Based Indexes: Example
-- This table was previously created and populated CREATE TABLE cities_xy( City varchar2(20), State_Abrv varchar2(2), Pop number, Rank number, City_longitude number, City_latitude number); -- Function on simple relational columns CREATE OR REPLACE FUNCTION get_geom ( longitude IN NUMBER, latitude IN NUMBER ) RETURN sdo_geometry DETERMINISTIC IS BEGIN RETURN sdo_geometry (2001,8307, sdo_point_type (longitude, latitude, NULL), NULL, NULL ); END; / Function-Based Indexes: Example The example given is a step-by-step implementation of function-based indexes. In the first step, a function is created that takes two input arguments, a longitude and a latitude value, which are both of type NUMBER. The function returns a value of type SDO_GEOMETRY. Note that the function is declared as deterministic, which is a requirement of function-based indexes. The function simply returns an SDO_GEOMETRY constructor with the following settings: SDO_GTYPE = 2001 (always a two-dimensional point) SDO_SRID = 8307 (which is WGS 84) SDO_POINT constructor populated with the longitude and latitude values passed in SDO_ELEM_INFO = NULL SDO_ORDINATE_ARRAY = NULL The next step shown is a simple CREATE TABLE statement used to create the base table against which the function will execute. Typically, this table would already exist and be populated. Oracle Spatial 10g: Advanced
56
Function-Based Indexes: Example
INSERT INTO user_sdo_geom_metadata values ('CITIES_XY', 'SCOTT.GET_GEOM(CITY_LONGITUDE,CITY_LATITUDE)' , sdo_dim_array( sdo_dim_element('LONG', -180, 180, 0.5), sdo_dim_element('LAT', -90, 90, 0.5)), 8307); CREATE INDEX cities_func_sidx ON cities_xy(get_geom(city_longitude,city_latitude)) INDEXTYPE IS mdsys.spatial_index; SELECT a.city FROM cities_xy a WHERE sdo_within_distance( get_geom(a.city_longitude,a.city_latitude), sdo_geometry(2001,8307, sdo_point_type(-73,42,NULL),NULL,NULL), 'distance = 100 unit = MILE') = 'TRUE'; Function-Based Indexes: Example (continued) Continuing the previous example, a record is inserted into the USER_SDO_GEOM_METADATA view. The first column is the table name (CITIES_XY), the second column (the COLUMN_NAME field) has the name of the function with the arguments. The arguments are the CITY_LONGITUDE and CITY_LATITUDE columns of the CITIES_XY table. Note that the name of the function is prefixed by the owner of the function. This is required to differentiate the function GET_GEOM from other functions named GET_GEOM that the user may have access to. The rest of the entry in USER_SDO_GEOM_METADATA is exactly the same as has been discussed previously. Next, the index is created on the results of the function. The only difference in the statement to create the spatial index is that the geometry column name is replaced with the function name. The function’s parameters are the CITY_LONGITUDE and CITY_LATITUDE columns from the CITIES_XY table. A geodetic R-tree function-based spatial index is created. Finally, it is possible to query the table using spatial operators by specifying the function call, which returns the SDO_GEOMETRY object. In the example given, all cities within 100 miles of the given point are returned. This example uses the function-based index for the GET_GEOM function. Oracle Spatial 10g: Advanced
57
Performance of Function-Based Indexes
Create index The function is called for each row in the table Can use PARALLEL indexing Query performance Index only (SDO_FILTER) No overhead unless the SELECT list includes function call to return geometry Secondary filter (SDO_RELATE, SDO_NN, and so on) Filter portion has no overhead Relate will need to create geometries (function call is required) Performance of Function-Based Indexes Function-based indexes affect spatial index creation performance. Depending on the type of query and the results desired, function-based indexes may also affect query performance. During the spatial index creation process, the function that returns the SDO_GEOMETRY object is called for every row in the table. The time it takes to build the index includes the overhead associated with calling the function for each row. In the function-based index examples previously discussed, the function was very simple. The function simply returned a geometry constructor. If the function is more complicated and takes longer to run, the function call overhead of the create index process also increases. The PARALLEL keyword is supported when creating a function-based index, which can reduce overall index creation time. Any query that performs a SELECT, which specifies the function that returns the geometry object, has to instantiate the geometry by calling the function. At query time, primary filter operators (that is, SDO_FILTER or SDO_WITHIN_DISTANCE specifying QUERYTYPE=FILTER) do not incur any performance overhead with spatial function-based indexes. Only the spatial function-based index is searched. The function is never called. At query time, SDO_RELATE, SDO_NN, and SDO_WITHIN_DISTANCE (without QUERYTYPE=FILTER) incur the function call overhead for each candidate returned by the index search that requires additional processing (any geometry that was not optimized directly into the result set). Oracle Spatial 10g: Advanced
58
Embedded SDO_GEOMETRY Objects
Oracle Spatial 10g: Advanced
59
Embedded Spatial Geometry
Spatial geometry type can be embedded in another user-defined type. This is useful for building applications requiring spatial and nonspatial attributes in a type. Examples: GeoRaster: Image and Geometry Cartographic Text Type: Text attributes and Geometry Embedded Spatial Geometry Oracle Spatial indexes can be built on the SDO_GEOMETRY type even if it is embedded in another type. This is extremely useful for applications that require both spatial and nonspatial attributes encapsulated in a single type. Some sample applications include: GeoRaster applications, where a type is defined to contain the perimeter of an image and the image itself. The type could be defined as containing an SDO_GEOMETRY field for the perimeter, and other fields containing information about the image as well as the database location of the image. Mapping applications, where a cartographic text type may include attributes (color, font and so on), and the associated geometry for text placement. Oracle Spatial 10g: Advanced
60
Steps to Create an Embedded Geometry
Create the new user-defined type. Create and populate a column of that type. Insert the geometry metadata. Create a spatial index on the geometry attribute. Perform spatial queries. Steps to Create an Embedded Geometry The procedure to index and query embedded types is similar to the procedure for nonembedded SDO_GEOMETRY columns. There are some minor syntax changes: 1. The user-defined type is created first. 2. Then a table is created that has a column of that type. The column is populated with appropriate data. 3. The USER_SDO_GEOM_METADATA view is populated. 4. An index can then be created on the SDO_GEOMETRY attribute of the user-defined type. 5. Spatial operators use the embedded attribute’s spatial index. Oracle Spatial 10g: Advanced
61
Embedded Geometry: Example
create or replace type Street_Address as Object ( Street varchar2(200), City varchar2(200), State char(2), Zip varchar2(20)); / create or replace type Address_T as object ( St_Address Street_Address, Location sdo_geometry); create table customers( name varchar2(100), address Address_T); Embedded Geometry: Example In this example, two user-defined types are created: Street_Address (with the following attributes or fields): Street City State Zip Address_T (with the following attributes or fields): St_Address of Street_Address type Location of type SDO_GEOMETRY A table is created with two columns, NAME and ADDRESS. Note that ADDRESS is of type Address_T, and contains the information described above. Oracle Spatial 10g: Advanced
62
Embedded Geometry: Example
insert into user_sdo_geom_metadata values ( 'CUSTOMERS', 'ADDRESS.LOCATION', sdo_dim_array ( sdo_dim_element ('Long', -180, 180, 0.5), sdo_dim_element ('Lat', -90, 90, 0.5)), 8307); insert into customers values (…)… create index cust_sidx on customers(address.location) indextype is mdsys.spatial_index; select a.Name from customers a where sdo_within_distance( a.address.location, sdo_geometry(2001, 8307, sdo_point_type( , ,NULL),NULL,NULL), 'distance = 5 unit = MILE') = 'TRUE'; Embedded Geometry: Example (continued) Continuing the example, the USER_SDO_GEOM_METADATA view is populated with the following: CUSTOMERS is the table name. The column name is the embedded geometry attribute in the type. In this example, it is the LOCATION attribute of the ADDRESS column. The rest of the information inserted into the USER_SDO_GEOM_METADATA view is the same as previously described. Next, data is inserted into the table, and a spatial index is created. In this example, an R-tree index called CUST_SIDX is created on the LOCATION attribute of the ADDRESS column in the CUSTOMERS table. Finally, a spatial query is shown that returns the name of any customer within five miles of ( , ). Note: This query requires a table alias (in this case it is “a”). This is a requirement in Oracle Spatial whenever accessing attributes or member functions of an object. Oracle Spatial 10g: Advanced
63
Oracle Spatial 10g: Advanced 1-65
Summary In this lesson, you should have learned how to: Create and use partitioned spatial indexes Discuss spatial partitioning of data Export and import transportable tablespaces that include spatial indexes Create and use function-based indexes Embed and index spatial objects within objects Summary This lesson described the process of building spatial indexes by using advanced indexing mechanisms. Oracle Spatial 10g: Advanced
64
Oracle Spatial GeoRaster
65
Oracle Spatial 10g: Advanced 1-67
Objectives After completing this lesson, you should be able to: Describe what raster data is Explain Oracle Spatial GeoRaster concepts Discuss Oracle Spatial GeoRaster storage Load GeoRaster data View GeoRaster data using MapViewer Oracle Spatial 10g: Advanced
66
Oracle Spatial 10g: Advanced 1-68
What Is Raster Data? Raster data is spatial data created by assigning values to a matrix of cells that cover objects. What Is Raster Data? Raster data is spatial data created by assigning values to arrays in a matrix of cells that cover objects. For example, you can think of overlaying a piece of graph paper at an area of interest, where each cell is assigned a value representing the data in that cell. The objects can be mapped to their position on the surface of the earth if they include location information. Raster data has other names including grid data and digital imagery. Oracle Spatial 10g: Advanced
67
Raster Data Features and Cell Size
Coarser resolution Finer resolution Raster Data Features and Cell Size Within a raster matrix, each individual row and column pair is a cell. Features in a raster are generated by assigning values to cells within a matrix, where each cell contains only one value. A matrix can contain many features. The smaller the cell size, the finer the resolution of the data. Coarse resolution raster data uses fewer cells to cover a given area than fine resolution data. Finer resolution data: Stores smaller, more numerous cells Requires more storage Results in more accurate feature representation May take more time to process Oracle Spatial 10g: Advanced
68
Raster/Vector Data Differences
Vector Data Vector Coordinates Raster Data – , – , , – , , – , – , , – , , – , , – , Raster/Vector Data Differences This slide illustrates the differences between vector data and raster data. Points, lines, and polygons can be precisely defined in vector format; however, in raster format they are approximated using a matrix or grid. The storage requirement for vector data can be quite small, but in the case of raster data the entire matrix is always stored. Within that matrix, each individual row/column pair is a cell. In vector format, to draw data other than points, the data between defined coordinates must be calculated and drawn. In raster format, the matrix can be mapped to a display, where each cell is mapped to a section of the display. The value of each cell determines how it is displayed. Oracle Spatial 10g: Advanced
69
Raster/Vector Data Differences
How does raster data differ from vector data? Vector data: Is defined using precise coordinates that define a point, line, or polygon Needs sparse representation (requires less storage) Is good for representing map features Is good for describing connectivity (topology) Raster data: Is defined using one or more cells that approximate a point, line, or polygon Is good for representing and analyzing large, filled regions Always requires storage of a complete matrix of cells Typically requires much more storage space Raster/Vector Data Differences (continued) Vector data is defined using precise coordinates that can define a point, two or more points that define a line string, and three or more points that define a polygon. The coordinates can be sparse in line string or polygon. For instance, if a line is a straight line between two points, only the start and end points of the line are required. If a rectangle is stored, only the four coordinates at the corners can be used to define it. Vector data is good for representing and drawing map features, and is also well suited for describing connectivity relationships between objects in space. Raster data approximates points, lines, and polygons by assigning cell values in a matrix. The cells are part of a complete matrix, and the entire matrix must be stored. Raster data is ideally suited to represent large, filled regions. Cell values provide more information about the filled region. For example, if the large, filled region is a lake, the cell values can represent depth. Oracle Spatial 10g: Advanced
70
What Is Oracle Spatial GeoRaster?
The GeoRaster schema includes: SDO_GEORASTER: Oracle’s data type for raster data Raster metadata required for storage and retrieval You can store, index, query, and analyze GeoRaster data in Oracle Spatial 10g GeoRaster data can be categorized as: Grid Raster Data Digital Imagery Raster Data What Is Oracle Spatial GeoRaster? Raster data is spatial data created by assigning values to arrays in a matrix of cells that cover objects. The objects can be mapped to their positions on the surface of the Earth if they include location information. Oracle Spatial 10g introduces a new native data type, SDO_GEORASTER, to store raster data. Ordinary Oracle tables can contain columns of type SDO_GEORASTER. Oracle Spatial GeoRaster defines a schema including the data type and a set of metadata required for storage and retrieval of raster data. Oracle Spatial 10g GeoRaster can store, index, query, and analyze raster data. It leverages all of the benefits of using the Oracle database, including security, scalability, manageability, high availability, and so on. Oracle Spatial GeoRaster stores: Grid data Digital imagery Oracle Spatial 10g: Advanced
71
GeoRaster: Grid Raster Data Concepts
Oracle Spatial 10g: Advanced
72
Oracle Spatial 10g: Advanced 1-74
Grid Raster Data A Value Attribute Table (VAT) is used to map numeric cell values with their meaning. Given below is an example of a Value Attribute Table for geological raster data: Stored cell values 6 1 3 8 7 9 5 2 4 CELL VALUE GEOLOGICAL PERIOD Quaternary Tertiary Paleocene–Cretaceous Mesozoic Gondwana Early Paleozoic Proterozoic Early Proterozoic Archaean Blank Cell (no data) Grid Raster Data A Value Attribute Table (VAT) ties the allowable stored values for each cell to the meaning of those stored values. In the example above, the cell values 1 through 9 represent the geological periods from the most recent (Quaternary) to the most ancient (Archaean). If no cell data is collected for a location, or if it does not make sense to include cell data for a location (for example, locations associated with the ocean), those cells can be assigned an empty cell value. Note that the grid data to the right contains an appropriate value for each cell. A Value Attribute Table can be extended to contain other user-defined information. Note: A VAT can also contain user-defined columns. Oracle Spatial 10g: Advanced
73
Grid Raster Data: Colormap Table
A colormap table maps the range of possible cell values to colors. It is useful for rendering a raster. Given below is a sample colormap table for geological raster data: 6 1 3 8 7 9 5 2 4 CELL VALUE Red Green Blue Grid Raster Data: Colormap Table A colormap table associates cell values with colors that can be used for display purposes. Shown above is an example of an RGB (Red Green Blue) colormap for the geological data previously described. The example colormap table in this slide shows each allowable cell value and an associated color used when the grid cells are rendered as a map. The upper-right portion of the slide contains a grid with its cell values. The lower-right portion of the slide contains a grid that leverages colormap information when it is rendered. In this example, valid colormap values range from 0 to 255. Often, colormaps also include an alpha value associated with opacity. Oracle Spatial 10g: Advanced
74
Geological Map of India (Grid Data)
Quaternary Tertiary Paleocene–Cretaceous Mesozoic Gondwana Early Paleozoic Late Proterozoic Early Proterozoic Archaean Geological Map of India (Grid Data) This geological map of India is an example of grid data. Various geological types are encoded and displayed as different colors. The legend combines information in the Value Attribute Table (VAT) and the colormap table to help users understand the meaning of the map. Oracle Spatial 10g: Advanced
75
GeoRaster: Digital Imagery Raster Data Concepts
Oracle Spatial 10g: Advanced
76
Raster Data Concepts: Digital Imagery
A digital image is a two-dimensional array of regularly spaced picture elements (pixels). Pixel values are collected from optical or other sensors, such as satellite remote sensing, airborne photogrammetry, and sonar. Digital images can comprise one or more bands: A band typically represents a complete matrix of pixel values associated with data collected from one sensor. Band data can be simultaneously recorded by different sensors. Raster Data Concepts: Digital Imagery Digital imagery is a specialized type of raster data. A digital image is a two-dimensional array (a matrix or grid) of regularly spaced picture elements (pixels). Pixels are analogous to cells. Typically, digital images do not require a separate table to hold value or attribute information. Digital imagery data (pixel values) is created from optical or other sensors including: Satellite remote sensing Airborne photogrammetry Sonar Digital images can be composed of one or more bands. Each band typically represents a complete matrix of pixel values associated with data collected from one sensor. Multiple bands of an image can be simultaneously recorded to generate a multiband digital image. Oracle Spatial 10g: Advanced
77
Multiband Digital Image: Example
Each band is collected at a different wavelength for later processing and display. Band 3 Ultraviolet 0.4 mm Blue Band 2 0.5 mm Green 0.6 mm Red 0.7 mm Band 1 Multiband Digital Image: Example Multiband digital imagery is collected at various wavelengths and stored for later processing and display. Often, multiband imagery is displayed as an RGB (Red Green Blue) image because that is how computer monitors display information. Oracle Spatial 10g: Advanced
78
Multiband Digital Image: Example
Multiband Digital Image: Example (continued) This is an example of image data with multiple bands. Some bands accentuate different features. Each band here is an image captured at a different frequency range in the electromagnetic spectrum. The fourth image is the composition of the three bands shown together with a colormap. This is an example of a false color image. The colormap specifies how to map the cell values in each band to R (red, for band 4), G (green, for band 3) and B (blue, for band 2). Some bands may accentuate different features. Oracle Spatial 10g: Advanced
79
Cell Data and Bands: Concepts
Cell data is the value associated with cells Each cell has a value in a raster. In an RGB image, three different cells are stored for each row/column location: One cell for the intensity value of red One cell for the intensity value of green One cell for the intensity value of blue In GeoRaster, all cells associated with a 2-D set of rows and columns in a plane is a band. An RGB image has three bands. A multispectral image with four channels has four bands in Oracle Spatial GeoRaster. Grid data with four bands has four bands in Oracle Spatial GeoRaster. Cell Data and Bands: Concepts In Oracle Spatial GeoRaster, band has a specific meaning. A band is a physical dimension in a multidimensional raster data set. It is one dimension in the cell space, where data is stored in terms of rows, columns, and bands. A single GeoRaster object can have multiple bands. Band numbering in Oracle Spatial GeoRaster starts at band 0, and goes up to n–1, where n is the total number of bands in the GeoRaster object. Bands are used when physically addressing GeoRaster data in cell space. Oracle Spatial 10g: Advanced
80
Oracle Spatial 10g: Advanced 1-82
Bands and Layers Layer n Band n–1 Layer 2 Band 1 Layer 1 Band 0 Layer 0 Bands and Layers Layer is a well-defined term when discussing GeoRaster data. Logical layers can be mapped to physical bands in Oracle GeoRaster. Ultimately, bands get stored in Oracle tables. How this is accomplished (with blocking and interleaving) is discussed in one of the following slides. A logical layer includes band information (cell data), along with associated information such as a Value Attribute Table (VAT), colormap table, grayscale table, and so on. The numbering system for logical layers associated with a single bands starts at 1. Physical band numbering starts at 0. Each cell in a band maps to data stored in the Oracle database. Additionally, Layer 0 is a special layer that maps to the entire GeoRaster object. It is associated with global information for the entire GeoRaster object. Information associated with a nonzero layer can be used to override global information stored at layer 0. For example, if a nonzero layer has an associated colormap, its colormap can be used to render its layers cells. If a nonzero layer does not have a colormap table, its default colormap table can be the one stored in Layer 0. Physical Logical Oracle Spatial 10g: Advanced
81
Band and Layer in GeoRaster
Optional associated information Band/ cell data VAT Scaling ColorMap Band and Layer in GeoRaster A layer in Oracle Spatial GeoRaster is a logical abstraction encompassing both the cell data (the band data) for that layer as well as any optional ancillary information associated with that data. One layer is mapped to each band dimension. Each layer is numbered from 1 to n, and each band is numbered from 0 to n–1. The other optional information associated with the band can include a VAT, colormap information, histogram information, and other related data. The mapping from layers to bands is calculated as follows: layerNumber = bandNumber + 1 Layer 0 in GeoRaster has a specific meaning. It is associated with the entire GeoRaster object, so it is not associated with a single band of the GeoRaster data, but instead is associated with the whole GeoRaster object. It is associated with global information for the entire GeoRaster object. Other statistics GreyScale Histogram Bin information Oracle Spatial 10g: Advanced
82
Examples of Additional Information Associated with a Layer
Example (VAT): In a grid, a cell value of 12 represents a population density of 200 per square mile. Example (histogram): There are 721 cells with a value of 12. Example (colormap): Show pixels with a value of 12 using R = 255, G = 128, B = 0. Examples of Additional Information Associated with a Layer Attribute data can be associated with all of the cells in a GeoRaster object. Attribute data is data that is common to all of the cells in a raster. A VAT contains possible values in the GeoRaster object and associates their meanings to their values. An example of this is mapping a number (12) to its meaning (population density of approximately 200 people per square mile). A histogram contains information about how often values appear in the raster. For example, there are 721 cells with a value of 12. A colormap contains information about how to display each value in a raster. For instance, if the value is 12, then display it using a red intensity of 255, a green intensity of 128, and a blue intensity of 0. Oracle Spatial 10g: Advanced
83
Oracle Spatial 10g: Advanced 1-85
Layer in GeoRaster Layer 0 encompasses all layers. Layer 0 Layer n Layer 1 Layer in GeoRaster Layer 0 is a special layer that maps to the entire GeoRaster object. It is associated with global information for the entire GeoRaster object. Information associated with a nonzero layer can be used to override global information stored at layer 0. For example, if a nonzero layer has an associated colormap, its colormap can be used to render its layers cells. If a nonzero layer does not have a colormap table, its default colormap table can be the one stored in Layer 0. Oracle Spatial 10g: Advanced
84
Oracle Spatial 10g: Advanced 1-86
Pyramids Raster images can be represented at differing storage sizes and degrees of resolution. Pyramid levels associated with reduced resolution images help optimize image rendering. A pyramid level 0 indicates the original raster data. Values greater than zero indicate increasingly reduced levels of image resolution. Each higher pyramid level is half the resolution, requiring one-fourth the storage space of the previous, lower level. Pyramids Raster images do not have to be stored or displayed at the full resolution in which the data was gathered. In fact, it is not always practicable to use the full resolution data. Imagine a raster made up of 10 million cells, and the map display canvas limited to 512 512 pixels (or 262,144 pixels). When zoomed out to a region that displays the full extent of the image, many cells would render to the same display canvas pixel. Generalized versions of the original raster called pyramids can be used for rendering less detailed versions of a raster at different zoom levels. Pyramid levels are used to describe the data stored at a lower resolution. Lower resolution data requires less storage space than higher resolution data. A pyramid level of 0 indicates that the data is stored at its original resolution. For each pyramid level higher than 0, each pyramid level is approximately half the resolution and one-fourth the storage requirement of the previous lower level. Oracle Spatial GeoRaster supports several methods for generating pyramid data. Oracle Spatial 10g: Advanced
85
Oracle Spatial 10g: Advanced 1-87
Pyramids Pyramid level 2 Pyramid level Pyramid level 1 Pyramid level 0 (raw data) Pyramids (continued) The above graphic illustrates how pyramids reduce the resolution and the amount of raster data stored. At pyramid level 0, the data is shown in a 16 rows 16 columns matrix at the resolution it was originally stored. At pyramid level 1, the resolution is reduced by half to 8 rows 8 columns (storage required is reduced to one-fourth the original storage requirement). At pyramid level 2, the resolution and storage requirements drop again to 4 rows 4 columns. Oracle Spatial GeoRaster gives users a choice of algorithms to use when pyramids are created, including: Nearest neighbor Bilinear interpolation using four neighboring cells Cubic convolution using sixteen neighboring cells Average4 using four neighboring cells Average16 using sixteen neighboring cells Oracle Spatial 10g: Advanced
86
Oracle Spatial 10g: Advanced 1-88
Blocking A GeoRaster image can be composed of an extremely large number of cells. It may be more efficient in terms of storage and retrieval to break large images into smaller blocks. In GeoRaster, users or applications can determine how data is blocked: Specify rows, columns, and optionally bands 4 4 blocks Blocking A GeoRaster image can be tens of millions of bytes, or more. To facilitate efficient, fast storage and retrieval of large images, the images can be broken into smaller blocks, where subsets of the image are stored separately, each individually addressable by Oracle Spatial GeoRaster. Users or applications can determine how raster data is blocked in the database. In this example, the GeoRaster data in an 8 rows 8 columns matrix is blocked into four 4 rows 4 columns blocks. Oracle Spatial 10g: Advanced
87
Oracle Spatial 10g: Advanced 1-89
Interleaving Interleaving is used when storing multiband images. Oracle GeoRaster supports three methods of interleaving: Band sequential (BSQ) Band interleaved by pixel (BIP) Band interleaved by line (BIL) Each method can be optimal depending on the requirements of the application. Interleaving Interleaving is used when storing multiband images. In Oracle Spatial GeoRaster there are three methods of interleaving. The three methods are band interleaving (Band SeQential or BSQ), band interleaved by pixel (or BIP), and band interleaved by line (or BIL). Application query requirements can help determine which storage method is best. For example, if the application searches only one band of data at a time, then band sequential may be the best storage mechanism. For certain image processing functions (such as fast fourier transforms), images are processed by line; therefore, the best storage method would be band interleaved by line. Similarly, if the application overlays each pixel with pixels from several bands, then band interleaved by pixel may be the optimal storage method. Oracle Spatial 10g: Advanced
88
Oracle Spatial 10g: Advanced 1-90
BSQ Interleaving Column 0 Band 0 Band 1 Band 2 Row 0 Band sequential (BSQ) stores: Multiband Image Interleaving in GeoRaster This example shows band sequential interleaving for a three-band GeoRaster. In band sequential interleaving, data from each band is stored completely before data from another band is stored. Band sequential interleaving is optimal for operations where GeoRaster data is accessed one band at a time. … Oracle Spatial 10g: Advanced
89
Oracle Spatial 10g: Advanced 1-91
BIP Interleaving Column 0 Band 0 Band 1 Band 2 Row 0 Band interleaved by pixel (BIP) stores: Multiband Image Interleaving in GeoRaster (continued) This example shows band interleaved by pixel storage for a three-band GeoRaster. Band interleaved by line stores a cell from one band, then the corresponding cell from the second band, and then the corresponding cell from the third band. This process is repeated one line at a time, until all the lines are processed. Band interleaved by pixel may be optimal for operations that combine pixel values from different bands, for instance: Raster display applications Applications that add cell values across bands … Oracle Spatial 10g: Advanced
90
Oracle Spatial 10g: Advanced 1-92
BIL Interleaving Column 0 Band 0 Band 1 Band 2 Row 0 Band interleaved by line (BIL) stores: Multiband Image Interleaving in GeoRaster (continued) This example shows band interleaved by line storage for a three-band GeoRaster. Using band interleaved by line, a line of cells from one band is stored, then the corresponding line from the next band, and then the corresponding line from the third band. The process is repeated until all the lines are processed. Many image-processing operations operate on a line (or a few lines) of data from different bands. Many image enhancement algorithms use line-by-line image enhancement techniques. For these applications, storing the raster BIL would be optimal. … Oracle Spatial 10g: Advanced
91
Oracle Spatial 10g: Advanced 1-93
Cell Depth GeoRaster data is a matrix of cells with assigned values. Cell depth is the data type of the cell values. Valid Oracle Spatial GeoRaster cell depths are: 1 BIT 2 BIT 4 BIT 8 BIT UNSIGNED 8 BIT SIGNED 16 BIT_UNSIGNED 16 BIT SIGNED 32 BIT UNSIGNED 32 BIT SIGNED 32 BIT REAL 64 BIT REAL Cell Depth GeoRaster data is spatial data created by assigning values to each cell in a matrix that covers an area. The cell values are numeric values. The numeric data types Oracle Spatial GeoRaster supports include: 1BIT, 2BIT, 4BIT, 8BIT_U, 8BIT_S, 16BIT_U, 16BIT_S, 32BIT_U, 32BIT_S, 32BIT_REAL, and 64BIT_REAL. The default value is the cell depth of the source data. GeoRaster data can be stored with smaller cell depth than the source data. This can result in loss of data and a reduction in image quality and precision of the raster data as well as reduced storage requirements. Oracle Spatial 10g: Advanced
92
GeoRaster: Object Types and Storage
Oracle Spatial 10g: Advanced
93
SDO_GEORASTER Object Type
You can create tables with SDO_GEORASTER columns. This is the type used to store, analyze, query, and retrieve GeoRaster data. CREATE TABLE city_data ( city_name VARCHAR2(40), population NUMBER, . . Other columns geor SDO_GEORASTER); SDO_GEORASTER Object Type You can create tables with the SDO_GEORASTER object type. The SDO_GEORASTER type is used to store, analyze, query, and retrieve GeoRaster data. Attributes and imagery can both be queried when you require information from the table. For each row: Boston … Image of Boston New York … Image of New York Oracle Spatial 10g: Advanced
94
GeoRaster Physical Storage
city_name population … geor Boston … Image of Boston New York … Image of New York CITY_DATA table . SDO_GEORASTER object GeoRaster Type Image Extent (SDO_GEOMETRY) Raster data table name Raster ID Metadata (SYS.XMLtype) GeoRaster Physical Storage You create tables that contain GeoRaster data. These tables can contain attribute data just like any other Oracle tables, but in addition they contain an object of type SDO_GEORASTER. Two attributes from the SDO_GEORASTER object, the RASTERDATATABLE and the RASTERID provide the information required to get the raster data from the raster data table. The raster data table is a table of type SDO_RASTER, explained in an upcoming slide called “Raster Data Table.” The SDO_GEORASTER object includes image footprint information, stored in the SDO_GEOMETRY type. A requirement for using a spatial index on this column is that all GeoRaster data stored in a single column of type SDO_GEORASTER should be in the same coordinate system. A blocked raster is stored in a raster data table, one row per block The Raster ID uniquely identifies a raster in a raster data table Oracle Spatial 10g: Advanced
95
The SDO_GEORASTER Object Type
The SDO_GEORASTER object type is included when Oracle Spatial is installed: The SDO_GEORASTER object type has five attributes. The pair (RASTERID, RASTERDATATABLE) uniquely identify a raster object in the database . SQL> desc sdo_georaster Name Type RASTERTYPE NUMBER SPATIALEXTENT MDSYS.SDO_GEOMETRY RASTERDATATABLE VARCHAR2(32) RASTERID NUMBER METADATA SYS.XMLTYPE The SDO_GEORASTER Object Type The SDO_GEORASTER object type is installed when Oracle Spatial is installed. The SDO_GEORASTER object type has five attributes: RASTERTYPE, SPATIALEXTENT, RASTERDATATABLE, RASTERID, and METADATA. These attributes are discussed in the next slides. Oracle Spatial 10g: Advanced
96
The SDO_GEORASTER Object Type
RASTERTYPE: A five-digit number A RASTERTYPE of is raster data that has two dimensions and one band, and is raster data that has two spatial dimensions and more than one band. SPATIALEXTENT defines the spatial extent or footprint associated with the raster data. The SPATIALEXTENT is of type SDO_GEOMETRY. RASTERDATATABLE identifies the name of the raster data table. The raster data table contains the GeoRaster data, and has one row for each stored raster block. RASTERID is used with RASTERDATATABLE to uniquely identify the data associated with a GeoRaster object. METADATA is the XML metadata defined by Oracle Spatial GeoRaster. The SDO_GEORASTER Object Type (continued) The RASTERTYPE field in the SDO_GEORASTER object type is a five-digit number that contains information about the raster data stored in that row. A RASTERTYPE of is used for raster data that has two spatial dimensions and a single band, and a RASTERTYPE of is used for raster data that has two spatial dimensions and one or more bands. The SPATIALEXTENT defines the footprint of the raster data in the model coordinate system using the Oracle Spatial geometry type, SDO_GEOMETRY. If the raster data is georeferenced, the spatial extent includes the SDO_SRID of the coordinate system. If the data is not georeferenced, the coordinate system information (SDO_SRID) is set to NULL. The RASTERDATATABLE is the name of the raster data table that contains the actual blocks of GeoRaster data. RASTERID and RASTERDATATABLE uniquely identify all the data associated with a GeoRaster object. METADATA is the XML metadata associated with the GeoRaster data stored in each row. Oracle Spatial 10g: Advanced
97
GeoRaster Physical Storage
city_name population … geor Boston … Image of Boston New York … Image of New York CITY_DATA table . SDO_GEORASTER object GeoRaster Type Image Extent (SDO_GEOMETRY) Raster data table name Raster ID Metadata (SYS.XMLtype) GeoRaster Physical Storage Users create tables that contain GeoRaster data. The tables can contain attribute data just like any other Oracle tables, but in addition they contain an object of type SDO_GEORASTER. Two attributes from the SDO_GEORASTER object, the RASTERDATATABLE and the RASTERID provide the information required to get the raster data from the raster data table. The raster data table is a table of type SDO_RASTER, which is explained in the following slide. Raster data is stored in the raster data table. As discussed earlier, it may be more efficient to break large rasters into smaller, more manageable pieces known as blocks. The raster data table stores all the blocks of a raster, one block per row. Users can decide how many rasters to store in a raster data table. Two possible extremes are: Store all of your blocked rasters in a single raster data table Store each blocked raster in its own raster data table This flexible and scalable storage model allows you to decide how many rasters to store in each raster data table. Raster data table of SDO_RASTER type (one row per raster block) One block (BLOB) RasterID More information (discussed later) Oracle Spatial 10g: Advanced
98
Oracle Spatial 10g: Advanced 1-100
Raster Data Table The raster data table is an object table containing GeoRaster data. It is an object table of type SDO_RASTER. Raster data table must be created by the user. It must be uniquely named in the Oracle instance. It must have the same owner as table with SDO_GEORASTER. create table my_rdt of sdo_raster (PRIMARY KEY (rasterId, pyramidLevel, bandBlockNumber, rowBlockNumber, columnBlockNumber)) tablespace rdt_tbs nologging storage (initial 1M next 5M pctincrease 0) lob(rasterblock) store as mylobseg (tablespace lob_rdt_tbs chunk 8192 cache reads nologging pctversion 0 storage (initial 5M next 10M pctincrease 0)); Raster Data Table A raster data table is a table of type SDO_RASTER. Users create their own SDO_RASTER object tables. The owner of the table containing the SDO_GEORASTER column and the owner of the raster data table(s) associated with that SDO_GEORASTER column must be the same. Every raster data table must be uniquely named within an Oracle instance. Two separate schemas cannot have raster data tables with the same name. Oracle Spatial 10g: Advanced
99
SDO_RASTER Object Type
Image data for this block (BLOB) MBR for this block (SDO_GEOMETRY) rowBlockNumber, PyramidLevel, … RasterID The SDO_RASTER object type is included when Oracle Spatial is installed. SQL> desc sdo_raster Name Type RASTERID NUMBER PYRAMIDLEVEL NUMBER BANDBLOCKNUMBER NUMBER ROWBLOCKNUMBER NUMBER COLUMNBLOCKNUMBER NUMBER BLOCKMBR MDSYS.SDO_GEOMETRY RASTERBLOCK BLOB SDO_RASTER Object Type The SDO_RASTER object type is installed when Oracle Spatial is installed. The SDO_RASTER object type has seven attributes: RASTERID, PYRAMIDLEVEL, BANDBLOCKNUMBER, ROWBLOCKNUMBER, COLUMNBLOCKNUMBER, BLOCKMBR, and RASTERBLOCK. These are discussed in the next slides. Oracle Spatial 10g: Advanced
100
SDO_RASTER Object Type
RASTERID associates one or more blocks of raster data in the raster data table with a specific row in a table containing the SDO_GEORASTER object type. Each block in the raster data table is stored in a separate row. PYRAMIDLEVEL is the pyramid level of the raster block. 0 indicates the data is at its original resolution. Each increasing integer level indicates that the resolution is reduced by a factor of two, and storage by a factor of four. SDO_RASTER Object Type (continued) The RASTERID field in the SDO_RASTER object type is used to associate one or more rows of raster data in the raster data table to a particular SDO_GEORASTER object stored in a user table. There is one row in the raster data table associated with each block of raster data. PYRAMIDLEVEL is used to specify the pyramid level of the raster data. A pyramid level of 0 means the raster data is at the original resolution that it was stored at; a pyramid level of 1 means the data has half the resolution and approximately one-fourth the number of cells as there were at pyramid level 0; a pyramid level of 2 means half the resolution and approximately one-fourth the number of cells as there were at pyramid level 1, and so on. Oracle Spatial 10g: Advanced
101
SDO_RASTER Object Type
BANDBLOCKNUMBER, ROWBLOCKNUMBER, and COLUMNBLOCKNUMBER are all defined in terms of the BLOCKSIZE the you choose for the storage parameters of the raster data. BLOCKMBR is the Minimum Bounding Rectangle around the data stored in the block. SDO_GEOMETRY type Currently not used; will be used for irregular blocking RASTERBLOCK contains the raster cell data for the given block. BLOB type (Binary Large OBject) SDO_RASTER Object Type (continued) BANDBLOCKNUMBER, ROWBLOCKNUMBER, and COLUMNBLOCKNUMBER are all defined in terms of the BLOCKSIZE the user or application chooses as one of the storage parameters of the raster data. These will be discussed in a future slide. The BLOCKMBR field in the SDO_RASTER object type is the Minimum Bounding Rectangle (MBR) that encompasses all of the data stored in the raster block. The minimum bounding rectangle is stored in the SDO_GEOMETRY type, and is stored in the cell coordinate space, so its SDO_SRID is set to NULL. The stored coordinates are the minimum row and column for this block (the lower-left cell location), and the maximum row and column for this block (the upper-right cell location). The RASTERBLOCK attribute contains the raster data associated with this block of GeoRaster data. The data is stored in the Oracle BLOB (Binary Large OBject) data type, which can accommodate all of the data types Oracle Spatial GeoRaster supports. Oracle Spatial 10g: Advanced
102
Creating Triggers for GeoRaster Data
One trigger for each column of type SDO_GEORASTER: Keeps the SDO_GEORASTER column and the raster data table synchronized. TABLENAME:The table name that contains the SDO_GEORASTER column. COLUMNNAME:The SDO_GEORASTER column name. SDO_GEOR_UTL.CREATEDMLTRIGGER ( TABLENAME, COLUMNNAME) begin SDO_GEOR_UTL.CREATEDMLTRIGGER ( 'CITY_DATA', 'GEOR'); end; / Creating Triggers for GeoRaster Data A data manipulation language (DML) trigger must be created for each column of type SDO_GEORASTER. Oracle Spatial 10g: Advanced
103
Oracle Spatial 10g: Advanced 1-105
Break Point Oracle Spatial 10g: Advanced
104
GeoRaster: Loading GeoRaster Data
Oracle Spatial 10g: Advanced
105
Oracle Spatial 10g: Advanced 1-107
Java GeoRaster Loader Oracle Spatial provides a Java GeoRaster loader to load some simple types of raster imagery into the database. To use the loader: A table with an SDO_GEORASTER column must exist. The raster data table must exist. The SDO_GEOR_UTL.CREATEDMLTRIGGER procedure must be called. The SDO_GEORASTER column must be initialized. Java GeoRaster Loader Oracle Spatial provides a simple Java loader to load a few types of raster data into the database. Oracle Corporation relies on partners for a comprehensive set of loaders. To load raster data into the database using Oracle’s Java GeoRaster loader, the following operations must be completed: A table with an SDO_GEORASTER column must exist The raster data table must exist The SDO_GEOR_UTL.CREATEDMLTRIGGER procedure must have been called The SDO_GEORASTER column must have been initialized Oracle Spatial 10g: Advanced
106
Preparing to Load a GeoRaster Image
-- Create the georaster table drop table city_data; create table city_data (city_name varchar2(50), population number, georaster sdo_georaster); -- Create the DML trigger on the GEORASTER -- column of the CITY_DATA table call SDO_GEOR_UTL.createDMLTrigger('CITY_DATA', 'GEORASTER'); Preparing to Load a GeoRaster Image This example starts by creating the table with an SDO_GEORASTER column. Next, the DML trigger is created using the procedure SDO_GEOR_UTL.createDMLTrigger. Oracle Spatial 10g: Advanced
107
Preparing to Load a GeoRaster Image
-- Drop/create a uniquely named raster data table drop table city_data_rdt_01; create table city_data_rdt_01 of sdo_raster (primary key ( rasterId, pyramidLevel, bandBlockNumber, rowBlockNumber, columnBlockNumber)) lob(rasterblock) store as (nocache nologging); -- Initialize a GeoRaster image with RASTERID=1 INSERT INTO city_data values ('Boston', , sdo_geor.init('city_data_rdt_01', 1)); COMMIT; Preparing to Load a GeoRaster Image (continued) The setup to load a GeoRaster image is completed by creating the raster data table and initializing the SDO_GEORASTER. Oracle Spatial 10g: Advanced
108
The Java GeoRaster Loader
The Java GeoRaster loader can now be called to load raster data into the database Each command is on a single line Set clpath=%ORACLE_HOME%\ord\jlib\jai_codec.jar; %ORACLE_HOME%\ord\jlib\jai_core.jar; %ORACLE_HOME%\jdbc\lib\classes12.jar; %ORACLE_HOME%\rdbms\jlib\xdb.jar; %ORACLE_HOME%\lib\xmlparserv2.jar;%ORACLE_HOME%\LIB\xmlcomp.jar; %ORACLE_HOME%\LIB\xschema.jar;%ORACLE_HOME%\jlib\jewt4.jar; %ORACLE_HOME%\md\lib\sdoapi.jar;%ORACLE_HOME%\md\lib\sdoutl.jar; %ORACLE_HOME%\md\demo\georaster\java\georaster_tools.jar; %ORACLE_HOME%\jdbc\lib\nls_charset12.jar java -Xmx128M -cp %clpath% GeoRasterLoader localhost orcl 1521 student student thin 32 T city_data georaster "blocking=true blocksize=(512,512,3)" "boston.tif,1,city_data_rdt_01,boston.tfw" The Java GeoRaster Loader This example sets up the classpath for the Java-based GeoRaster Loader, then runs the loader to add the image to the database. The example shown is for Windows. Interesting parameters include: The –Xmx128M sets up 128 megabytes of memory for the Java-based tool Connection information (localhost, orcl, 1521, student, student, thin, 32, T are all connection parameters) Load the georaster column of the CITY_DATA table Blocking is 512 x 512 x 3 The raster image is boston.tif, and it is loaded into the georaster column with rasterid=1 and raster data table id city_data_rdt_1. The raster image has an associated worldfile, boston.tfw. Note: Often, worldfiles have “.” to represent the decimal point. If your character set and locale is not set to US English, then the Java command can incorporate setting to allow it to read US-based character sets by altering the java command: java -Duser.language=EN -Duser.region=US … Oracle Spatial 10g: Advanced
109
Oracle Spatial 10g: Advanced 1-111
GeoRaster: Model SRID Oracle Spatial 10g: Advanced
110
SDO_GEOR.setModelSRID
<georaster> GeoRaster object whose model SRID is set This is an in/out parameter <SRID> SRID associated with georeference information SDO_GEOR.setModelSRID (<georaster>, <SRID>) SDO_GEOR.setModelSRID If a raster is georeferenced, it can also be associated with a coordinate system. SDO_GEOR.setModelSRID associates a coordinate system with a georeferenced raster. The model SRID gets stored in the METADATA attribute of the SDO_GEORASTER object in XML format. Oracle Spatial 10g: Advanced
111
SDO_GEOR.setModelSRID: Example
-- -- Associate rasters with SRID 40978, -- California 0403, Zone III (1983, meters) BEGIN FOR r IN (SELECT rowid, georaster FROM sf_rasters FOR UPDATE) LOOP SDO_GEOR.setModelSRID(r.georaster, 40978); UPDATE sf_rasters SET georaster = r.georaster WHERE rowid = r.rowid; END LOOP; END; / SDO_GEOR.setModelSRID: Example A sample anonymous PL/SQL block sets the model SRID for each raster stored in the GEORASTER column of the SF_RASTERS table. You are recommended to select raster objects for update (FOR UPDATE), whenever portions are updated. This ensures no other user can modify the raster during the update. Oracle Spatial 10g: Advanced
112
GeoRaster: Spatial Extent
Oracle Spatial 10g: Advanced
113
SDO_GEOR.generateSpatialExtent
(<georaster>) RETURN SDO_GEOMETRY The SDO_GEORASTER object has an attribute called spatialExtent of type SDO_GEOMETRY. spatialExtent is the raster’s MBR. SDO_GEOR.generateSpatialExtent can be used to populate the spatialExtent attribute of an SDO_GEORASTER object. If the raster’s model SRID is set, the spatial extent returned also contains the model SRID. The spatialExtent attribute can be: Indexed with an ordinary SDO_GEOMETRY R-tree index Searched to locate rasters in a specified region SDO_GEOR.generateSpatialExtent SDO_GEOR.generateSpatialExtent can be used to populate the spatialExtent attribute of an SDO_GEORASTER object. If the SDO_GEORASTER object has an associated model SRID, SDO_GEOR.generateSpatialExtent returns an MBR in the model coordinate system. If the SDO_GEORASTER object does not have an associated model SRID, SDO_GEOR.generateSpatialExtent returns an MBR in cell space (or pixel space). The SDO_GEORASTER SPATIALEXTENT attribute is of type SDO_GEOMETRY. It can be indexed and searched. This is useful for locating rasters in a user-specified region. Oracle Spatial 10g: Advanced
114
SDO_GEOR.generateSpatialExtent: Example
-- Generate the spatial extent of rasters in an SDO_GEORASTER column BEGIN FOR r IN (SELECT rowid, georaster FROM sf_rasters FOR UPDATE) LOOP r.georaster.spatialExtent := SDO_GEOR.generateSpatialExtent(r.georaster); UPDATE sf_rasters SET georaster = r.georaster WHERE rowid = r.rowid; END LOOP; END; / SDO_GEOR.generateSpatialExtent: Example This is a sample of the anonymous PL/SQL block that generates the spatial extent for each raster stored in the georaster column of the SF_RASTERS table. You are recommended to select raster objects for update (FOR UPDATE) whenever portions are updated. This ensures that no other user can modify the raster during the update. Oracle Spatial 10g: Advanced
115
Index the Spatial Extent
DELETE FROM user_sdo_geom_metadata WHERE table_name = 'SF_RASTERS' AND column_name = 'GEORASTER.SPATIALEXTENT'; INSERT INTO user_sdo_geom_metadata VALUES ('SF_RASTERS', 'GEORASTER.SPATIALEXTENT', SDO_DIM_ARRAY(SDO_DIM_ELEMENT('X', , , .05), SDO_DIM_ELEMENT('Y', , , .05)), 40978); COMMIT; DROP INDEX sf_rasters_sidx; CREATE INDEX sf_rasters_sidx ON sf_rasters (georaster.spatialExtent) INDEXTYPE IS mdsys.spatial_index; SDO_GEOR.generateSpatialExtent: Example (continued) Here you see created an ordinary R-tree spatial index on the SPATIALEXTENT attribute of the SDO_GEORASTER object. Note that the embedded SDO_GEOMETRY attribute of the column is being indexed. Oracle Spatial 10g: Advanced
116
Search the Spatial Extent
-- Find all the rasters in a rectangular region -- SELECT georid FROM sf_rasters a WHERE SDO_ANYINTERACT ( a.georaster.spatialExtent, SDO_GEOMETRY (2003,40978,NULL, SDO_ELEM_INFO_ARRAY (1,1003,3), SDO_ORDINATE_ARRAY ( ,645135, , ))) = 'TRUE'; GEORID 1 2 4 5 SDO_GEOR.generateSpatialExtent: Example (continued) The spatial index on the spatialExtent attribute enables you to perform spatial searches against raster MBRs of an SDO_GEORASTER column in a table. Oracle Spatial 10g: Advanced
117
GeoRaster: Georeferencing Concepts
Oracle Spatial 10g: Advanced
118
Oracle Spatial 10g: Advanced 1-120
Georeferencing Georeferencing establishes the relationship between cell coordinates of GeoRaster data and real-world ground coordinates or other local coordinates. Georectification is the process of assigning ground control points (GCPs) to digital images and processing the image to better map it to the surface of the Earth. In Oracle Spatial 10g Release 1, GeoRaster supports affine transformations that georeference two-dimensional raster data. The implementation in GeoRaster is known as the GeoRaster Spatial Reference System. Georeferencing Georeferencing allows raster data to be mapped from its row-and-column grid structure to a location on the surface of the Earth, or some location based on a local coordinate system. Georeferencing enables each cell in the image to be mapped to its location on the surface of the Earth or, given a location on the surface of the Earth, the cell that represents that location can be found. Georectification is the process of assigning ground control points (GCPs) to digital images to improve their mapping to the surface of the Earth. In Oracle Spatial GeoRaster, georeferencing uses the GeoRaster Spatial Reference System. This system uses affine transformations to enable two-dimensional raster cells to be mapped to specific locations and the appropriate raster cell (or cells) to be found given a specific Earth coordinate. Oracle Spatial 10g: Advanced
119
Georeferencing Raster Data Geographic Entities Cell Coordinate System
Model (ground) space Model (ground) coordinate system column row National Park GeoRaster Spatial Reference System (SRS) Restaurant Georeferencing (continued) In the objects on the left, the medium-size rectangle represents a raster image, and within it are: A rectangular area showing a national park A point identifying the location of a specific restaurant Each pixel in the image can be identified by its coordinates in a cell coordinate system (the coordinate system associated with the raster image). In the objects on the right, the large rectangle represents the geographical area (in the model, or ground, space). Within it are spatial geometries for the national park and the specific restaurant. Each entire geographical area and the geometries within it can be identified using coordinates in its model (or, ground) coordinate system, such as WGS 84 for longitude/latitude data. To go from the cell coordinate system to the ground coordinate system, GeoRaster currently supports affine transformation that georeferences two-dimensional images. Y X Oracle Spatial 10g: Advanced
120
Register Georeference Information
The metadata attribute of the SDO_GEORASTER object includes the SpatialReferenceInfo XML element. The SpatialReferenceInfo XML element stores georeference information related to a raster. There are two ways to register georeference information: Include an ESRI WORLDFILE (.tfw file) when using Oracle’s (Java or PL/SQL) GeoRaster Loaders. If you do not have a .tfw file, call SDO_GEOR.GEOREFERENCE after you load a raster. Register Georeference Information Oracle Spatial GeoRaster does not perform the georeferencing process. You can, however, register georeference information, for example, coefficients for a georeferencing equation, with a raster. This information gets stored in XML in the METADATA attribute of the SDO_GEORASTER object. Note: ESRI is the Environmental Systems Research Institute. Oracle Spatial 10g: Advanced
121
SDO_GEOR.GEOREFERENCE
( <georaster>, <srid>, <modelCoordinateLocation>, <xCoefficients>, <yCoefficients>) <georaster> GeoRaster object whose metadata attribute is updated This is an IN/OUT parameter. <SRID> Model SRID to associate with the raster <modelCoordinateLocation> 0 corresponds to a raster’s center cell 1 corresponds to a raster’s upper-left cell <xCoefficients>, <yCoefficients> Coefficients of the georeference equation SDO_GEOR.GEOREFERENCE SDO_GEOR.GEOREFERENCE does not georeference a raster. This function assumes that the raster has already been georeferenced. SDO_GEOR.GEOREFERENCE registers georeference information in the SDO_GEORASTER metadata attribute. If you call SDO_GEOR.GEOREFERENCE, you do not have to call SDO_GEOR.setModelSRID. For a detailed description of the supported georeference equations, please see Oracle Spatial GeoRaster 10g. Oracle Spatial 10g: Advanced
122
SDO_GEOR.GEOREFERENCE: Example
82233 is the SRID - UTM Zone 14, Northern Hemisphere modelCoordinateLocation is 1, upper-left cell of raster xCoefficients First value in the SDO_NUMBER_ARRAY: X resolution, 777 meters between pixels along the X axis -- Third parameter is 1. Information is relative to the upper left cell SDO_GEOR.GEOREFERENCE (gr, 82233, 1, SDO_NUMBER_ARRAY (777, 0, ), SDO_NUMBER_ARRAY ( 0, -822, )); SDO_GEOR.GEOREFERENCE: Example If a georeferenced raster was loaded with Oracle’s raster loader, without a world file (.tfw file), then register georeference information with the SDO_GEOR.GEOREFERENCE procedure. If a world file was specified at load time, there is no need to call SDO_GEOR.GEOREFERENCE, just call SDO_GEOR.setModelSRID. The zero (0) values above in the SDO_GEOR.GEOREFERENCE call are related to rotation, and can be used if the image is not aligned along the X and Y axes. SELECT sdo_geor.getSpatialDimSizes(georaster) spatialDimSizes FROM mexico_rasters WHERE georid = 1; Oracle Spatial 10g: Advanced
123
SDO_GEOR.GEOREFERENCE: Example
xCoefficients (continued) Third value in the SDO_NUMBER_ARRAY: Upper-left pixel X ordinate value in model space is – yCoefficients Second value in the SDO_NUMBER_ARRAY: Y resolution, 822 meters between pixels along the Y axis Y origin is flipped between cell and model space, so –822 Upper-left pixel Y ordinate value in model space is SDO_GEOR.GEOREFERENCE: Example (continued) Oracle Application Server MapViewer is the first MapViewer release with GeoRaster Support. To render GeoRaster data, it must: Be georeferenced (associated with a Model SRID) Have a generated spatialExtent spatialExtent must be spatially indexed MapViewer automatically selects the optimal pyramid level when rendering GeoRaster themes. MapViewer demos that support GeoRaster themes include: georaster.jsp mapclient.jsp MapViewer welcome page - Sample Map Request Oracle Spatial 10g: Advanced
124
SDO_GEOR.GEOREFERENCE: Example
-- If raster was loaded without a worldfile, -- then set the georeference information. -- Otherwise, can just call sdo_geor.setModelSRID DECLARE gr SDO_GEORASTER; BEGIN SELECT georaster INTO gr FROM mexico_rasters WHERE georid = 1 FOR UPDATE; -- Third parameter is 1. Information is relative to upper left cell SDO_GEOR.GEOREFERENCE (gr, 82233, 1, SDO_NUMBER_ARRAY (777, 0, ), SDO_NUMBER_ARRAY ( 0, -822, )); SDO_GEOR.SetSpatialResolutions (gr,SDO_NUMBER_ARRAY (777,822)); UPDATE mexico_rasters SET georaster = gr WHERE georid = 1; END; / SDO_GEOR.GEOREFERENCE: Example (continued) This is a sample anonymous PL/SQL block that makes the SDO_GEOR.GEOREFERENCE call discussed in the previous slide. The raster was loaded without a world file, so SDO_GEOR.GEOREFERENCE registers georeference information with the raster. You are recommended to select raster objects for update (FOR UPDATE) whenever portions are updated. This ensures that no other user can modify the raster during the update. Oracle Spatial 10g: Advanced
125
GeoRaster: Features and Functionality
Oracle Spatial 10g: Advanced
126
GeoRaster: Features and Functionality
Insert, update, index, and retrieve raster data Insert, update, and retrieve GeoRaster metadata Analysis functionality: Generate pyramids Copy raster data Change format: Interleaving, blocking Subset: Clip GeoRaster data by band or layer Scaling: Enlarge or reduce Generate the spatial extent of an image Tile adjacent images to build a mosaic of the data GeoRaster data that has been georectified and georeferenced is supported GeoRaster: Features and Functionality The first release of GeoRaster is in Oracle Spatial 10g. You use it to insert, update, index, and retrieve raster and image data to and from Oracle Database 10g. Metadata is stored in XML format. Procedures are supplied to insert, update, and delete metadata elements. Image-specific metadata is typically loaded with the image. Use GeoRaster to perform the following functions: Generate pyramids (which reduces the resolution of the raster data) Copy raster data Change the format of the raster data (both interleaving method and the blocking size) Subset raster data with crop operations which can be done by layer or by band, or subset specific bands or layers Generate the spatial extent of an image Scale a GeoRaster image Tile together adjacent images to build a mosaic of the data If the data has been georectified and georeferenced, then Oracle Spatial GeoRaster can find the Earth location of each cell in an image. Also, given a location, it can find the cell in an image associated with that location. Oracle Spatial 10g: Advanced
127
GeoRaster: Features and Functionality
Oracle Spatial relies on partners to import or export data in many data formats to or from the SDO_GEORASTER data type. Oracle Spatial’s minimum support for loaders and exporters include: TIFF/GeoTIFF ESRI World File JPEG GIF BMP PNG MapViewer provides simple support for the visualization of GeoRaster data. GeoRaster: Features and Functionality (continued) Oracle Spatial GeoRaster relies on partners to convert from or to many popular data formats. Many of these vendors understand a large number of data formats, and have to learn only the GeoRaster storage format to supply utilities to convert from or to all of their supported formats. GeoRaster includes support to load data from or export data to the following formats: TIFF/GeoTIFF (6.0, excluding georeferencing) ESRI World File JPG GIF BMP PNG Additionally, Oracle Application Server MapViewer provides simple visualization support for GeoRaster data. Oracle Spatial 10g: Advanced
128
Oracle Spatial 10g: Advanced 1-130
GeoRaster: Features and Functionality Oracle Spatial 10g Release 2 Enhancements Native JPEG and DEFLATE compression Extensible plug-in compression Through third-party tools Multischema support Each raster data table name must be unique in an Oracle instance Loader, Exporter, and Viewer enhancements GeoRaster: Features and Functionality Oracle Spatial 10g Release 2 Enhancements Oracle Spatial GeoRaster supports native JPEG and DEFLATE compression for georaster objects. Additionally, Oracle Spatial GeoRaster will support some wavelet-based compression by third party applications based on a plug-in model. Multischema support is supported in Oracle Spatial 10g Release 2 as well as many enhancements to the GeoRaster Viewer, the GeoRaster Loader, and the GeoRaster Exporter. Oracle Spatial 10g: Advanced
129
MapViewer Support for GeoRaster
Oracle Spatial 10g: Advanced
130
MapViewer Support for GeoRaster
Oracle Application Server MapViewer is the first MapViewer release with GeoRaster Support. For MapViewer, an SDO_GEORASTER object must: – Be georeferenced (associated with a model SRID) – Have a generated and spatially indexed spatialExtent MapViewer automatically selects optimal pyramid level when rendering GeoRaster themes. MapViewer demonstrations that support GeoRaster themes: georaster.jsp mapclient.jsp MapViewer welcome page: Sample Map Request Oracle Spatial 10g: Advanced
131
Oracle Spatial 10g: Advanced 1-133
MapViewer’s GeoRaster Support Uses Java Advanced Imaging (JAI) Libraries The following files must be in the MapViewer library classpath: jai_core.jar jai_codec.jar JAI files are included in: An Oracle Application Server install An Oracle Database install Copy the jai_core.jar and jai_codec.jar files into the following directory: J2EE_HOME\applications\mapviewer\web\WEB-INF\lib MapViewer’s GeoRaster Support Uses Java Advanced Imaging (JAI) Libraries MapViewer used Java Advanced Imaging (JAI) libraries to render raster data. The following files must be in the MapViewer library classpath: jai_core.jar jai_codec.jar Copy the files from either an Oracle Application Server installation, or an Oracle Database installation into the following directory: J2EE_HOME\applications\mapviewer\web\WEB-INF\lib This is also documented in the “Installing and Deploying MapViewer” section of the Oracle Application Server MapViewer User’s Guide. Oracle Spatial 10g: Advanced
132
MapViewer Welcome Page: georaster.jsp Demo
Click the Demos hyperlink: MapViewer Welcome Page: georaster.jsp Demo The georaster.jsp demo can be accessed from the MapViewer Welcome page located at Click the Demos hyperlink on the Welcome page. Then click the new MapViewer demos hyperlink, as demonstrated in the following slide. Oracle Spatial 10g: Advanced
133
MapViewer Welcome Page: georaster.jsp Demo
Click the hyperlink for new MapViewer demos: MapViewer Welcome Page: georaster.jsp Demo (continued) The MapViewer Welcome page includes hyperlinks to some very useful JSP demos. Click the hyperlink for new MapViewer demos to get to georaster.jsp. Oracle Spatial 10g: Advanced
134
georaster.jsp Demo Hyperlink
Click the hyperlink for georaster.jsp demo: Oracle Spatial 10g: Advanced
135
georaster.jsp Request Mode = RasterID
Specify which RasterID to render: georaster.jsp: Request Mode = RasterID When Request Mode = RasterID, specify a single RasterID to render. You can also specify Pyramid Level, and Bands. It is not necessary, however, to specify Raster Table (this is the raster data table). georaster.jsp derives the raster data table from the RasterDataTable attribute in the GeoRaster object. The Query Condition field is used when Request Mode = Query, discussed in the next slide. Oracle Spatial 10g: Advanced
136
georaster.jsp Request Mode = Query
Specify any query condition for the WHERE clause: georaster.jsp - Request Mode = Query When Request Mode = Query, specify any condition to attach to the WHERE clause. In this example, the query condition is: georid in (1,5) You can also specify Pyramid Level and Bands. It is not necessary to specify Raster Table (this is the raster data table). The georaster.jsp derives the raster data table from the RasterDataTable attribute in the GeoRaster object. The RasterId field is used when Request Mode = RasterID, discussed in the previous slide. Request/Response/Msg displays the map request submitted by the georaster.jsp. georaster.jsp submits a jdbc_georaster_query element (shown n the next slide). Oracle Spatial 10g: Advanced
137
Dynamic jdbc_georaster_query Element
Sample map request submitted by georaster.jsp: xml_request=<?xml version="1.0" standalone="yes" ?> <map_request title="" datasource="scott" width="400“ height="360" format="PNG_URL" > <center size="2700.0"> <geoFeature> <geometricProperty typeName="center"> <Point> <coordinates> , </coordinates> </Point> </geometricProperty> </geoFeature> </center> <themes> <theme name="geor_theme" > <jdbc_georaster_query jdbc_srid="40978" georaster_table="sf_rasters" georaster_column="georaster" asis="false"> select georaster from sf_rasters where georid in (1,5) </jdbc_georaster_query> </theme> </themes> </map_request> Dynamic jdbc_georaster_query Element The georaster.jsp map request contains a dynamic jdbc_georaster_query element. The map request in this slide was submitted by the georaster.jsp example in the previous slide. Oracle Spatial 10g: Advanced
138
GeoRaster Predefined Themes
DELETE FROM user_sdo_themes WHERE name = 'SF_RASTERS'; INSERT INTO user_sdo_themes (NAME, BASE_TABLE, GEOMETRY_COLUMN, STYLING_RULES) VALUES ('SF_RASTERS', 'SF_RASTERS', 'GEORASTER', '<?xml version="1.0" standalone="yes"?> <styling_rules theme_type="georaster"> </styling_rules>'); COMMIT; There are other GeoRaster XML styling_rules attributes, for example, raster_bands. You can also define dynamic jdbc_georaster_query themes. GeoRaster Predefined Themes In the previous slides, the dynamic jdbc_georaster_query map request elements were discussed. This slide demonstrates how to create a GeoRaster predefined theme. The production Map Definition Tool has a mechanism to create a predefined GeoRaster theme. The current Beta version of the Map Definition tool does not have a way to create a predefined GeoRaster theme. For now, creating predefined GeoRaster themes can be accomplished through SQL, as demonstrated in this slide. GeoRaster predefined themes can also contain other styling rule attributes, for example, raster_bands. Raster_bands enables you to select a specific set of bands to render. In addition to predefined GeoRaster themes, dynamic jdbc_georaster_query themes can be submitted in a map request. For more information on additional styling_rule attributes for predefined GeoRaster themes, or how to create dynamic jdbc_georaster_query themes, see the Oracle Application Server MapViewer User’s Guide. Oracle Spatial 10g: Advanced
139
mapclient.jsp Renders Predefined GeoRaster Themes
Vector theme rendered on top of a GeoRaster Theme: mapclient.jsp Renders Predefined GeoRaster Themes The mapclient.jsp demo renders predefined GeoRaster themes. MapViewer can also render vector themes on top of GeoRaster themes. This slide renders San Francisco streets on top of a San Francisco raster. Oracle Spatial 10g: Advanced
140
Oracle Spatial 10g: Advanced 1-142
Summary In this lesson, you should have learned: What raster data is Oracle Spatial GeoRaster concepts How Oracle Spatial GeoRaster stores data How to load GeoRaster data How to view GeoRaster data using MapViewer Oracle Spatial 10g: Advanced
141
Oracle Spatial Geocoding
142
Oracle Spatial 10g: Advanced 1-144
Objectives After completing this lesson you should be able to do the following: Explain geocoding concepts Describe the Oracle Spatial Geocoding architecture Describe Geocoding Metadata concepts Detail Geocoding Reference Data concepts Discuss Geocoding Schema Objects Use geocoding functions Objectives This section introduces you to the concepts associated with Oracle Spatial Geocoding. Oracle Spatial 10g: Advanced
143
Oracle Spatial 10g: Advanced 1-145
What Is Geocoding? Geocoding takes a textual address as input and returns a longitude/latitude coordinate associated with the address. Geocoding can have various levels of precision, for example: Number and street Street Postal code Town What Is Geocoding? Geocoding is the process of taking textual information that represents an address and returning the coordinates (usually the longitude and latitude) and potentially other information associated with that address. Often, geocoded data has various levels of precision—from full and complete address matching (more accurate) to matching just at the center of the postal code or town boundary (more general). Oracle Spatial 10g: Advanced
144
Oracle Spatial 10g: Advanced 1-146
What Is Geocoding? Geocoding is used in many application areas, for example: Business finders Routing and directions Mapping Employee What Is Geocoding? (continued) Geocoding is used in many application areas including business and location finders, routing applications, and mapping. Oracle Spatial 10g: Advanced
145
Oracle Spatial 10g Geocoding
Oracle Spatial 10g provides built-in geocoding functions. Geocoding algorithms run in the server. Users can purchase data from Oracle Partners, or they can create data in a standard format to use the Spatial geocoding functions. Sample data is provided at Oracle partner sites, such as NAVTEQ. Links are provided from the Spatial OTN Web site: Oracle Spatial 10g Geocoding Oracle Spatial 10g has built-in geocoding functions to help users geocode their address information. Geocoding algorithms run in the server. To use the geocoding functions, users can get data from an Oracle Partner (a data provider) or create their own, storing the data in the storage format used by the geocoding functions. Sample data is available from Oracle Geocoding Partner sites. Pointers to sample data are posted at: Oracle Spatial 10g: Advanced
146
Oracle Spatial 10g Geocoder Architecture
Oracle Geocoder: Metadata Reference Data functionality: Address parsing Address correction Searching/cleaning Computation of geographic coordinates Input address Address formats, Address parsing parser profiles Reference data Searching and cleansing for geocoding Geocoder Street and place names Coordinate generation Location and other information Coordinates + Corrected address Oracle Spatial 10g Geocoder Architecture The Oracle Spatial Geocoder takes an address as input by using SQL geocoding functions. All metadata and reference data is stored in the database. Using the Geocoder functionality, the address is parsed, reference data is searched, and coordinates and other information are returned to the user. Reference data can be purchased from Oracle Partners such as NAVTEQ, or users can create their own reference data by using the schema published by the Oracle database. Reference data: Purchase from Partners such as NAVTEQ, or create on your own Oracle Spatial 10g: Advanced
147
Oracle Spatial 10g: Advanced 1-149
Geocoding Metadata The three tables that contain geocoding metadata are: GC_COUNTRY_PROFILE Information about a country: Languages Abbreviations used Number of administrative boundaries Suffix of reference data tables for the country GC_PARSER_PROFILES Defines keywords and common abbreviations “St” is a synonym for “Street.” Can also store common spelling mistakes GC_PARSER_PROFILEAFS Describes the address structure in each country XML notation Geocoding Metadata There are three metadata tables used by Oracle Spatial Geocoder: GC_COUNTRY_PROFILE: This table describes the organizational structure of a country, including the name of the country, abbreviations used for the country, languages that are spoken, the number of administrative boundaries (for instance, city, state, or county), and the suffix of the reference data tables that is associated specifically with the reference data stored for that country. GC_PARSER_PROFILES: This table defines keywords and common abbreviations associated with addresses. For instance, “Street” is often abbreviated as “St.” This table can also store some typical spelling mistakes people make with standard keywords. GC_PARSER_PROFILEAFS: This table contains XML notation with the address structure for each country. Oracle Spatial 10g: Advanced
148
International Address Parsing
International addresses differ in format: US: 500 Oracle Parkway Germany: Bahnoffstraße, 53 Address format specified in XML GC_PARSER_PROFILEAFS (AF: Address Format) Customize “parsing rules” to specific country Example for the United States <address format ..> … <street address>… <house number> … </house number> <street name>… </street name> </street address> </address format> International Address Parsing The GC_PARSER_PROFILEAFS table contains address format information for each country. This enables Oracle Spatial Geocoder to look up metadata based on the country specified in the address and understand what each piece of information is, and where it is stored within the address. This enables it to look appropriately in the reference data for each country. Oracle Spatial 10g: Advanced
149
Geocoding Reference Data
GC_ROAD_xx Street names and house numbers GC_ROAD_SEGMENT_xx Street segments with geometries and house numbers. It is used for returning coordinates and other information. GC_AREA_xx Administrative areas Note: xx is the country-specific code. In the United States, xx = US. Geocoding Reference Data The slide lists the reference data tables used for geocoding. There are specific tables for each country, therefore, xx is used to denote that a country code is used. In the United States, xx=US. Road and road segment tables are used for address geocoding, in conjunction with area and postal code information. There are also point-of-interest and intersection tables used with other searches. Oracle Spatial 10g: Advanced
150
Geocoding Reference Data
GC_POSTAL_CODE_xx Postal code areas GC_POI_xx Points of interest GC_INTERSECTION_xx US only: Intersection-based searches Note: xx is the country-specific code. In the United States, xx = US. Oracle Spatial 10g: Advanced
151
Oracle Geocoder Functionality
Address parsing of input address: Search for input address in reference data Fuzzy searching of the input address Coordinate computation by interpolation: Reference data has coordinates for “600 Oracle Parkway” and “100 Oracle Parkway.” Input address: 500 Oracle Parkway Calculate location by interpolation. 600 500 100 Oracle Parkway Oracle Geocoder Functionality Address matches are completed within Oracle Spatial Geocoder using the metadata to break down the address, and the reference data to find matches. Addresses do not have to match perfectly for the geocoder to function. When a match is found, the geocoder computes coordinates based on interpolation. For every segment, start and end addresses are stored. Interpolation is used to compute the approximate location of intermediate addresses. Oracle Spatial 10g: Advanced
152
Oracle Spatial 10g Geocoding Functions
The geocoding functions provided are: SDO_GCDR.GEOCODE Returns an SDO_GEO_ADDR object with address and geocoding process information SDO_GCDR.GEOCODE_ALL Returns an array of SDO_GEO_ADDR objects with address and geocoding process information SDO_GCDR.GEOCODE_AS_GEOMETRY Returns an SDO_GEOMETRY object with the location of the geocoded address Oracle Spatial 10g Geocoding Functions Oracle Spatial 10g supplies three functions for geocoding: SDO_GCDR.GEOCODE SDO_GCDR.GEOCODE_ALL SDO_GCDR.GEOCODE_AS_GEOMETRY All functions have similar input parameters, but return geocoded data in different formats. Oracle Spatial 10g: Advanced
153
Oracle Spatial 10g Geocoding Functions
SDO_GEO_ADDR = SDO_GCDR.GEOCODE ( <USER_NAME>, <ADDRESS_LINES>, <COUNTRY>, <MATCH_MODE>) SDO_GEO_ADDR_ARRAY = SDO_GCDR.GEOCODE_ALL ( <USER_NAME>, <ADDRESS_LINES>, <COUNTRY>, <MATCH_MODE>) GEOM = SDO_GCDR.GEOCODE_AS_GEOMETRY ( <USER_NAME>, <ADDRESS_LINES>, <COUNTRY>) Oracle Spatial 10g Geocoding Functions (continued) There are three geocoding functions supported in Oracle Spatial 10g. They are: SDO_GCDR.GEOCODE: Returns address information, longitude/latitude, status, and matching information for an input address in the SDO_GEO_ADDR object type SDO_GCDR.GEOCODE_ALL: Returns a set of possible geocoding matches in the SDO_ADDR_ARRAY, which is a varray of type SDO_GEO_ADDR SDO_GCDR_GEOCODE_AS_GEOMETRY: Returns longitude/latitude information in the SDO_GEOMETRY object type Oracle Spatial 10g: Advanced
154
Oracle Spatial 10g Geocoding Functions
<USER_NAME> The schema containing the geocoding tables <ADDRESS_LINES> The address information encoded in SDO_KEYWORDARRAY <COUNTRY> The country code, for example 'US' <MATCH_MODE> The type of address match requested Oracle Spatial 10g Geocoding Functions (continued) The three geocoding functions SDO_GCDR.GEOCODE, SDO_GCDR.GEOCODE_ALL, and SDO_GCDR.GEOCODE_AS_GEOMETRY have similar input parameters. They are: USER_NAME: The schema containing the partner geocoding information ADDRESS_LINES: The address information encoded in SDO_KEYWORD_ARRAY. COUNTRY: The country code, for example 'US' Additionally, SDO_GCDR.GEOCODE and SDO_GCDR.GEOCODE_ALL include: MATCH_MODE: The type of address match requested Oracle Spatial 10g: Advanced
155
Oracle Spatial 10g Geocoding
ADDRESS_LINES information is encoded in SDO_KEYWORDARRAY. Valid address formats may vary by country. Examples of valid addresses include: SQL> DESCRIBE SDO_KEYWORDARRAY SDO_KEYWORDARRAY VARRAY(10000) OF VARCHAR2(9000) SDO_KEYWORDARRAY('1600 pennsylvania ave nw', 'washington, DC') SDO_KEYWORDARRAY('1718 Desales Street NW', 'Apartment 3G' , 'Washington, DC', '20036') Oracle Spatial 10g Geocoding ADDRESS_LINES are encoded in SDO_KEYWORD_ARRAY. SDO_KEYWORD_ARRAY is a set of string variables representing valid addresses for the COUNTRY input parameter. Oracle Spatial 10g: Advanced
156
Oracle Spatial 10g Geocoding: Match Mode
Match mode specifies how close the input address matches the stored address. EXACT: All attributes in address match storage RELAX_STREET_TYPE: Allows match if street type (Street, Road, Blvd, Ave) does not match RELAX_POI_NAME: Allows match if point-of-interest names do not match (Central Park = Central Pk) RELAX_HOUSE_NUMBER: House number and street type can be different Oracle Spatial 10g Geocoding (continued) Match mode is used in geocoding to specify how closely the input address must match the stored address. Valid match modes are: EXACT: All attributes of the address specified in SDO_KEYWORD_ARRAY must exactly match the stored address information in the geocoder. RELAX_STREET_TYPE: The street type in the address information encoded in SDO_KEYWORD_ARRAY does not need to match. For instance, if the input address has “Street,” and there is a match for “Road,” then that match is used. RELAX_POI_NAME: Allows a geocoding match if the point-of-interest name does not exactly match the stored point-of-interest name RELAX_HOUSE_NUMBER: Allows a geocoding match if the house number and street type are different RELAX_POI_NAME: The country code, for example 'US' Oracle Spatial 10g: Advanced
157
Oracle Spatial 10g Geocoding
RELAX_BASE_NAME [default]: The base name of the street, the house number, and the street type can be different from the data used for geocoding. For example, Crosse Street can match with Cross Road. RELAX_POSTAL_CODE: The postal code, base street name, house number, and street type can be different from the stored data. RELAX_BUILTUP_AREA, RELAX_ALL: Semantics of RELAX_POSTAL_CODE, but also relaxes city or town name as long as the match is in the same county Oracle Spatial 10g Geocoding (continued) Other match modes are: RELAX_BASE_NAME [default]: The name of the street, the house number, and the street type can be different than that stored in the geocoding database. RELAX_POSTAL_CODE: Same semantics of RELAX_BASE_NAME, also allowing nonexact matching of the postal code RELAX_BUILTUP_AREA, RELAX_ALL: Same semantics of RELAX_POSTAL_CODE, but also allows matches when the city or town name is different as long as the match occurs in the same county Oracle Spatial 10g: Advanced
158
Oracle Spatial 10g Geocoding
SDO_GEO_ADDR: Structure for returning geocoded results: SQL> desc sdo_geo_addr Name Type ID NUMBER ADDRESSLINES MDSYS.SDO_KEYWORDARRAY PLACENAME VARCHAR2(200) STREETNAME VARCHAR2(200) INTERSECTSTREET VARCHAR2(200) SECUNIT VARCHAR2(200) SETTLEMENT VARCHAR2(200) MUNICIPALITY VARCHAR2(200) REGION VARCHAR2(200) COUNTRY VARCHAR2(100) POSTALCODE VARCHAR2(20) POSTALADDONCODE VARCHAR2(20) FULLPOSTALCODE VARCHAR2(40) Oracle Spatial 10g Geocoding (continued) Data is returned from geocoding functions either in the SDO_GEOMETRY type, or either a single SDO_GEO_ADDR type or an array of this type. The SDO_GEO_ADDR type has the attributes shown in the slide. Oracle Spatial 10g: Advanced
159
Oracle Spatial 10g Geocoding
SDO_GEO_ADDR (continued): POBOX VARCHAR2(100) HOUSENUMBER VARCHAR2(100) BASENAME VARCHAR2(200) STREETTYPE VARCHAR2(20) STREETTYPEBEFORE VARCHAR2(1) STREETTYPEATTACHED VARCHAR2(1) STREETPREFIX VARCHAR2(20) STREETSUFFIX VARCHAR2(20) SIDE VARCHAR2(1) PERCENT NUMBER EDGEID NUMBER ERRORMESSAGE VARCHAR2(20) MATCHCODE NUMBER MATCHMODE VARCHAR2(30) LONGITUDE NUMBER LATITUDE NUMBER Oracle Spatial 10g Geocoding (continued) A full description of the SDO_GEO_ADDR type is available in the Oracle Spatial User’s Guide and Reference. Of particular importance in this slide are the matching information, MATCHCODE and MATCHMODE (so users know how well their geocoding query worked), LONGITUDE and LATITUDE information (so a location can be seen on a map), and SIDE, PERCENT, and EDGEID information (which are useful for routing). Oracle Spatial 10g: Advanced
160
Oracle Spatial 10g Geocoding
Values filled in the SDO_GEO_ADDR structure vary based on country. Information for the United States may include: STREET_NAME: The base name of the street SETTLEMENT: The city or town REGION: The state COUNTRY: The country POSTALCODE: Five-digit postal code POSTALADDONCODE: Four-digit string appended to the postal code FULLPOSTALCODE: Five-digit postal code plus four-digit add-on code HOUSENUMBER: House number: 123 in 123 Main St BASENAME: Street name: Main in 123 Main Street Oracle Spatial 10g Geocoding (continued) Geocoded addresses can be returned in the SDO_GEO_ADDR type. The filled-in values are dependent on the geographical region the geocoding occurs in. In the United States, the values shown in the slide can be used. Oracle Spatial 10g: Advanced
161
Oracle Spatial 10g Geocoding
More information for the United States may include: STREETTYPE: St for Street, Ave for Avenue, Rd for Road, and so on STREETPREFIX: Prefix: S in 123 S Main Street STREETSUFFIX: Suffix: NW in 123 Main Street NW SIDE: Side of street from lower to higher numbers PERCENT: Percentage value representing how far along the street you are when going from lower to higher street addresses EDGEID: Optional edge information if topological ERRORMESSAGE: Error information MATCHCODE: Numeric match information MATCHMODE: Match mode as previously described LONGITUDE: Geocoded longitude LATITUDE: Geocoded latitude Oracle Spatial 10g Geocoding (continued) As previously discussed, geocoded addresses can be returned in the SDO_GEO_ADDR type. The slide lists a continuation of the possible values used in the United States. Oracle Spatial 10g: Advanced
162
Oracle Spatial 10g Geocoding
Status information returned in MATCHCODE specifies how well the geocoder matched the input address: 1 Exact match: The city name, postal code, street name, street type (and suffix or prefix or both, if applicable), and house number match. 2 The city name, postal code, street name, and house number match, but the street type, suffix, or prefix do not match. 3 The city name, postal code, and street base name match, but the house number does not match. 4 The city name and postal code match, but the street address does not match. 10 The city name matches, but the postal code does not match. 11 The postal code matches the data used for geocoding, but the city name does not match. Oracle Spatial 10g Geocoding (continued) As previously discussed, geocoded addresses can be returned in the SDO_GEO_ADDR type. The slide lists a continuation of the possible values used in the United States. Oracle Spatial 10g: Advanced
163
SDO_GCDR.GEOCODE: Examples
Oracle Spatial 10g: Advanced
164
SDO_GCDR.GEOCODE: Example Match Mode = DEFAULT
SELECT SDO_GCDR.GEOCODE( 'GEOCODER', SDO_KEYWORDARRAY('1600 Pennsylvania Ave NW', 'Washington, DC'), 'US', 'DEFAULT') RESULT_GEO_ADDR FROM DUAL; RESULT_GEO_ADDR(ID, ADDRESSLINES, PLACENAME, STREETNAME SDO_GEO_ADDR(0, SDO_KEYWORDARRAY(), NULL, 'PENNSYLVANIA AVE NW', NULL, NULL, 'WASHINGTON', NULL, 'DC', 'US', '20006', NULL, '20006', NULL, '1600', 'PENNSYLVANIA', 'AVE', 'F', 'F',NULL, 'NW', 'R', .5, , '????#ENUT?B281CP?', 1, 'DEFAULT', , ) Result MATCHCODE is 1, exact match found Longitude and latitude values also returned SDO_GCDR.GEOCODE: Example (Match Mode = DEFAULT) In the slide example, the address for the White House (1600 Pennsylvania Ave NW) is returned in the SDO_GEO_ADDR type. The address is returned as well as other information. Note that the DEFAULT match mode was specified, and the same address as the input address is returned. The match code is 1 (exact match) and the longitude and latitude values are also returned (the geocoded values). Oracle Spatial 10g: Advanced
165
SDO_GCDR.GEOCODE: Example Match Mode = DEFAULT
Misspelled street address entered as input: SELECT SDO_GCDR.GEOCODE('GEOCODER', SDO_KEYWORDARRAY('1600 Pennsylvakia Ave NW', 'Washington, DC'), 'US', 'DEFAULT') RESULT_GEO_ADDR FROM DUAL; RESULT_GEO_ADDR(ID, ADDRESSLINES, PLACENAME, STREETNAME SDO_GEO_ADDR(0, SDO_KEYWORDARRAY(), NULL, 'PENNSYLVANIA AVE NW', NULL, NULL, 'WASHINGTON', NULL, 'DC', 'US', '20006', NULL, '20006', NULL, '1600', 'PENNSYLVANIA', 'AVE', 'F', 'F', NULL, 'NW', 'R', .5, , '????#E?UT?B281CP?', 4, 'DEFAULT', , ) SDO_GCDR.GEOCODE: Example (Match Mode = DEFAULT) (continued) In the slide example, there is an error with the input address for the (1600 Pennsylvania Ave NW), however the corrected address and longitude/latitude information is returned in the SDO_GEO_ADDR type. DEFAULT match mode was specified, so the address was corrected, and the match code is set to 4 (the city and postal code match, but the street address does not). Result MATCHCODE is 4. Result city matches. Result street address does not match. Oracle Spatial 10g: Advanced
166
SDO_GCDR.GEOCODE: Example Match Mode = EXACT
Misspelled street address entered as input: SELECT SDO_GCDR.GEOCODE('GEOCODER', SDO_KEYWORDARRAY('1600 Pennsylvakia Ave NW', 'Washington, DC'), 'US', 'EXACT') RESULT_GEO_ADDR FROM DUAL; RESULT_GEO_ADDR(ID, ADDRESSLINES, PLACENAME, STREETNAME SDO_GEO_ADDR(0, SDO_KEYWORDARRAY(), NULL, NULL, NULL, NULL, 'WASHINGTON', NULL, 'DC', 'US', '20001', NULL, NULL, NULL, NULL, NULL, NULL, 'F', 'F', NULL, NULL, 'L', 0, , '??????????B281CP?', 4, 'EXACT', , ) SDO_GCDR.GEOCODE: Example (Match Mode = EXACT) In the slide example, there is an error with the input address for the (1600 Pennsylvania Ave NW). Because the EXACT match mode was specified, there is no attempt to correct the address. The geocoding algorithm then tried its next best search criterion, which is to match city and state (Washington, DC). Because a match was found for Washington, DC, a longitude/latitude pair is returned for a location at the beginning of the street closest to the centroid of the city. The match code is set to 4 (the city and postal code match, but the street address does not). Note the ERRORMESSAGE information has changed in the examples provided so far. For more information about ERRORMESSAGE, see the Oracle Spatial User’s Guide and Reference. Result MATCHCODE is 4. Result city matches. Result street address has no EXACT match. Result longitude and latitude differ from previous slide. Oracle Spatial 10g: Advanced
167
SDO_GCDR.GEOCODE_AS_GEOMETRY: Example
Oracle Spatial 10g: Advanced
168
SDO_GCDR.GEOCODE_AS_GEOMETRY: Example
GEOCODE_AS_GEOMETRY similar to calling GEOCODE with match mode = DEFAULT Returns SDO_GEOMETRY instead of SDO_GEO_ADDR Returns best SDO_GEOMETRY candidate SELECT SDO_GCDR.GEOCODE_AS_GEOMETRY( 'GEOCODER', SDO_KEYWORDARRAY('1600 Pennsylvakia Ave NW', 'Washington, DC'), 'US') RESULT_GEOMETRY FROM DUAL; RESULT_GEOMETRY(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z)… SDO_GEOMETRY(2001, 8307, SDO_POINT_TYPE( , , NULL), NULL, NULL) SDO_GCDR.GEOCODE_AS_GEOMETRY: Example SDO_GCDR.GEOCODE_AS_GEOMETRY is similar to calling SDO_GCDR.GEOCODE match mode = DEFAULT. Instead of returning a SDO_GEO_ADDR type, it returns an SDO_GEOMETRY. The algorithm returns what it believes to be the best SDO_GEOMETRY candidate for the address provided. Oracle Spatial 10g: Advanced
169
SDO_GCDR.GEOCODE_ALL: Example
Oracle Spatial 10g: Advanced
170
SDO_GCDR.GEOCODE_ALL: Example
GEOCODE_ALL is similar to GEOCODE, but returns many results if address match is not exact. Array of results is returned in order, with the best match listed first. Results are returned in the SDO_GEO_ADDR_ARRAY structure. SELECT SDO_GCDR.GEOCODE_ALL('GEOCODER', SDO_KEYWORDARRAY('10 Pennsylvania Ave NW', 'Washington, DC'), 'US', 'DEFAULT') RESULT_SDO_GEO_ADDR_ARRAY FROM DUAL; SDO_GCDR.GEOCODE_ALL: Example SDO_GCDR.GEOCODE_ALL is similar to SDO_GCDR.GEOCODE, but it returns many results if there is no exact match. Results are returned in an array of type SDO_GEO_ADDR_ARRAY, with the best match listed first. The results are displayed in the following slide. Oracle Spatial 10g: Advanced
171
Oracle Spatial 10g Geocoding
Result of query from previous slide: RESULT_SDO_GEO_ADDR_ARRAY(ID, ADDRESSLINES,… SDO_ADDR_ARRAY( SDO_GEO_ADDR(1, SDO_KEYWORDARRAY(), NULL, 'PENNSYLVANIA AVE NW', NULL, NULL, 'WASHINGTON', NULL, 'DC', 'US', '20001', NULL, '20001', NULL, '301', 'PENNSYLVANIA', 'AVE', 'F', 'F', NULL, 'NW', 'R', 0, , '?????E?UT?B281CP?', 4, 'DEFAULT', , ), SDO_GEO_ADDR(1, SDO_KEYWORDARRAY(), NULL, 'PENNSYLVANIA AVE NW', NULL, NULL, 'WASHINGTON', NULL, 'DC', 'US', '20004', NULL, '20004', NULL, '300', 'PENNSYLVANIA', 'AVE', 'F', 'F', NULL, 'NW', 'L',0, , '?????E?UT?B281CP?', 4, 'DEFAULT', , ), SDO_GEO_ADDR…( SDO_GCDR.GEOCODE_ALL: Example (continued) This example result from the query on the previous slide illustrates that when the street address does not match an address in the geocoder database, then the function may return several possible matches. Oracle Spatial 10g: Advanced
172
Geocoding in Oracle Spatial 10g Release 2
Geocoding in Oracle Spatial 10g Release 2 is enhanced to include: Reverse Geocoding User supplies a point location and the Geocoder returns an address Batch Geocoding Geocodes multiple addresses in a single call Structured Address Geocoding Input address in an address object rather than a keyword array Oracle Spatial 10g: Advanced
173
Oracle Spatial 10g: Advanced 1-175
Summary In this lesson you should have learned: Geocoding Concepts The Oracle Spatial Geocoding Architecture Geocoding Metadata Concepts Geocoding Reference Data Concepts The Geocoding Schema Objects How to use Geocoding Functions Summary This section introduced the concepts associated with the Oracle Spatial Geocoding. It described what geocoding is, and the metadata and reference data associated with Oracle Spatial Geocoding. Also, geocoding functions were introduced. Oracle Spatial 10g: Advanced
174
Oracle Spatial Routing Engine
175
Oracle Spatial 10g: Advanced 1-177
Objectives After completing this lesson you should be able to do the following: Explain the Oracle Spatial Routing architecture Describe how to formulate route requests Describe the route response Use the sample RouteServer JSP Objectives This section introduces you to the concepts associated with the Oracle Spatial Routing Engine. Oracle Spatial 10g: Advanced
176
The Oracle Spatial 10g Routing Engine
The Oracle Spatial Routing Engine enables the hosting of XML-based Web services that: Given a route request that includes start location and an end location, returns route information (which can include directions, driving distances, estimated drive times, and geometry information) between the two locations Given a batch route request consisting of a single start location and multiple end locations, can return information (driving distances and estimated drive times) for each of the start and end location pairs The Oracle Spatial 10g Routing Engine The Oracle Spatial Routing Engine enables the hosting of XML-based Web services that provide the following capabilities: Given a route request that consists of a start location and an end location, return route information that can include directions, estimated driving times, and driving distances between the two locations. Given a batch route request consisting of a single start location and multiple end locations, returns information that can include estimated driving times, and driving distances between the start node and each of the end nodes. Oracle Spatial 10g: Advanced
177
Routing Engine Architecture
Browser/Apps Client XML/HTTP Java Environment Routing Engine JDBC Routing Engine Architecture Client applications connect to the Routing Engine and send XML routing requests via the HTTP communications protocol. Requests include information about which database to query, and also information about start and end locations for the route. Start and end locations can be identified either as address information or as the EDGEID, PERCENT, and SIDE attributes resulting from a geocoder request. The Oracle Spatial Routing Engine executes in a Java environment, which can be either a middle-tier Java environment or a server Java environment. The Routing Engine accepts routing requests, connects to the database using JDBC, fetches information required to process the request, processes the routing request, and sends the results of the routing request back to the requestor. Oracle Spatial Oracle Spatial 10g: Advanced
178
Oracle Spatial 10g: Advanced 1-180
Routing Query A route request consists of: Preferences Start location End location A batch route request consists of: End locations A route response consists of: Route information Optional Geometry Segment information (for each segment of the route) A batch route response consists of: Route information (for each route) Routing client Routing engine Routing Query A client sends an XML request to the Routing Engine that includes preferences, the start location, and the end location of a single route request; or preferences, the start location, and one or more end locations of a batch route request. The response consists of route information associated with each request or batch request. Route information can include distance information, time information, directions, and the SDO_GEOMETRY representing the route for a route request, and distance and time information for each route in a batch route request. Oracle Spatial Oracle Spatial 10g: Advanced
179
A Routing Engine Request
This is an example routing engine request: HOSTNAME Network path of the server on which the routing engine is running PORT The port on which the application server listens ROUTE-SERVER-SERVLET-PATH The routing engine servlet path (for example, routeserver/servlet/RouteServerServlet) XML-REQUEST The URL-encoded XML request submitted using the HTML GET or POST method A Routing Engine Request This is the format of a route request to the routing engine. The format of the HTTP request includes: The host name of the server on which the routing engine is running The port number on which the Java container is listening The path to the routing engine servlet The encoded XML input request Oracle Spatial 10g: Advanced
180
XML Input for a Route Request
This is an example of an XML input for a route request: <?xml version="1.0" standalone="yes"?> <route_request id="8" route_preference="fastest" road_preference="highway" return_driving_directions="true" distance_unit="mile" time_unit="minute"> <start_location> <input_location id="1"> <input_address> <us_form1 street="1000 Winter St" lastline="Waltham, MA" /> </input_address> </input_location> </start_location> <end_location> <input_location id="2"> street="1 Oracle Dr" lastline="Nashua, NH" /> </end_location> </route_request> XML Input for a Route Request Here you see an example of XML input for a route request based on using input addresses. You can see that each route request includes an ID value (required), and the start and end addresses also have ID values assigned (also required). The XML for this request includes preferences for the fastest route using highways if possible, returning driving directions, using miles for distances and minutes for times. Note that all of these preferences are defaults, so they did not need to be specified. The above input is formatted for readability. Oracle Spatial 10g: Advanced
181
Oracle Spatial 10g: Advanced 1-183
A Route Request All route requests require an XML input request. An XML request for a single route includes: A numeric route ID One start and one end location Optionally, one or more of the following attributes: route_preference: Fastest (default) or shortest road_preference: Highway (default) or local return_driving_directions: TRUE by default return_route_geometry: FALSE by default distance_unit: Kilometer, mile (default), meter time_unit: Hour, minute (default), second A Route Request All route requests to the routing engine require an input XML request. There are two types of requests, a (single) route request, and a batch route request. The (single) route request to the routing engine requires: A numeric route ID A start location An end location Optionally, one or more of the following attributes can be specified: Route preference: Fastest (default) or shortest Road preference: Highway (default) or local Return driving directions (TRUE by default) Return the line string coordinates for the route (FALSE by default) Distance unit: Kilometer, mile (default), meter Time unit: Hour, minute (default), second Oracle Spatial 10g: Advanced
182
Response XML from a Route Request
This is the XML response from the previous route request: <?xml version="1.0" ?> <route_response> <route id="8" step_count="14" distance=" " distance_unit="mile" time=" " time_unit="minute"> <segment sequence="1" instruction="Start out on WINTER ST (Going South)" distance=" "/> sequence="2" instruction="Stay STRAIGHT to go onto TOTTEN POND RD (Going East)" distance=" "/> sequence="3" instruction="Turn LEFT onto WYMAN ST (Going North)" distance=" "/> Response XML from a Route Request Above is an example of the XML response for the previous route request. The response includes the route information, the travel time (in minutes), and distance information. Note that this response has been formatted for readability. Oracle Spatial 10g: Advanced
183
Response XML from a Route Request
XML response from the previous route request (continued): <segment sequence="4" instruction="Take I-95 N RAMP toward PEABODY" distance=" "/> sequence="5" instruction="Merge onto I-95/RT-128 (Going North)" distance=" "/> sequence="6" instruction="Continue on I-95/RT-128" distance="0.0"/> sequence="7" instruction="Stay STRAIGHT to go onto 32B/32A (Going East)" distance=" "/> sequence="8" instruction="Take EXIT 32A toward LOWELL" distance=" "/> sequence="9" instruction="Stay STRAIGHT to go onto RAMP (Going East)" distance=" "/> Response XML from a Route Request (continued) Above is a continuation of the response XML from the routing engine. Oracle Spatial 10g: Advanced
184
Response XML from a Route Request
XML response from the previous route request (continued): <segment sequence="10" instruction="Turn LEFT onto US-3 (Going Northwest)" distance=" "/> sequence="11" instruction="Stay STRAIGHT to go onto FREDERICK E EVERETT TPKE/US-3 (Going Northwest)" distance=" "/> sequence="12" instruction="Take EXIT 1 toward SO NASHUA" distance=" "/> sequence="13" instruction="Turn LEFT onto SPIT BROOK RD (Going West)" distance=" "/> sequence="14" instruction="Turn RIGHT onto ORACLE DR (Going North)" distance=" "/> </route> </route_response> Response XML from a Route Request (continued) The example above finishes the response XML from the routing engine. Oracle Spatial 10g: Advanced
185
Point Coordinates in a Route Request
The previous route request used addresses for the start and end locations. A coordinate interface is available in Oracle Spatial 10g Release 2. This is useful for telematics and other applications. From a location specified by coordinates, what is the route to a particular address? Given a current location, what is the route to a location specified by coordinates? Point Coordinates in a Route Request Start and end locations (input locations) can be addresses. Another option is for start and/or end locations to be point coordinates that specify the locations. Oracle Spatial 10g: Advanced
186
Oracle Spatial 10g: Advanced 1-188
A Batch Route Request All route requests require an XML input request. An XML request for a batch route includes: A numeric route ID One start and one or more end locations Optionally, one or more of the following attributes: route_preference: Fastest (default) or shortest road_preference: Highway (default) or local distance_unit: Kilometer, mile (default), meter time_unit: Hour, minute (default), second A Batch Route Request All route requests to the routing engine require an input XML request. A batch route request to the routing engine requires: A numeric route ID A start location One or more end locations Optionally, one or more of the following attributes can be specified: Route preference: Fastest (default) or shortest Road preference: Highway (default) or local Distance unit: Kilometer, mile (default), meter Time unit: Hour, minute (default), second Oracle Spatial 10g: Advanced
187
Oracle Spatial 10g: Advanced 1-189
A Batch Route Request Optionally, one or more of the following attributes (continued): sort_by_distance: Sorts the returned information in ascending order by distance (FALSE by default) cutoff_distance: Returns information only if the distance is less than or equal to a specified distance (no limit by default) A Batch Route Request (continued) Optionally, one or more of the following attributes can be specified (continued): Whether or not to sort the returned information in ascending order by the distance of the end location from the start location (FALSE by default) Cut-off distance, returning only information where the end location is less than or equal to a specified distance from the start location (no limit by default) Oracle Spatial 10g: Advanced
188
XML Input for a Batch Route Request
This example is an XML input for a batch route request: Has multiple end locations <?xml version="1.0" standalone="yes"?> <batch_route_request id="8" route_preference="fastest" road_preference="highway" return_driving_directions="false" sort_by_distance = "true" cutoff_distance="35" distance_unit="mile" time_unit="minute"> <start_location> <input_location id="1"> <input_address> <us_form1 street="1000 Winter St" lastline="Waltham, MA" /> </input_address> </input_location> </start_location> XML Input for a Batch Route Request Here you see an example of an XML input for a batch route request. Note that it has one start location, and multiple end locations. The XML for this request includes preferences for the fastest route using highways if possible, returning driving directions, using miles for distances and minutes for times. Note that all these preferences are defaults, so did not need to be specified. Also note that RETURN_DRIVING_DIRECTIONS must be FALSE for batch route requests. The input in the slide is formatted for readability, and continues in the next slide. Oracle Spatial 10g: Advanced
189
XML Input for a Batch Route Request
This example continues the XML for a batch route request: <end_location> <input_location id="10"> <input_address> <us_form1 street="1 Oracle Dr" lastline="Nashua, NH" /> </input_address> </input_location> </end_location> <input_location id="11"> street="22 Monument Sq" lastline="Concord, MA" /> XML Input for a Batch Route Request (continued) This slide highlights the multiple END_LOCATION tags that are the hallmark of a batch route request. The above input is formatted for readability. Oracle Spatial 10g: Advanced
190
XML Input for a Batch Route Request
This example finishes the XML for a batch route request: <end_location> <input_location id="12"> <input_address> <us_form1 street="1 City Hall Plaza" lastline="Boston, MA" /> </input_address> </input_location> </end_location> </batch_route_request> XML Input for a Batch Route Request (continued) This slide finishes the batch route request. The input shown in the slide is formatted for readability. Oracle Spatial 10g: Advanced
191
Response XML from a Batch Route Request
This is the XML response from the previous route request: <?xml version="1.0" standalone="yes" ?> <batch_route_response id="8"> <route id="11" step_count="0" distance=" " distance_unit="mile" time=" " time_unit="minute" /> <route id="12" distance=" " time=" " <route id="10" distance=" " time=" " </batch_route_response> Response XML from a Batch Route Request Above is an example of the XML response for the previous batch route request. The response includes the travel time (in minutes) and distance information for the routes that had a distance of less than 35 miles, as specified in the batch route request (CUTOFF_DISTANCE=35). The route IDs for the response can be matched to the end location IDs in the request. Note that this response has been formatted for readability. Oracle Spatial 10g: Advanced
192
Oracle Spatial 10g: Advanced 1-194
Sample RouteServer A sample RouteServer application is supplied with the Oracle Spatial Router. Sample RouteServer This is the startup page of the sample RouteServer. This example shows you how to route by address. Oracle Spatial 10g: Advanced
193
Oracle Spatial 10g: Advanced 1-195
Sample RouteServer XML to route with a start address and an end address. Sample RouteServer (continued) This is an example of the XML used to generate a request for the route server. Oracle Spatial 10g: Advanced
194
Oracle Spatial 10g: Advanced 1-196
Sample RouteServer XML response from previous routing request: Sample RouteServer (continued) This is an example of the XML response from the previous request to the route server. Oracle Spatial 10g: Advanced
195
Oracle Spatial 10g Release 2 Routing Enhancements
Longitude/latitude point interface In Oracle Spatial 10g Release 2, a point interface has been added so that you can specify a point location as: A starting location An ending location Both a starting and an ending location Oracle Spatial 10g Release 2 Routing Enhancements Oracle Spatial 10g Release 2 adds a point interface for routing requests, allowing you to specify a longitude/latitude point as a starting location, an ending location, or both a starting and ending location. Oracle Spatial 10g: Advanced
196
Oracle Spatial 10g: Advanced 1-198
Summary In this lesson, you should have learned the following: The Oracle Spatial routing architecture How to create a route request How to interpret a route response How to use the sample RouteServer JSP Summary This section introduced the concepts associated with the Oracle Spatial Routing Engine. It described Oracle Spatial’s routing architecture, how to create a route request, and how to interpret the response. Additionally, a sample RouteServer JSP was used to send route requests and receive responses to or from Oracle Spatial Router. Oracle Spatial 10g: Advanced
197
Oracle Spatial Topology Data Model
198
Oracle Spatial 10g: Advanced 1-200
Objectives After completing this lesson, you should be able to: Explain what topology is Describe the Oracle Spatial Topology Data Model Create a topology Load topology primitives Explain the topology feature model Use the topology data type: SDO_TOPO_GEOMETRY Describe topology caches Use SDO_TOPO_MAP.CREATE_FEATURE Explain topology hierarchies Discuss Spatial queries and topology Share a topology between Oracle users Oracle Spatial 10g: Advanced
199
Introduction to Topology
Oracle Spatial 10g: Advanced
200
Oracle Spatial Feature Descriptions
Object Storage Topology Storage G1 G2 G3 G4 G5 N3 E1 E10 F1 E3 N2 E2 F2 N4 N1 E4 N5 N6 e5 F-1 F3 E7 E6 N7 E8 E9 Oracle Spatial Feature Descriptions Object storage: Each feature is stored as a separate but complete object. This is accomplished using Oracle’s SDO_GEOMETRY object. In the illustration on the left, there are five separate geometries shown. These objects are used to model spatial data. For example, land parcels can be represented as polygons (G1, G2, and G3) and roads can be line strings (G4 and G5). Object storage is optimal for applications that require manipulation and display of geometry data is as a complete object, for example, map generation. Topology storage: In the object storage model, land parcels G1 and G2 each store the shared edge. The object model must duplicate shared edges between parcels because the SDO_GEOMETRY object must include all the coordinates that make up each parcel. In a topology model, primitive nodes, edges, and faces are stored once, and initially not associated with any features. Each feature is then associated with a list of primitive identifiers. In the example above, face 1 (F1) is made up of edges E1 and E2. Face 2 (F2) is made up of edges E2, E3, E4, and E5. Parcel G1 can then be associated with F1, and parcel G2 associated with F2. By doing so, none of the primitives (nodes, edges, or faces) are stored more than once in the topology model. N8 N9 Oracle Spatial 10g: Advanced
201
Oracle Spatial 10g: Advanced 1-203
Spatial Feature Each of these represents a spatial feature. Oracle Spatial can store features in two ways: Object storage: Each feature is stored as a separate, complete object. Topology storage: Each feature is modeled in terms of the topological primitives it is composed of. California Main street Current car location Spatial Feature Spatial features can be real-world spatial objects. Examples of these features include roads, land boundaries such as cadastral (land parcel) boundaries and the United States county boundaries, and electric utility cables. In Oracle Spatial, a spatial feature can be stored in two ways. Your business requirements will determine the optimal way to store spatial features. Object storage: Stores each feature as a separate but complete object. This can be accomplished with Oracle’s SDO_GEOMETRY type. Object storage is optimal for applications that require manipulation and display of geometry data as complete objects, for example map generation. Topology storage: Each feature is modeled in terms of its basic topological elements: Nodes Edges Faces Topological storage is optimal for data collection as well as for applications that require topological consistency, for example, land management. Oracle Spatial 10g: Advanced
202
Advantages of Using Topology
Some of the advantages of using topology to store and manage data include: No redundant storage of data: Shared edges between objects stored only once Features from different layers can share edges, such as roads and land parcels Data consistency: No “registration” issues between geometries A boundary between objects is moved only once Topological relationships are quickly and easily determined. Advantages of Using Topology There are several advantages of using a topological data model over an object data model. There is no redundant storage of data. In the object data model, edges between two adjacent land parcels are stored twice, once for each land parcel. In the topology data model, the shared edges are stored only once. In addition, Oracle’s topological data model allows features from different layers to share topological primitives, for example, roads and land parcels. Data remains consistent in the topological data model. In the object data model, shared edges between adjacent parcels are stored twice. Parcel boundaries may be slightly inconsistent, because edge coordinates of adjacent parcels may not be perfectly aligned. Also, if an adjacent edge between parcels changes, it must be changed in two places. The topology data model eliminates data consistency issues. The topological relationships are very easily and quickly determined using the topology data model. The benefits described are not narrowly focused in one application space, but apply to a large range of application areas. Oracle Spatial 10g: Advanced
203
Oracle Spatial 10g: Advanced 1-205
What Is Topology? Topology is a branch of mathematics concerned with objects in space. Topological relationships: Remain constant when coordinate space is deformed (twisted, stretched, but not torn) Examples: TOUCH, INSIDE, CONTAINS Relationships that are not topological: Length Distance Area Oracle Spatial Topology Data Model stores and maintains topological relationships between features using a database. What Is Topology? Topology is a branch of mathematics that defines objects in space and how they interact. Topological relationships between features are those relationships that remain invariant when a coordinate space undergoes continuous deformations, such as twisting and stretching, but not tearing. For this reason, topology is sometimes called rubber-sheet geometry. Examples of topological relationships include the following: TOUCH INSIDE CONTAINS COVERS COVEREDBY Some relationships between objects do change when a coordinate space is deformed. Examples include the length of an object, the distance between two objects, and the area of an object. Oracle Spatial Topology Data Model stores and maintains topological relationships between features using a database. Oracle Spatial 10g: Advanced
204
Topological Relationships
The following are examples of topological relationships: The following relationships are not topological: A B A B A B A B CONTAINS and INSIDE COVERS and COVEREDBY TOUCH OVERLAPBDYINTERSECT D Area of D A Length of A B C Distance between B and C Topological Relationships This slide contains some examples of topological relationships between objects. CONTAINS: The first object wholly contains the second object, including the boundary of the contained object. In the slide, A CONTAINS B. It is the opposite of INSIDE. INSIDE: The first object is wholly contained within the second object, including the boundary of the contained object. It is the opposite of CONTAINS. B INSIDE A implies A CONTAINS B. COVERS: The interior of the second object is completely contained in the interior or boundary of the first object, and their boundaries intersect. The opposite relationship is COVEREDBY. In the slide, A COVERS B. COVEREDBY: The opposite of COVERS. B COVEREDBY A implies A COVERS B. TOUCH: The boundaries of the objects intersect, but the interiors do not intersect. In the slide, A TOUCH B and B TOUCH A. OVERLAPBDYINTERSECT: The interiors of the two objects intersect, and some portion of either or both of the interiors does not intersect with any portion of the interior of the other object. Also, the boundaries intersect. In the slide, A OVERLAPBDYINTERSECT B and B OVERLAPBDYINTERSECT A. Some nontopological relationships between objects, such as length, distance, and area, are also shown in the slide. Oracle Spatial 10g: Advanced
205
Topology Concepts: Nodes, Edges, and Faces
May represent point feature(s) Island node (for example, N5) Node bounds an edge (for example, N1) May not represent a point feature Node bounds an edge (for example, N3) Node that results from the intersection of edges (for example, N9) E2 E4 F –1 N2 E9 N3 E8 N5 N10 N9 N8 E3 F1 F2 E5 E7 N7 N6 E1 N1 E6 N4 Topology Concepts: Nodes, Edges, and Faces In a topology, nodes may or may not represent point features. Two examples of nodes that could represent point features are nodes N5 and N1. N5 is an example of an island node. N1 is an example of a node that bounds an edge (edges will be discussed in the next slide). Both N1 and N5 could represent point features, for example, store locations. Some nodes may not represent any features, but are necessary primitives in a topology. For example, E3 may represent a linear road feature. N3 does not represent any feature, but is necessary to bound E3. Another example is N9. In a topology, edges cannot cross. So node N9 was created to enable edges E8 and E9 to be added to the topology. Oracle Spatial 10g: Advanced
206
Topology Concepts: Nodes, Edges, and Faces
An edge: Is always bounded by two nodes Is directional Can contain shape points (for example, E6 has 5 shape points) May represent linear feature(s) Island edge represents feature(s) (for example, E7 could be a landing strip) Non-island edge represents feature(s) (for example, E3 could be a road) May not represent a linear feature. May be part of area boundaries. (for example, E1) E2 E4 F -1 N2 E9 E8 N5 N3 N10 N9 N8 E3 F1 F2 E5 E7 N7 N6 E1 N1 E6 N4 Topology Concepts: Nodes, Edges, and Faces (continued) In a topology, an edge is always bound by two nodes. Edges are directional. Edge direction can be determined by traversing the edge from start node to end node. Edges can contain shape points. Shape points are not nodes. They are points that describe the shape of an edge between its bounding nodes. For example, E6 has five shape points. All edges have an associated direction. The arrows in the example show direction, which is determined by the order in which the coordinates of the edge have been defined (the coordinates begin at the start node, and end at the end node). A positive direction agrees with this orientation of the edge, and a negative direction reverses the orientation. Each orientated edge is called a directed edge, and each directed edge is the mirror image of its negated edge. Edges may or may not represent linear features. For example, E7 (an island edge), could represent a landing strip. Non-island edges, like E3, could represent a road. Some edges may not represent any feature, but are necessary in a topology. For example, E1 is one of the several edges that bound an area (F1). Oracle Spatial 10g: Advanced
207
Topology Concepts: Nodes, Edges, and Faces
Face -1 is the universal face (contains the entire topology). A face may represent polygon feature(s): For example, F1 A face may be part of a group of faces that represent a polygon feature: For example, F1 and F2 together may represent a feature. Groups of faces that represent a feature do not include coincident edges (E3 is not part of the feature by default). E2 E4 F -1 N2 E9 N3 E8 N10 N5 N9 N8 E3 F1 F2 E5 E7 N7 N6 E1 N1 E6 N4 Topology Concepts: Nodes, Edges, and Faces (continued) In a topology, faces are used to describe area features (polygons). A face is completely bound by one or more edges. Face -1 (F –1 in the slide) is a special face that contains the entire topology. Faces may or may not represent polygon features. For example, F1 and F2 together may represent a feature, like a town border. F1 was created when edge E3 was added. But F1 alone may not represent any feature. Groups of faces that represent a feature do not include coincident edges. For example, the boundary of a town represented by F1 and F2 does not include edge E3. Oracle Spatial 10g: Advanced
208
Topology Concepts: Nodes, Edges, and Faces
Faces do not have to represent polygon feature(s). For example, this model may be of a road network. Connecting roads together causes faces F1 and F2 to be created in the topology, but these faces do not have to be associated with any features stored in the database. E2 E4 F -1 N2 E9 N3 E8 N5 N10 N9 N8 E3 F1 F2 E5 E7 N7 N6 E1 N1 E6 N4 Topology Concepts: Nodes, Edges, and Faces (continued) In the previous slide you saw how one or more faces may be associated with a spatial feature. It is also possible for faces to be created when no features are associated with them. In the above example, faces F1 and F2 are created as roads close off areas within the topology, but it is not necessary for those faces to be associated with any features stored in the database. Oracle Spatial 10g: Advanced
209
Oracle Spatial 10g: Advanced 1-211
Topology Example Below are two land parcels whose boundary includes a stream. Edge E3 is shared between land parcel features and also a stream feature. Land parcel features Land Parcel 1 associated with face F1 Land Parcel 2 associated with face F2 Both faces include edge E3. Stream features Stream 1 associated with edge E3 (and edges E1 and E5) F2 Land Parcel 2 E4 E1 E3 E5 Stream 1 Topology Example Topology primitives can be shared across different types of features. For example, this slide contains a picture of two land parcel features, and a stream feature. One edge (E3) is associated with each land parcel boundary. The same edge (E3) is also associated with Stream 1 (along with edges E1 and E5). N2 N1 N3 N4 E2 F1 Land Parcel 1 Oracle Spatial 10g: Advanced
210
Oracle Spatial 10g Topology Data Model
The Topology Data Model includes: Topological primitives, each with a unique ID SDO_TOPO_GEOMETRY, a data type to create a spatial feature derived from a set of primitive IDs Metadata views Commands to create, populate, edit, and validate topology-related structures Topological spatial index Topological spatial operators to perform spatial analysis Oracle Spatial 10g: Advanced
211
Oracle Spatial 10g: Advanced 1-213
Creating a Topology Oracle Spatial 10g: Advanced
212
Tables in the Topology Data Model
In the Topology Data Model, when SDO_TOPO.CREATE_TOPOLOGY is called, the following tables are created: Three tables that contain topology primitives: <topology_name>_NODE$ <topology_name>_EDGE$ <topology_name>_FACE$ One table to maintain the transaction history for merges and splits of edges and faces: <topology_name>_HISTORY$ Tables in the Topology Data Model When the SDO_TOPO.CREATE_TOPOLOGY command is called, the following tables are created: <topology_name>_NODE$: Stores node primitives <topology_name>_EDGE$: Stores edge primitives <topology_name>_FACE$: Stores face primitives <topology_name>_HISTORY$: A single table that maintains the transaction history for merges and splits of edges and faces. Oracle Spatial 10g: Advanced
213
The Topology Data Model
SDO_TOPO.CREATE_TOPOLOGY creates a topology. A topology is analogous to a project. There can be multiple topology projects in an Oracle database, or even within an Oracle user. Each topology has a self-contained set of primitives. It has everything required to read and edit its primitives. Primitives are not shared across topology projects. A topology’s information can be accessed by multiple Oracle users. The Topology Data Model You can think of the topology data model in terms of topology projects. Calling SDO_TOPO.CREATE_TOPOLOGY creates the schema associated with a topology (or topology project). All the information required for that project is included. Multiple Oracle users can access the same topology. The Oracle database, or even an Oracle user, may contain multiple topology projects. Each topology (or project) is created by calling SDO_TOPO.CREATE_TOPOLOGY. Primitives cannot be shared across topologies (or projects). Oracle Spatial 10g: Advanced
214
SDO_TOPO.CREATE_TOPOLOGY
Creates an empty topology Creates NODE$, EDGE$, FACE$, HISTORY$ tables Sets up the metadata An Oracle schema can contain more than one topology. Primitives cannot be shared across topologies. No primitives or spatial features are created at this stage. Optional parameters available to specify the NODE$, EDGE$, FACE$, and HISTORY$ tablespaces SDO_TOPO.CREATE_TOPOLOGY When a topology is created, Oracle Spatial creates an empty topology in the Oracle Spatial Topology Data Model. Steps performed when creating a topology include: 1. Topology metadata storage. 2. Creation of the following tables: <topology_name>_NODE$ <topology_name>_EDGE$ <topology_name>_FACE$ <topology_name>_HISTORY$ There are optional SDO_TOPO.CREATE_TOPOLOGY parameters available to specify the tablespace for each table listed above. At this point, no primitives are loaded, and no features are associated with the topology. SDO_TOPO.CREATE_TOPOLOGY('<topology_name>', <tolerance>, <srid>); Oracle Spatial 10g: Advanced
215
SDO_TOPO.CREATE_TOPOLOGY Parameters
<topology_name> The name of the topology Follows Oracle database naming requirements Maximum length 20 characters <tolerance> Associated with the SDO_GEOMETRY columns in the NODE$, EDGE$, and FACE$ tables SDO_TOPO.CREATE_TOPOLOGY Parameters The SDO_TOPO.CREATE_TOPOLOGY parameters are: <topology_name> The name of the topology The name of the topology follows Oracle naming rules (must begin with an alphabetic character, cannot include special characters like %, and so on). An additional requirement for a topology name is a 20-character maximum length. <tolerance> The tolerance to associate with all of the topological elements in the topology. Two parallel edges that are within the tolerance for their entire length will be merged into a single edge. Oracle Spatial 10g: Advanced
216
SDO_TOPO.CREATE_TOPOLOGY Parameters
<srid> Spatial reference system ID to associate with all of the layers in the topology Foreign key to MDSYS.CS_SRS Only one coordinate system can be in a topology The default is NULL SQL> EXECUTE SDO_TOPO.CREATE_TOPOLOGY('CITY_DATA',0.05,8307); SDO_TOPO.CREATE_TOPOLOGY Parameters (continued) The rest of the SDO_TOPO.CREATE_TOPOLOGY parameters are: <SRID> The coordinate system ID for the topology The spatial reference system (coordinate system) ID for this topology Is a foreign key to MDSYS.CS_SRS All elements in the topology must have the same spatial reference system ID. The default is NULL. <optional tablespace parameters> Four optional parameters to specify the tablespace associated with the NODE$, EDGE$, FACE$, and HISTORY$ tables. Oracle Spatial 10g: Advanced
217
SDO_TOPO.DROP_TOPOLOGY
SDO_TOPO.DROP_TOPOLOGY('<topology_name>'); <topology_name>: Name of the topology to be dropped: Drops the NODE$, EDGE$, FACE$, HISTORY$, and RELATION$ tables (RELATION$ table discussed later in the course) Cannot drop a topology if feature layers are associated with it (feature layers are discussed later in the course) SDO_TOPO.DROP_TOPOLOGY This procedure drops a topology, including the NODE$, EDGE$, FACE$, HISTORY$, and RELATION$ tables associated with the topology. It also removes the metadata entries associated with the topology. A topology cannot be dropped if it has feature layers associated with it (SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER and SDO_TOPO.DROP_TOPO_GEOMETRY_LAYER are discussed in the slide titled “Register Feature Layer with a Topology”). SQL> EXECUTE SDO_TOPO.DROP_TOPOLOGY('CITY_DATA'); Oracle Spatial 10g: Advanced
218
Loading Topology Primitives
Oracle Spatial 10g: Advanced
219
Adding Topology Primitives to NODE$, EDGE$, and FACE$ Tables
Bulk load operations: Bulk load topology primitives into the NODE$, EDGE$, and FACE$ tables: SQL*Loader Java, PL/SQL, OCI, or other programmatic interface SQL INSERT statements Adding Topology Primitives to NODE$, EDGE$, and FACE$ Tables An initial bulk load of topological primitives is the best way to migrate topology data from an external source into Oracle’s Topology Data Model. Bulk loaded primitives must adhere to rules that govern a valid topology, for example: Edge primitives in a topology cannot cross. Explicit nodes must exist where edges meet. Node primitives in a topology cannot coincide with other nodes. The remaining rules are discussed in the SDO_TOPO_MAP.VALIDATE_TOPOLOGY command, as documented in the Oracle Spatial Topology and Network Data Models 10g guide. Bulk load operations can be accomplished with SQL*Loader, array inserts via SQL, Java PL/SQL, OCI, or other programmatic interfaces. Oracle Spatial 10g: Advanced
220
Adding Topology Primitives to NODE$, EDGE$, and FACE$ Tables
Non bulk load/edit operations: Oracle Spatial Topology Data Model includes APIs to help load or edit topology primitives: Java PL/SQL Note: Once APIs are used, bulk loads cannot be used (One exception discussed in an upcoming slide) Adding Topology Primitives to NODE$, EDGE$, and FACE$ Tables (continued) Oracle Spatial includes transactional Java and PL/SQL topological load/edit APIs. The APIs ensure that the primitives added adhere to the rules that govern a valid topology. For example, the API does not allow an edge primitive to be added that crossed other edges in the topology. Non API bulk loads do not ensure that the rules of a valid topology are not violated. Once the transactional APIs are used, bulk loads cannot be used, unless they occur in an area that does not overlap with primitives already loaded. Note: The Data Model APIs are discussed throughout this lesson. Oracle Spatial 10g: Advanced
221
Load Topology Primitives
Before loading topology primitives, the topology must be created. For a topology named CITY_DATA, SDO_TOPO.CREATE_TOPOLOGY creates the following tables: CITY_DATA_NODE$ CITY_DATA_EDGE$ CITY_DATA_FACE$ CITY_DATA_HISTORY$ Oracle Spatial 10g: Advanced
222
Load Topology Primitives
For data in an external topological model, best initial load performance is accomplished by: Bulk load topology primitives to the NODE$, EDGE$, FACE$ tables: SQL*Loader/Data Pump Insert statements May require conversion utility from existing model to Oracle’s model After topology primitives are loaded, spatial features can be associated with the topological primitives. Load Topology Primitives After a topology has been created, it must be loaded. If the data is already in some topological model, it may be easy to transform and load it. If the data is not in a topological model, it may require building a utility to convert it. Oracle Spatial 10g: Advanced
223
Load Topology Primitives
Only positive integer values for primitive IDs: NODE_ID in the NODE$ table EDGE_ID in the EDGE$ table FACE_ID in the FACE$ table Exception, universal FACE_ID is –1 IDs must be unique in each table. The same ID value can be stored in different tables. Note: For data not in an external topological model, SDO_TOPO_MAP.CREATE_FEATURE can push SDO_GEOMETRY data into a topology (discussed later in this lesson). Load Topology Primitives (continued) Each primitive has a unique identifier. The NODE_ID column in the <topology_name>_NODE$ table, the EDGE_ID column in the <topology_name>_EDGE$ table, and the FACE_ID column in the <topology_name>_FACE$ table should all be loaded with positive integer values. The one exception to this rule is the single entry for the universal face in the <topology_name>_FACE$ table, whose FACE_ID is –1. The ID entries in each table must be unique in that table. For example, there can be only one node with NODE_ID=1 in the <topology_name>_NODE$ table. There can be a single edge with EDGE_ID=1 in the <topology_name>_EDGE$ table. The CREATE_FEATURE command, which loads SDO_GEOMETRY objects into a topology, is discussed further in the section titled “SDO_TOPO_MAP.CREATE_FEATURE.” Oracle Spatial 10g: Advanced
224
Example Topology (CITY_DATA)
N7 N21 N22 E2 N4 N4 N5 E26 N3 E25 N3 F9 F2 E3 F1 E4 N20 N6 N1 N2 E6 E7 E8 N16 N17 N18 N19 E21 F3 E19 F4 E17 F5 E15 F -1 E9 E10 E11 N15 N14 N13 N12 Example Topology (CITY_DATA) This is an example of a topology. The nodes, edges, and faces are labeled. For clarity, nodes begin with the letter N, edges begin with the letter E, and faces begin with the letter F. Arrows specify direction, which corresponds to the order in which the coordinates are specified. Details about how to populate the primitives in this example are discussed in the Oracle Database 10g: Spatial Topology Data Model online course. E22 F6 E20 F7 E18 F8 E16 E12 E13 E14 N8 N9 N10 N11 Oracle Spatial 10g: Advanced
225
Insert Universal Face Empty Topology: Example
Every topology must have an entry for its universal face in the <topology_name>_FACE$ table. Here is a sample INSERT statement for the universal face of an empty topology: If the topology contained primitives, the INSERT statement for the universal face would contain more information. INSERT INTO my_project_face$ VALUES (-1, NULL, SDO_LIST_TYPE(), SDO_LIST_TYPE(), NULL); Insert Universal Face Empty Topology: Example Every topology must have a universal face entry in the <topology_name>_FACE$ table. This slide demonstrates a sample INSERT statement for the universal face entry of an empty topology. The column definitions for the <topology_name>_FACE$ table are beyond the scope of this course. For more information, please refer to the Oracle Spatial Topology and Network Data Models 10g documentation, or the Oracle Database 10g: Spatial Topology Data Model online course. Oracle Spatial 10g: Advanced
226
Oracle Spatial Topology Data Model PL/SQL and Java APIs
The Topology Data Model includes Java and PL/SQL APIs to INSERT, UPDATE, and DELETE topological primitives. Oracle Spatial Topology and Network Data Models 10g: Documents PL/SQL API Usage notes of PL/SQL commands also mention equivalent Java methods Editing applications must use the Java or PL/SQL APIs to manage all the topology primitive editing operations. Add topological primitives Delete topological primitives Move topological primitives, and more… Oracle Spatial Topology Data Model PL/SQL and Java APIs In addition to the previous components of topology management, there is also a special set of APIs useful for updating topology data. The JAVA and PL/SQL APIs are for use by editing applications that modify topological primitives. All of the PL/SQL API commands are documented in the: Oracle Spatial Topology and Network Data Models 10g documentation. The PL/SQL Topology API function and procedure documentation also mentions equivalent Java methods. Applications must use the Java or PL/SQL APIs to manage all topological primitive editing operations. Oracle Spatial 10g: Advanced
227
Oracle Spatial Topology Data Model PL/SQL and Java APIs
The Java and PL/SQL APIs ensure consistency of: Topological primitives How topological primitives map to features Java API includes a TOPO_MAP class: ORACLE_HOME\md\lib\sdotopo.jar Java doc available: ORACLE_HOME\md\doc\sdotopo.zip Oracle Spatial Topology Data Model PL/SQL and Java APIs (continued) Using the Java or PL/SQL APIs ensures that the required consistency checks are done to keep the topology and topological features in a valid state with respect to nodes, edges, and faces. For example, if a road points to primitive edge E1, and a node N1 is inserted with the PL/SQL or Java API onto primitive E1 (splits E1) to create E1 and E2, the road feature gets “transparently” associated with E1 and E2. This type of primitive/feature consistency is maintained only if primitive edits are accomplished with the Oracle Spatial Topology APIs. The Java API includes a TOPO_MAP class. The sdotopo.jar file is located in: ORACLE_HOME\md\lib\sdotopo.jar Java doc is also available in: ORACLE_HOME\md\doc\sdotopo.zip Oracle Spatial 10g: Advanced
228
SDO_TOPO.INITIALIZE_METADATA
Call the SDO_TOPO.INITIALIZE_METADATA procedure after an initial bulk load of topological primitives: <topology_name>: Name of the topology whose metadata will be initialized Creates spatial indexes on the following SDO_GEOMETRY columns: <topology_name>_NODE$ (geometry) <topology_name>_EDGE$ (geometry) <topology_name>_FACE$ (geometry) SDO_TOPO.INITIALIZE_METADATA('<topology_name>'); Initialize Topology Metadata SDO_TOPO.INITIALIZE_METADATA should be called after the initial bulk load of topology primitives. The procedure SDO_TOPO.INITIALIZE_METADATA: Creates spatial indexes on the geometry columns in the NODE$, EDGE$ and FACE$ tables Oracle Spatial 10g: Advanced
229
SDO_TOPO.INITIALIZE_METADATA
Sets Oracle sequences to track max NODE_ID, EDGE_ID, and FACE_ID values: Sequence values used by Oracle when adding/modifying primitives through programmatic APIs Initialize Topology Metadata (continued) Initializes Oracle sequences for the NODE$, EDGE$, and FACE$ tables respectively. If SDO_TOPO.INITIALIZE_METADATA is called after an initial bulk load, each sequence is initialized with the highest ID value in its respective table. This ensures that no attempt is made to reuse the unique ID values in these tables when adding new primitives through the topology editing APIs. Oracle Spatial 10g: Advanced
230
SDO_TOPO.INITIALIZE_METADATA
If you have already performed a bulk load and run SDO_TOPO.INITIALIZE_METADATA and then want to perform a subsequent primitive bulk load: Ensure the area you are bulk loading to does not overlap the existing topology primitives Ensure the primitive ID values do not already exist Manually drop SDO_GEOMETRY spatial indexes Perform subsequent primitive bulk loads Rerun SDO_TOPO.INITIALIZE_METADATA Initialize Topology Metadata (continued) Earlier it was mentioned that once the topology editing APIs are used, bulk loads should no longer occur. This requirement can be carefully relaxed if the bulk load is in an area that does not overlap with existing topology primitives. For optimal performance, the recommended approach for additional bulk loads is: Ensure the topology primitives being loaded do not have the same ID values as existing topology primitives. Manually drop the spatial indexes on the SDO_GEOMETRY columns in the NODE$, EDGE$, and FACE$ tables. Perform additional bulk loads. Rerun SDO_TOPO.INITIALIZE_METADATA to re-create the spatial indexes and reset the Oracle sequences. Oracle Spatial 10g: Advanced
231
SDO_TOPO.INITIALIZE_METADATA: Example
Creates or re-creates required indexes on the geometry column in the NODE$, EDGE$, and FACE$ tables. Sets max NODE_ID, EDGE_ID, FACE_ID sequence values. SQL> EXECUTE SDO_TOPO.INITIALIZE_METADATA('CITY_DATA'); Initialize Topology Metadata: Example This is an example of calling SDO_TOPO.INITIALIZE_METADATA. This procedure should be called after an initial bulk load of topology primitives. It can be called after a subsequent bulk load of primitives. Oracle Spatial 10g: Advanced
232
Oracle Spatial 10g: Advanced 1-234
Break Point Oracle Spatial 10g: Advanced
233
Oracle Spatial 10g: Advanced 1-235
Spatial Feature Model Oracle Spatial 10g: Advanced
234
Oracle Spatial 10g: Advanced 1-236
Spatial Features Each of these represents a spatial feature. Using topology, each feature is modeled in terms of the topological elements (nodes, edges, and faces) it is composed of. California Main Street Current car location Spatial Features Spatial features can be real-world spatial objects. Examples of these features include roads, land boundaries such as cadastral (land parcel) boundaries and United States county boundaries, and electric utility cables. In a topology, each feature is modeled in terms of its basic topological elements: Nodes Edges Faces A spatial feature can be associated with many primitives, and a primitive can be associated with many spatial features. Oracle Spatial 10g: Advanced
235
Defining Spatial Features
Initially, topological primitives (nodes, edges, and faces) have no associated spatial features. A spatial feature is defined by its association with a set of topological primitive IDs. SDO_TOPO_GEOMETRY, a native Oracle data type, associates a spatial feature with a set of topological primitive IDs. Defining Spatial Features Initially, the topological primitives (the nodes, edges, and faces) are not associated with any spatial features. When a spatial feature is created, it is defined by a set of topological primitive IDs. SDO_TOPO_GEOMETRY, a native data type in the Oracle database, associates a spatial feature with the set of topological primitives it is composed of. Oracle Spatial 10g: Advanced
236
Defining Spatial Features
SDO_TOPO_GEOMETRY is similar in concept to SDO_GEOMETRY except for the following: SDO_TOPO_GEOMETRY does not explicitly store any coordinates. SDO_TOPO_GEOMETRY associates a spatial feature with the set of topological primitive IDs it is composed of. SDO_TOPO_GEOMETRY enables topological primitives to be shared across SDO_TOPO_GEOMETRY instances. Ordinary Oracle tables can have one or more SDO_TOPO_GEOMETRY columns. Defining Spatial Features (continued) A Spatial Topology feature layer is an SDO_TOPO_GEOMETRY column in an ordinary Oracle table. SDO_TOPO_GEOMETRY is a native data type that is shipped with the Oracle Spatial Topology Data Model. An SDO_TOPO_GEOMETRY layer is similar to an SDO_GEOMETRY layer. SDO_TOPO_GEOMETRY columns associate spatial features with topological primitives. Data modeling is also similar when working with SDO_TOPO_GEOMETRY columns. For normalized data models, store the SDO_TOPO_GEOMETRY column in an Oracle table whose other columns have a 1-1 relationship with the SDO_TOPO_GEOMETRY column. An SDO_TOPO_GEOMETRY layer is different from an SDO_GEOMETRY layer in that it does not explicitly store coordinates. Instead, it provides a mechanism to associate a spatial feature with its topological primitives (nodes, edges, faces). The SDO_TOPO_GEOMETRY data type enables multiple spatial features to share topological primitives. An ordinary Oracle table can have one or more SDO_TOPO_GEOMETRY columns. Oracle Spatial 10g: Advanced
237
Defining Spatial Features
Each SDO_TOPO_GEOMETRY column is also known as a feature layer. A topology can have multiple feature layers. Each feature layer has a unique ID in a topology. Defining Spatial Features (continued) A topology can contain many feature layers. For instance, a topology created for a town may include a parcel layer, a road layer, a utilities layer, a street sign layer, a wetlands layer, and so on. Each feature layer (or SDO_TOPO_GEOMETRY column) has a unique ID in the topology, also known as TG_LAYER_ID. Oracle Spatial 10g: Advanced
238
Oracle Spatial 10g: Advanced 1-240
Create a Feature Layer CREATE TABLE city_streets ( name VARCHAR2(25), feature SDO_TOPO_GEOMETRY); Create an ordinary Oracle table with an SDO_TOPO_GEOMETRY column. SDO_TOPO_GEOMETRY column is synonymous to a “Feature Layer.” An Oracle table can have multiple feature layers. Traditional data modeling concepts apply. Create a Feature Layer Initially, no features are associated with the topological primitives. First, create an ordinary Oracle table with an SDO_TOPO_GEOMETRY column (a feature layer). Traditional data model concepts apply. For a normalized data model, store the SDO_TOPO_GEOMETRY column in an Oracle table whose other columns have a 1-1 relationship with the SDO_TOPO_GEOMETRY column. Next, attribute values and the topological primitive IDs associated with each spatial feature are inserted into the table. Oracle Spatial 10g: Advanced
239
Oracle Spatial 10g: Advanced 1-241
SDO_TOPO_GEOMETRY SQL> DESCRIBE sdo_topo_geometry Name Null? Type TG_TYPE NUMBER TG_ID NUMBER TG_LAYER_ID NUMBER TOPOLOGY_ID NUMBER METHOD ------ MEMBER FUNCTION GET_GEOMETRY RETURNS SDO_GEOMETRY Member function GET_GEOMETRY returns an SDO_GEOMETRY representation of the spatial feature. SDO_TOPO_GEOMETRY The SDO_TOPO_GEOMETRY data type associates spatial features to topologic primitives. Each attribute of the SDO_TOPO_GEOMETRY type is described in the next slide. The SDO_TOPO_GEOMETRY type has several user-defined constructors that are discussed in an upcoming slide. The SDO_TOPO_GEOMETRY type also includes a method, GET_GEOMETRY(). The GET_GEOMETRY() method constructs an SDO_GEOMETRY representation from the SDO_TOPO_GEOMETRY topological primitive representation. Oracle Spatial 10g: Advanced
240
SDO_TOPO_GEOMETRY: Attributes
TG_TYPE: Type of spatial feature 1 = point or multipoint 2 = line string or multiline string 3 = polygon or multipolygon 4 = heterogeneous collection TG_ID: Unique feature ID Generated by Spatial when new features are added TG_LAYER_ID: Unique feature layer ID Unique numeric value associated with a feature layer in a topology Value is generated by Spatial when feature layer is registered TOPOLOGY_ID: Unique ID of the topology Value determined by Spatial when topology created SDO_TOPO_GEOMETRY: Attributes The SDO_TOPO_GEOMETRY has four attributes. TG_TYPE: This field holds information about the feature type. Types are defined as follows: 1 = (MULTI)POINT 2 = (MULTI)LINE 3 = (MULTI)POLYGON 4 = COLLECTION TG_ID: Unique feature ID assigned by Oracle when a feature is added to the topology. The value is unique to this feature layer. TG_LAYER_ID: Unique feature layer ID. Value was assigned when layer was registered with SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER (discussed in the next slide) TOPOLOGY_ID: Each schema in a database can have multiple topologies. Each topology has a unique ID assigned when SDO_TOPO.CREATE_TOPOLOGY is called. This set of fields is enough information to get a feature’s associated topological primitives. TG_LAYER_ID and TOPOLOGY_ID are stored in topology metadata. Oracle Spatial 10g: Advanced
241
Register a Feature Layer with a Topology
SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER Invoke once for each feature layer Associates a feature layer with a topology Adds metadata to topology metadata tables Creates a topology index for this feature layer CREATE VIEW privilege required in Oracle Spatial 10g Release 2 and beyond SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER( '<topology_name>', '<table_name>','<column_name>', '<topo_geometry_layer_type>', '<relation_table_storage>', <child_layer_id>); Register a Feature Layer with a Topology The SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER procedure associates a feature layer (specifically, the SDO_TOPO_GEOMETRY column) with a topology. The SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER is called once for each feature layer in the topology. When called, the ADD_TOPO_GEOMETRY_LAYER procedure: 1. Adds metadata to the USER_SDO_TOPO_METADATA and USER_SDO_TOPO_INFO metadata views (these views are discussed in an upcoming slide). 2. Creates a domain index for the feature layer. The index allows fast access to the individual features in the feature layer. In Oracle Database 10g Release 2, the CONNECT role privilege reduction feature removed the following privileges from the CONNECT role: CREATE CLUSTER CREATE DATABASE LINK CREATE SEQUENCE ALTER SESSION CREATE SYNONYM CREATE TABLE CREATE VIEW Because of this, users granted CONNECT and RESOURCE privileges also explicitly need to be granted the CREATE VIEW privilege to invoke the SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER. Oracle Spatial 10g: Advanced
242
Register a Feature Layer with a Topology
SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER parameters: <topology_name>: Name of the topology in which to register the feature layer <table_name>: Table that contains feature layer <column_name>: Column name of type SDO_TOPO_GEOMETRY <topo_geometry_layer_type>: Type of feature layer: POINT LINE POLYGON COLLECTION Register a Feature Layer with a Topology (continued) SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER registers feature layers with the topology. It should be called once for each SDO_TOPO_GEOMETRY column. The parameters for the SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER are: <topology_name>: The topology in which to register the feature layer <table_name>: The name of the table that contains the feature layer <column_name>: The name of the column of type SDO_TOPO_GEOMETRY <topo_geometry_layer_type>: The topology type of the feature layer: POINT LINE POLYGON COLLECTION Oracle Spatial 10g: Advanced
243
Register a Feature Layer with a Topology
<relation_table_storage>: Tablespace for RELATION$ partition (optional) <child_layer_id>: TG_LAYER_ID of level N-1 hierarchy layer Register a Feature Layer with a Topology (continued) Other parameters in SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER include: <relation_table_storage>: Optional tablespace for the feature layer partition that gets created after SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER is called. If not specified, the partition is created in the user’s default tablespace. <child_layer_id>: If layer being registered is part of a hierarchy, this parameter specifies the unique TG_LAYER_ID of the layer this layer is derived from. Note: TG_LAYER_ID is discussed further in the section on “Topology Metadata.” Oracle Spatial 10g: Advanced
244
SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER
BEGIN SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER('CITY_DATA', 'LAND_PARCELS', 'FEATURE', 'POLYGON'); 'TRAFFIC_SIGNS', 'FEATURE', 'POINT'); 'CITY_STREETS', 'FEATURE', 'LINE'); END; / Now these three layers are registered with the existing topology. TG_LAYER_ID, a unique ID generated for each feature layer, is stored in topology metadata: LAND_PARCELS: 1 TRAFFIC_SIGNS: 2 CITY_STREETS: 3 SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER When a feature layer is registered with a topology (by calling SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER), a unique ID called TG_LAYER_ID is assigned to the feature layer. Each feature layer in a topology has a unique TG_LAYER_ID. An Oracle sequence manages TG_LAYER_ID assignments within a topology. Oracle Spatial 10g: Advanced
245
Oracle Spatial 10g: Advanced 1-247
Topology Metadata The Oracle database maintains all topology metadata. SQL> DESCRIBE all_sdo_topo_info Name Type OWNER VARCHAR2(32) TOPOLOGY VARCHAR2(20) TOPOLOGY_ID NUMBER TOLERANCE NUMBER SRID NUMBER TABLE_SCHEMA VARCHAR2(64) TABLE_NAME VARCHAR2(64) COLUMN_NAME VARCHAR2(32) TG_LAYER_ID NUMBER TG_LAYER_TYPE VARCHAR2(10) TG_LAYER_LEVEL NUMBER CHILD_LAYER_ID NUMBER Topology Metadata The ALL_SDO_TOPO_INFO table contains information about the topology and layer features associated with the topology. The columns associated with ALL_SDO_TOPO_INFO are: OWNER: The schema name of the owner of the topology TOPOLOGY: The name of the topology TOPOLOGY_ID: A unique ID assigned to a topology when SDO_TOPO.CREATE_TOPOLOGY is called TOPOLOGY_TYPE: PLANAR or NETWORK TOLERANCE: Tolerance of the data SRID: Spatial Reference System (Coordinate System) ID TABLE_NAME: Name of the table that contains the feature layer COLUMN_NAME: Name of the feature layer column (of type sdo_topo_geometry) TG_LAYER_ID: Unique ID in the topology associated with the feature layer. Assigned when SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER is called. Oracle Spatial 10g: Advanced
246
Oracle Spatial 10g: Advanced 1-249
Topology Metadata Two sets of topology metadata views visible to each schema: *_SDO_TOPO_METADATA *_SDO_TOPO_INFO USER and ALL views are created: USER shows topology metadata owned by the current user. ALL shows topology metadata for all tables on which the current user has SELECT permission. Topology Metadata (continued) Two sets of views have been created that are visible to all users: *_SDO_TOPO_METADATA *_SDO_TOPO_INFO where * can be replaced with either of the following: USER ALL Both sets of views are completely maintained by the Oracle database. Oracle Spatial 10g: Advanced
247
Oracle Spatial 10g: Advanced 1-250
Topology Metadata Topology metadata views maintained by Oracle database Detailed metadata in *_SDO_TOPO_METADATA Subset in *_SDO_TOPO_INFO When writing generic applications, search against ALL views (not USER views) Topology Metadata (continued) The Oracle database also maintains: USER_SDO_TOPO_METADATA ALL_SDO_TOPO_METADATA USER_SDO_TOPO_INFO ALL_SDO_TOPO_INFO The difference between the USER and the ALL variants of both views is that the USER views show metadata owned by the current user, and the ALL views show topology metadata for all tables on which the current user has SELECT permission. The *_SDO_TOPO_INFO views are a subset of the *_SDO_TOPO_METADATA views. Oracle Spatial 10g: Advanced
248
Summary of Structures So Far
SDO_TOPO.CREATE_TOPOLOGY created: Three tables that get populated with topology primitives: <topology_name>_NODE$ <topology_name>_EDGE$ <topology_name>_FACE$ One table to maintain the transaction history for merges and splits of edges and faces <topology_name>_HISTORY$ Primitives are bulk loaded Create Oracle tables with SDO_TOPO_GEOMETRY columns (or feature layers) Summary of Structures So Far When SDO_TOPO.CREATE_TOPOLOGY is executed, the <topology_name>_NODE$, <topology_name>_EDGE$, <topology_name>_FACE$, and <topology_name>_HISTORY$ tables are all created. Then the primitives are bulk loaded into the NODE$, EDGE$, and FACE$ tables. Tables are created with SDO_TOPO_GEOMETRY columns, which are used to map features in the table to topology primitives stored in the database. Oracle Spatial 10g: Advanced
249
Summary of Structures So Far
For each feature layer, invoke SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER to register it with the topology: <topology_name>_RELATION$ table is created when first feature layer is registered. <topology_name>_RELATION$ manages mapping between features and topology primitives (many-to-many relationship). Oracle Spatial 10g: Advanced
250
<topology_name>_RELATION$
SQL> DESCRIBE city_data_relation$ Name Null? Type TG_LAYER_ID NOT NULL NUMBER TG_ID NOT NULL NUMBER TOPO_ID NOT NULL NUMBER TOPO_TYPE NOT NULL NUMBER TOPO_ATTRIBUTE VARCHAR2(100) RELATION$ table created when first feature layer is registered with the topology Manages mapping between features and topology primitives (many-to-many relationship) RELATION$ table is partitioned, one partition for each feature layer associated with the topology The tablespace for the partition can be specified when SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER is called <topology_name>_RELATION$ The <topology_name>_RELATION$ table maps features to their associated primitives in the following tables: <topology_name>_NODE$ <topology_name>_EDGE$ <topology_name>_FACE$ The relationship between spatial features to topological primitives is many-to-many. A spatial feature can be associated with many primitives, and a primitive can be associated with many features. The <topology_name>_RELATION$ table is nothing more than an association table to manage the many-to-many relationship. The <topology_name>_RELATION$ table is a partitioned table. One partition is created for each feature layer registered with the topology. The RELATION$ table is not created until the first feature layer is registered with the topology. You can control the tablespace of each partition with a parameter to the SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER procedure. Note: If the implicit use of Oracle table partitioning in the RELATION$ table is the only use of Oracle table partitioning in the Oracle instance, the purchase of the Oracle Partitioning option is not required. Oracle Spatial 10g: Advanced
251
<topology_name>_RELATION$
Association table: A mapping between features and topology primitives (many-to-many relationship). TG_LAYER_ID Unique ID associated with a feature layer Generated by Oracle Spatial when SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER is invoked TG_ID Unique ID associated with a feature Generated by Oracle Spatial when a new feature is created TOPO_ID Unique primitive ID (node_id, edge_id, face_id) TOPO_TYPE Type of primitive: 1 = NODE, 2 = EDGE, 3 = FACE TOPO_ATTRIBUTE Used internally by Oracle Spatial F E A T U R P R I M I T V E <topology_name>_RELATION$ (continued) <topology_name>_RELATION$ is an association table that maps features and topology primitives, a many-to-many relationship. A single feature can be associated with many primitives. A primitive can be associated with many features. The following uniquely identifies a feature: TG_LAYER_ID: Contains a unique ID associated with the layer in the topology. TG_ID: Unique to each feature in the layer. The following uniquely identifies a primitive: TOPO_ID: Represents the unique primitive ID of either a node, edge, or face TOPO_TYPE: The table associated with the primitive type: 1 – NODE$ 2 – EDGE$ 3 – FACE$ The TOPO_ATTRIBUTE column stores information in an internal format used only by Oracle Spatial Topology. Oracle Spatial 10g: Advanced
252
Mapping Between Features and Topology
LAND_PARCELS Table SDO_TOPO_GEOMETRY OWNER . Other attributes CITY_STREETS Table NAME <topology_name>_RELATION$ LAND_PARCELS(feature) Partition CITY_STREETS(feature) Partition <topology_name>_NODE$ <topology_name>_EDGE$ <topology_name>_FACE$ Mapping Between Features and Topology The RELATION$ table is an association table that manages the many-to-many relationship between features and topological primitives. The RELATION$ table is a partitioned table. Each new feature layer added with SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER creates a new partition in the RELATION$ association table. As topological primitives are modified using the Oracle Topology PL/SQL or Java APIs, the mapping between the features and their underlying topological primitives is automatically maintained. RELATION$ table maintained by Oracle Spatial when PL/SQL or Java API is used to modify topological primitives Oracle Spatial 10g: Advanced
253
Feature Layer Examples
Oracle Spatial 10g: Advanced
254
Feature Layer Example: Area Feature
N1 N2 N3 E1 E2 N7 E7 F2 E5 F1 E3 E6 E4 N4 N6 N5 A park is an example of an area feature. In this slide, the park is composed of faces F1 and F2. A linear feature, E5 (which may be a road) divides the park into two faces. E5 is not part of the park boundary. An Oracle table with park attribute columns would also have a column of type SDO_TOPO_GEOMETRY. Feature Layer Example: Area Feature This area feature example shows a park composed of faces F2 and F1. An edge primitive (E5) separates the two faces, but E5 is not part of the park boundary. E5 may represent several other features, for example, a road and a utility line. To store spatial features, create an ordinary Oracle table with an SDO_TOPO_GEOMETRY column (or feature layer). The table can contain other columns too. To maintain a normalized table, other columns in the table should have a 1-1 relationship with the SDO_TOPO_GEOMETRY column. After the feature layer is created and registered with the topology, the <topology_name>_RELATION$ table maintains the many-to-many relationship between spatial features and topological primitives. Oracle Spatial 10g: Advanced
255
Feature Layer Example: Linear Feature
A road is an example of a linear feature. In this slide, a road is composed of edges E1 and -E2. An Oracle table with columns that represent road attributes would also have a column of type SDO_TOPO_GEOMETRY. Feature Layer Example: Linear Feature This linear feature example shows a road composed of edges E1 and –E2. A node (N2) separates the two edges. The node may represent a point feature, but more likely represents where the two edges intersect. Oracle Spatial 10g: Advanced
256
Feature Layer Example: Point Feature
An information booth in a park is an example of a point feature: In this slide, the building/information booth is located at node N7. An Oracle table with columns that represent building attributes would also have a column of type SDO_TOPO_GEOMETRY. Feature Model Example: Point Feature This point feature example shows a building associated with the N7 node. Oracle Spatial 10g: Advanced
257
Feature Layer: Example
Initially, no features are associated with topological primitives. Add parks by associating topological primitive IDs with each park feature, for example: CREATE TABLE parks (park_id NUMBER, park_name VARCHAR2(25), feature SDO_TOPO_GEOMETRY); EXECUTE SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER( 'CITY_DATA', 'PARKS', 'FEATURE', 'POLYGON'); INSERT INTO parks (park_id, park_name, feature) VALUES ( 1781, 'Central Park', SDO_TOPO_GEOMETRY (List of primitive IDs and other info here)); Feature Layer: Example Initially, no features are associated with the topological primitives. A table called parks is created with a feature layer called feature. Next, park attributes (for example, ID, name, and so on) and the feature layer are populated with an INSERT statement. An SDO_TOPO_GEOMETRY constructor associates topological primitives with each park spatial feature. Oracle Spatial 10g: Advanced
258
Oracle Spatial 10g: Advanced 1-261
Topology Editing Oracle Spatial 10g: Advanced
259
Edits Occur in a Memory Cache TOPO_MAP Object
Primitives are loaded and modified in a cache. Used by both the PL/SQL and Java APIs. Efficient to create cache once, and make many primitive edits. Edits Occur in a Memory Cache TOPO_MAP Object The Oracle Spatial PL/SQL and Java APIs perform primitive edits in an in-memory cache. The in-memory cache is often referred to as a TOPO_MAP object or TOPO_MAP cache. The TOPO_MAP cache is used by both the PL/SQL and Java APIs. An explicitly created cache can persist through many topology edit commands. For example, if the requirement was to add two new nodes primitives: You first create a persistent TOPO_MAP cache Then you call SDO_TOPO_MAP.ADD_NODE to add the first node, and have the operation use the persistent cache Then call SDO_TOPO_MAP.ADD_NODE to add the second node, and have the operation use the same persistent cache Oracle Spatial 10g: Advanced
260
SDO_TOPO_MAP.CREATE_TOPO_MAP
'<topology_name>', '<topo_map_name>', <number_of_edges>, <number_of_nodes>, <number_of_faces>); Explicitly creates an empty TOPO_MAP cache TOPO_MAP cache is populated by SDO_TOPO_MAP.LOAD_TOPO_MAP SDO_TOPO_MAP.CREATE_TOPO_MAP SDO_TOPO_MAP.CREATE_TOPO_MAP creates an explicit in-memory TOPO_MAP cache. The TOPO_MAP cache is populated by SDO_TOPO_MAP.LOAD_TOPO_MAP, discussed in the slide “SDO_TOPO_MAP.LOAD_TOPO_MAP.” Oracle Spatial 10g: Advanced
261
SDO_TOPO_MAP.CREATE_TOPO_MAP Parameters
<topology_name> Name of the topology <topo_map_name> Name of the cache <number_of_edges> Number of edges estimated to be in cache at one time Default is 100 <number_of_nodes> Number of nodes estimated to be in cache at one time Default is 80 <number_of_faces> Number of faces estimated to be in cache at one time Default is 30 SDO_TOPO_MAP.CREATE_TOPO_MAP: Parameters <topology_name> Name of the topology <topo_map_name> Name of the TOPO_MAP cache to be created <number_of_edges> Number of edges estimated to be in the cache at one time Default is 100 <number_of_nodes> Number of nodes estimated to be in the cache at one time Default is 80 <number_of_faces> Number of faces estimated to be in the cache at one time Default is 30 Setting appropriate values for the number of nodes, edges, and faces can help avoid resizing the hash map size when any of the default values are exceeded. Hash map size is not the same as Java heap size discussed in an upcoming slide. Oracle Spatial 10g: Advanced
262
SDO_TOPO_MAP.LOAD_TOPO_MAP
Loads primitives for entire topology or a specified region into the TOPO_MAP cache Returns TRUE if successful, otherwise raises an exception Can be loaded as editable: Only one editable TOPO_MAP cache per Oracle session Multiple sessions with editable TOPO_MAPs are allowed The same primitive cannot be locked more than once in editable TOPO_MAP caches (across different sessions) Can be loaded as read only A session can have multiple read only TOPO_MAP caches No restrictions on overlapping primitives in read only TOPO_MAP caches SDO_TOPO_MAP.LOAD_TOPO_MAP This command loads primitives into an explicitly created TOPO_MAP cache. You can load a TOPO_MAP cache: As editable (allow_updates = TRUE) Only one editable TOPO_MAP cache can exist in an Oracle session. Primitives in an editable TOPO_MAP cache are locked across all Oracle sessions. Multiple editable TOPO_MAP caches can concurrently persist in different sessions, but primitives can only be locked in one session. As read only (allow_update=FALSE) Can have many read-only TOPO_MAP caches No restriction on overlap of loaded regions Oracle Spatial 10g: Advanced
263
SDO_TOPO_MAP.LOAD_TOPO_MAP
'<topo_map_name>', '<allow_updates>', '<build_indexes>') RETURN VARCHAR2; SDO_TOPO_MAP.LOAD_TOPO_MAP( '<topo_map_name>', <xmin>, <ymin>, <xmax>, <ymax>, '<allow_updates>', '<build_indexes>') RETURN VARCHAR2; Oracle Spatial 10g: Advanced
264
SDO_TOPO_MAP.LOAD_TOPO_MAP Parameters
Name of cache <xmin>,<ymin>,<xmax>,<ymax> Optional rectangular region of topology to be loaded If not specified, entire topology is loaded <allow_updates> TRUE (the default), makes the cache editable Only one editable TOPO_MAP cache per Oracle session TOPO_MAP caches in different Oracle sessions cannot lock same primitives FALSE makes the cache read-only SDO_TOPO_MAP.LOAD_TOPO_MAP Parameters <topo_map> Name of the TOPO_MAP to load <xmin>,<ymin>,<xmax>,<ymax> If specified, rectangular region to load If not specified, the entire topology is loaded into the TOPO_MAP cache <allow_updates> If TRUE (the default), makes the cache editable Only one editable cache per Oracle session The same primitive cannot be loaded into more than one editable TOPO_MAP cache If FALSE, TOPO_MAP cache is read only Oracle Spatial 10g: Advanced
265
SDO_TOPO_MAP.LOAD_TOPO_MAP Parameters
<build_indexes> TRUE (the default), builds an in-memory R-tree index on the cache. The in-memory R-tree index improves performance for many operations when large portions of a topology are loaded into TOPO_MAP cache. FALSE, in-memory R-tree index is not built SDO_TOPO_MAP.LOAD_TOPO_MAP Parameters (continued) The last parameter to describe for SDO_TOPO_MAP.LOAD_TOPO_MAP is: <build_indexes> If TRUE (the default), builds an in-memory R-tree index for the cache The in-memory R-tree index improves performance when large portions of the topology are loaded into cache. If FALSE, in-memory R-tree index is not built. Oracle Spatial 10g: Advanced
266
SDO_TOPO_MAP.LOAD_TOPO_MAP
A read-only TOPO_MAP cache loads primitives, but does not lock them. An updatable TOPO_MAP cache loads primitives and also locks them. Can edit only inside the specified rectangular region There may be locked primitives that cannot be edited directly Loaded primitives include: Any face that intersects the region Any edge that intersects the region Any node that intersects the region SDO_TOPO_MAP.LOAD_TOPO_MAP A read-only TOPO_MAP cache loads only topological primitives. An updatable TOPO_MAP loads and locks topological primitives. Every TOPO_MAP has a region associated with it. Updates are allowed only within the region. There may be primitives loaded and locked that cannot be updated directly, although changes to the topology within the update region may indirectly change them. Loaded (and optionally locked) primitives include: Any node, edge, or face that intersects the region Oracle Spatial 10g: Advanced
267
SDO_TOPO_MAP.LOAD_TOPO_MAP Memory Use
By default, the Oracle JVM (Java Virtual Machine) heap size is 256 MB in a PL/SQL session. Sometimes, users want to load very large TOPO_MAP caches. In Oracle Spatial 10g Release 2, there is a new function: In Oracle Spatial 10g Release 1, you create this function yourself. SDO_TOPO_MAP.SET_MAX_MEMORY_SIZE( bytes NUMBER ) SDO_TOPO_MAP.LOAD_TOPO_MAP Memory Usage If you plan to load very large TOPO_MAP caches, Oracle Spatial 10g Release 2 (when it is in the market) will have a new function: SDO_TOPO_MAP.SET_MAX_MEMORY_SIZE(bytes NUMBER) which sets the heap size of the default Oracle JVM in a PL/SQL session. The default is 256 MB if the function is not called in the session. Before Oracle Spatial 10g Release 2, you create the function yourself as follows: CREATE OR REPLACE PROCEDURE set_max_memory_size(bytes NUMBER) AS LANGUAGE JAVA NAME 'oracle.aurora.vm.OracleRuntime.setMaxMemorySize(long)'; Here is a sample call to the function: SQL> CALL set_max_memory_size( ); Oracle Spatial 10g: Advanced
268
SDO_TOPO_MAP.UPDATE_TOPO_MAP
Writes explicit TOPO_MAP cache edits into NODE$, EDGE$, FACE$, HISTORY$, and RELATION$ tables No database COMMIT Primitives must exist in the NODE$, EDGE$, and FACE$ tables before they can be associated with spatial features The TOPO_MAP cache remains editable No parameters because an Oracle session can have only one editable TOPO_MAP cache SDO_TOPO_MAP.UPDATE_TOPO_MAP Associating spatial features with topological primitives requires the primitives to exist in the NODE$, EDGE$ and FACE$ tables. Spatial features cannot be associated with primitives that exist only in a TOPO_MAP cache. The SDO_TOPO_MAP.UPDATE_TOPO_MAP procedure performs the following: Flushes edits made in the cache to the NODE$, EDGE$, FACE$, and HISTORY$ tables Synchronizes the RELATION$ table with all TOPO_MAP cache edits made to primitives associated with spatial features Does not perform a database COMMIT Preserves the TOPO_MAP cache as editable Oracle Spatial 10g: Advanced
269
SDO_TOPO_MAP.COMMIT_TOPO_MAP
Writes TOPO_MAP cache edits into NODE$, EDGE$, FACE$ tables RELATION$ and HISTORY$ tables are also updated Issues database COMMIT Primitives must exist in NODE$, EDGE$, FACE$ tables before they can be associated with a spatial feature The TOPO_MAP cache becomes read only No parameters because an Oracle session can have only one editable TOPO_MAP cache SDO_TOPO_MAP.COMMIT_TOPO_MAP Associating spatial features with topological primitives requires the primitives to exist in the NODE$, EDGE$, and FACE$ tables. Spatial features cannot be associated with primitives that exist only in a TOPO_MAP cache. The SDO_TOPO_MAP.COMMIT_TOPO_MAP procedure performs the following: Flushes edits made in the cache to the NODE$, EDGE$, FACE$, and HISTORY$ tables Synchronizes RELATION$ table with all TOPO_MAP cache edits made to primitives associated with spatial features Performs a database COMMIT Makes the editable TOPO_MAP cache read only Oracle Spatial 10g: Advanced
270
SDO_TOPO_MAP.ROLLBACK_TOPO_MAP
Discards all edits made in a TOPO_MAP cache for a transaction Issues database ROLLBACK Entire database transaction is rolled back too TOPO_MAP cache gets cleared, and becomes read-only No parameters, because an Oracle session can have only one editable TOPO_MAP cache SDO_TOPO_MAP.ROLLBACK_TOPO_MAP Rolls back all TOPO_MAP cache edits that occurred in the current transaction, and also issues a database ROLLBACK The editable TOPO_MAP cache gets cleared, and becomes read only. Oracle Spatial 10g: Advanced
271
SDO_TOPO_MAP.DROP_TOPO_MAP
SDO_TOPO_MAP.DROP_TOPO_MAP('<topo_map_name>'); Destroys the TOPO_MAP cache All pending edits in cache are discarded Issues database ROLLBACK SDO_TOPO_MAP.DROP_TOPO_MAP SDO_TOPO_MAP.DROP_TOPO_MAP: Drops an explicitly created TOPO_MAP cache If the TOPO_MAP caches was editable, all pending edits in current transaction are rolled back. Issues a database ROLLBACK too The only parameter in the function is: <topo_map_name>: Name of the explicitly created TOPO_MAP to drop Oracle Spatial 10g: Advanced
272
Some Topology API Editing Commands
Edits from the following APIs occur in a TOPO_MAP cache: SDO_TOPO_MAP.ADD_NODE SDO_TOPO_MAP.ADD_ISOLATED_NODE SDO_TOPO_MAP.ADD_EDGE SDO_TOPO_MAP.MOVE_NODE SDO_TOPO_MAP.MOVE_EDGE And more… Some Topology API Editing Commands All of the PL/SQL API commands are documented in the following documentation: Oracle Spatial Topology and Network Data Models 10g guide The PL/SQL Topology API function and procedure documentation also mentions equivalent Java methods. Applications must use the Java or PL/SQL APIs to manage all topological primitive editing operations. Using the Java or PL/SQL APIs ensures that the required consistency checks are done to keep the topology and topological features in a valid state with respect to nodes, edges, and faces. For example, if a road points to primitive edge E1, and a node N1 is inserted with the PL/SQL or Java API onto primitive E1 (splits E1) to create E1 and E2, the road feature transparently gets associated with E1 and E2. This type of primitive/feature consistency is maintained only if primitive edits are accomplished with the Oracle Spatial Topology APIs. Oracle Spatial 10g: Advanced
273
Oracle Spatial 10g: Advanced 1-276
Break Point Oracle Spatial 10g: Advanced
274
SDO_TOPO_MAP.CREATE_FEATURE
SDO_TOPO_MAP.CREATE_FEATURE is available starting with patch in Oracle Spatial 10g. Oracle Spatial 10g: Advanced
275
SDO_TOPO_MAP.CREATE_FEATURE: Signature to Convert SDO_GEOMETRY
<topology_name>, <table_name>, <column_name>, <geometry>) RETURNS SDO_TOPO_GEOMETRY This call signature: Converts an SDO_GEOMETRY feature into topological primitives Requires an explicitly created TOPO_MAP cache Reuses existing primitives Adds new primitives if necessary Primitives written to NODE$, EDGE$, and FACE$ tables by implicit UPDATE_TOPO_MAP, but does not COMMIT Returns an SDO_TOPO_GEOMETRY new feature constructor Constructor can be inserted into specified feature layer SDO_TOPO_MAP.CREATE_FEATURE (Signature to Convert SDO_GEOMETRY) This function has two signatures, the first being to convert an SDO_GEOMETRY feature into an SDO_TOPO_GEOMETRY feature. The first SDO_GEOMETRY signature is described below: Takes an SDO_GEOMETRY spatial feature as input and decomposes it into its topological primitives Re-uses existing primitives in the topology when possible Adds new primitives in the topology if necessary Requires an explicitly created editable TOPO_MAP cache Oracle Spatial 10g: Advanced
276
SDO_TOPO_MAP.CREATE_FEATURE Parameters (for Converting SDO_GEOMETRY)
<topology_name>: Name of the topology <table_name>: Name of table with the SDO_TOPO_GEOMETRY column <column_name>: Name of the SDO_TOPO_GEOMETRY column <geometry>: The SDO_GEOMETRY object to convert Together <topology_name>, <table_name>, and <column_name> are used to identify the feature layer for the returned constructor. Note: Do not call this function as part of an insert statement. Call the function, then insert the result in a separate statement. SDO_TOPO_MAP.CREATE_FEATURE: Parameters (for Converting SDO_GEOMETRY) <topology_name>: Name of the topology <table_name>: Name of the table that contains the SDO_TOPO_GEOMETRY column <column_name>: Name of the SDO_TOPO_GEOMETRY column <geometry>: SDO_GEOMETRY spatial feature that is to be decomposed into its topological primitives Together, <topology_name>, <table_name>, and <column_name> identify the feature layer information returned in the constructor. Note: This function cannot be used within an INSERT statement. Instead, insert the resulting SDO_TOPO_GEOMETRY object into a table after the SDO_TOPO.CREATE_FEATURE function has been called. Oracle Spatial 10g: Advanced
277
Putting It All Together
-- Deregister feature layers, if they were registered. -- Unioned_counties is a feature layer we will create in the next code example. EXECUTE SDO_TOPO.DELETE_TOPO_GEOMETRY_LAYER ('TEST_TOPOLOGY', 'UNIONED_COUNTIES', 'FEATURE'); EXECUTE SDO_TOPO.DELETE_TOPO_GEOMETRY_LAYER ('TEST_TOPOLOGY', 'COUNTIES_TOPO', 'FEATURE'); -- Drop the topology if it exists, then create the topology EXECUTE SDO_TOPO.DROP_TOPOLOGY ('TEST_TOPOLOGY'); EXECUTE SDO_TOPO.CREATE_TOPOLOGY ('TEST_TOPOLOGY', 0.05, 8307); -- Insert the universal face for an empty topology INSERT INTO test_topology_face$ (face_id, boundary_edge_id, island_edge_id_list, island_node_id_list, mbr_geometry) VALUES (-1, NULL, SDO_LIST_TYPE(), SDO_LIST_TYPE(), NULL); -- Create an Oracle table with a feature layer. -- Each feature will represent a county. DROP TABLE counties_topo; CREATE TABLE counties_topo (state_name VARCHAR2(30), county_name VARCHAR2(30), feature SDO_TOPO_GEOMETRY); Putting It All Together This is a comprehensive example that: Removes a pre-created topology from a schema, if it exists Creates a topology called TEST_TOPOLOGY Inserts the universal face. This is a very important, required step. Creates an Oracle table with a feature layer. This example continues on the next several pages. Some things to point out about this page: The following two lines de-register two feature layers from the TEST_TOPOLOGY. The following calls may raise an error the first time they are called, because the feature layers do not exist yet. These errors are OK. They are similar to the errors you get when you drop a table before creating a table, a very common practice. EXECUTE SDO_TOPO.DELETE_TOPO_GEOMETRY_LAYER ('TEST_TOPOLOGY', 'UNIONED_COUNTIES', 'FEATURE'); EXECUTE SDO_TOPO.DELETE_TOPO_GEOMETRY_LAYER ('TEST_TOPOLOGY', 'COUNTIES_TOPO', 'FEATURE'); Oracle Spatial 10g: Advanced
278
Putting It All Together
-- Register feature layer with topology EXECUTE SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER('TEST_TOPOLOGY', 'COUNTIES_TOPO', 'FEATURE', 'POLYGON'); -- Create updatable TOPO_MAP object and load the whole topology in cache. -- Since we just created the topology, the cache will be empty. EXECUTE SDO_TOPO_MAP.DROP_TOPO_MAP('my_topo_map_cache'); EXECUTE SDO_TOPO_MAP.CREATE_TOPO_MAP('test_topology', 'my_topo_map_cache'); EXECUTE SDO_TOPO_MAP.LOAD_TOPO_MAP('my_topo_map_cache', 'true'); DECLARE CURSOR c1 IS SELECT state, county, geom FROM geod_counties WHERE state_abrv IN ('NH','CT','ME','MA'); topo_geom SDO_TOPO_GEOMETRY; BEGIN -- Counties table contains an SDO_GEOMETRY column. Decompose the counties -- in the following states ('NH', 'CT', 'ME', 'MA') into topological primitives FOR r IN c1 LOOP topo_geom := SDO_TOPO_MAP.CREATE_FEATURE('TEST_TOPOLOGY', 'COUNTIES_TOPO', 'FEATURE', r.geom); -- Associate topological primitives with features INSERT INTO counties_topo (state_name, county_name, feature) VALUES ( r.state, r.county, topo_geom); END LOOP; END; / Putting It All Together (continued) Continuing the previous page: If the feature layers did exist, they must be de-registered before the SDO_TOPO_MAP.DROP_TOPOLOGY call in the example. Once again, the SDO_TOPO_MAP.DROP_TOPOLOGY is being called right before a SDO_TOPO_MAP.CREATE_TOPOLOGY (very common practice). Next, this example: Registers the feature layer with TEST_TOPOLOGY Creates an explicit TOPO_MAP cache. Loads the entire topology into the TOPO_MAP cache as editable. In this example, an empty editable TOPO_MAP cache is established. Opens a cursor to select all of the counties in ('NH', 'CT', 'ME', 'MA'). Oracle Spatial 10g: Advanced
279
Putting It All Together
-- Commit topology changes. EXECUTE SDO_TOPO_MAP.COMMIT_TOPO_MAP; EXECUTE SDO_TOPO_MAP.DROP_TOPO_MAP ('my_topo_map_cache'); -- Check how many counties were converted SELECT COUNT(*) FROM counties_topo; -- After an initial bulk load into an empty topology, initialize_metadata EXECUTE SDO_TOPO.INITIALIZE_METADATA ('TEST_TOPOLOGY'); Putting It All Together (continued) Finally, this example: Fetches all of the counties in ('NH', 'CT', 'ME', 'MA') which are stored as SDO_GEOMETRY objects. Calls SDO_TOPO_MAP.CREATE_FEATURE to convert all the fetched counties into their respective topological primitives. 48 counties are converted. Results are stored in the COUNTIES_TOPO(FEATURE) feature layer using a separate insert statement (you cannot use SDO_TOPO_MAP.CREATE_FEATURE directly in the insert statement). Commits the transaction. Destroys the explicitly created TOPO_MAP cache. The number of counties converted is verified by counting the rows in the COUNTIES_TOPO table. Topology metadata is initialized after the bulk load performed in this example. Topology metadata is initialized by calling SDO_TOPO.INTIALIZE_METADATA. Oracle Spatial 10g: Advanced
280
SDO_TOPO_MAP.CREATE_FEATURE (Signature to Convert SDO_GEOMETRY)
Never do this: INSERT into COUNTIES_TOPO (state_name, county_name, feature) SELECT state, county, SDO_TOPO_MAP.CREATE_FEATURE('TEST_TOPOLOGY', 'COUNTIES_TOPO', 'FEATURE', geom) FROM geod_counties WHERE state_abrv IN ('NH', 'CT', 'ME', 'MA'); Never Do This: SDO_TOPO_MAP.CREATE_FEATURE (Signature to Convert SDO_GEOMETRY) You should never call SDO_TOPO_MAP.CREATE_FEATURE with the signature that converts SDO_GEOMETRY objects into primitives in an INSERT INTO SELECT as shown in the slide. Instead, set a variable to the result of SDO_TOPO_MAP.CREATE_FEATURE, and use the variable in the INSERT statement (example in the next slide). The reason for this is discussed in the Oracle Database Application Developer’s Guide – Fundamentals 10g Release 1, in the chapter titled “Using Procedures and Packages” and the “Calling Stored Functions from SQL Expressions” section. Under the “Controlling Side Effects” section, the following is stated with regards to purity (side effects): A subprogram called from a query (SELECT) statement or from a parallelized DML statement may not execute a DML statement or otherwise modify the database. Oracle Spatial 10g: Advanced
281
SDO_TOPO_MAP.CREATE_FEATURE (Signature to Convert SDO_GEOMETRY)
Do this instead: DECLARE CURSOR c1 IS SELECT state, county, geom FROM geod_counties WHERE state_abrv IN ('NH','CT','ME','MA'); topo_geom SDO_TOPO_GEOMETRY; BEGIN -- Decompose the SDO_GEOMETRY counties in the following states -- into topological primitives: ('NH', 'CT', 'ME', 'MA') FOR r IN c1 LOOP topo_geom := SDO_TOPO_MAP.CREATE_FEATURE('TEST_TOPOLOGY', 'COUNTIES_TOPO', 'FEATURE', r.geom); -- Associate topological primitives with features INSERT INTO counties_topo (state_name, county_name, feature) VALUES ( r.state, r.county, topo_geom); END LOOP; END; / Do This Instead: SDO_TOPO_MAP.CREATE_FEATURE (Signature to Convert SDO_GEOMETRY) This was previously demonstrated in the “Putting It All Together” example. You should never call SDO_TOPO_MAP.CREATE_FEATURE with the signature that converts SDO_GEOMETRY objects into primitives in an INSERT INTO SELECT statement as shown in the previous slide. Instead, you should set a variable to the result of SDO_TOPO_MAP.CREATE_FEATURE, and use the variable in the INSERT statement. Oracle Spatial 10g: Advanced
282
Hierarchical Feature Model
Oracle Spatial 10g: Advanced
283
Hierarchical Feature Model: Concepts
This is a model to build feature layers based on other feature layers. Level 0 features are derived from topological primitives (nodes, edges, faces): Feature layers derived from level 0 are level 1. Feature layers derived from level 1 are level 2. And so on . . . Feature layers at level N are always based on a single feature layer at level N–1. Hierarchical Feature Mode: Concepts The Oracle Spatial Topology Data Model includes a hierarchical feature model, where a feature layer can be built from lower level features in the hierarchy. By default, level 0 spatial features point to the nodes, edges, and faces that the features are composed of. Features layers derived from level 0 spatial features are at level 1 feature layers. Feature layers derived from level 1 features are at level 2 feature layers. And so on … Feature layers at level N are always based on a single feature layer at level N–1. Therefore, the value of TG_LAYER_ID for every feature in the feature layer is the same. Oracle Spatial 10g: Advanced
284
Hierarchical Feature Model: Example
Parcel features are stored in a level 0 feature layer Each parcel is derived from topological primitives (faces). Neighborhood features are stored in a level 1 feature layer: Each neighborhood is derived from a list of parcels. School District features are stored in a level 2 feature layer: Each school district is derived from a list of neighborhoods. Hierarchical Feature Model: Example This is a hierarchical feature model example. In a topology, there is table called PARCELS with an SDO_TOPO_GEOMETRY column (or feature layer). Each parcel feature is associated with a list of primitive IDs. Parcel features are stored in a level 0 feature layer. The NEIGHBORHOODS table also has an SDO_TOPO_GEOMETRY column (or feature layer). But instead of associating neighborhood features with a list of primitive IDs, each neighborhood feature is associated with a set of parcel feature IDs. Neighborhood features are stored in a level 1 feature layer. The SCHOOL DISTRICTS table also has an SDO_TOPO_GEOMETRY column (or feature layer). But instead of associating school district features with a list of primitive IDs, each school district feature is associated with a set of neighborhood feature IDs. School district features are stored in a level 2 feature layer. If the list of feature IDs (or primitive IDs if the feature layer changed is a level 0 feature layer) associated with a feature in a hierarchy is modified, all derived features at higher levels in the hierarchy automatically reflect the change. Oracle Spatial 10g: Advanced
285
Hierarchical Feature Model
For feature layers with level > 0: Instead of deriving features from topological primitives, features are derived from a list of features in another feature layer. The RELATION$ association table maintains the mapping. The level N layer changes transparently propagate to the layers derived from it (layers with level > N). The level N–1 features cannot be deleted if there are dependent features in a layer with level >= N. Hierarchical Feature Model For feature layers at levels greater than 0: Instead of deriving spatial features from topological primitives, features are derived from a set of features in another feature layer. The <topology_name>_RELATION$ table maintains the mapping between features in the hierarchy, all the way down to topological primitives. Changes to lower level features propagate automatically up the hierarchy (all features that are derived from a changed feature automatically incorporate the change). The hierarchical model maintains integrity on hierarchical features. Rows in a level N–1 feature layer cannot be deleted if derived features exist in the layer with level >= N. Oracle Spatial 10g: Advanced
286
Registering a Hierarchical Feature Layer with a Topology
SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER( '<topology_name>', '<table_name>','<column_name>', '<topo_geometry_layer_type>', '<relation_table_storage>', <child_layer_id>); SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER Similar to registering a nonhierarchical layer <child_layer_id> parameter used to register a hierarchical feature layer Value is the TG_LAYER_ID of level N-1 hierarchy layer Determine TG_LAYER_ID by selecting it from ALL_SDO_TOPO_INFO Registering a Hierarchical Feature Layer with a Topology The SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER procedure associates a feature layer (specifically, the SDO_TOPO_GEOMETRY column) with a topology. The difference when calling SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER for a hierarchical feature layer is that the <child_layer_id> is used. This is the TG_LAYER_ID of the lower-level feature layer that this new feature layer is built from. The TG_LAYER_ID is retrieved by selecting from the ALL_SDO_TOPO_INFO view, specifying the relevant information to select the correct TG_LAYER_ID (see example in the forthcoming slide “Putting It All Together”). Oracle Spatial 10g: Advanced
287
SDO_TOPO_MAP.CREATE_FEATURE (Signature to Build Hierarchical Features)
<topology_name>, <table_name>, <column_name>, <dml_condition>) RETURNS SDO_TOPO_GEOMETRY This signature groups a set of level N-1 features into a level N feature: Level 0 features point to topology primitives. Level 1 features point to a set of level 0 features. And so on . . . Level N features do not include coincident edges of level N-1 features. Does not use a TOPO_MAP cache. SDO_TOPO_MAP.CREATE_FEATURE (Signature to Build Hierarchical Features) This function has two signatures: 1. The signature that groups a set of level N-1 features into a level N feature is described below: Generates the set of features to group by the execution of a DML condition against the table that contains the Level N-1 features. Level N features do not include coincident edges of level N-1 features. For example: Assume parcel 1 is associated with FACE_ID 1 and parcel 2 is associated with FACE_ID 2. Also assume face 1 and face 2 are adjacent to each other. The hierarchical feature, neighborhood, made up of parcels 1 and 2, will dissolve adjacent edges between the parcels. The resulting neighborhood hierarchical feature is equivalent to the topological union of parcel 1 and parcel 2. The result is generated without having to perform a topological union operation. Because this call does not add any new primitives to the topology, this signature of SDO_TOPO_MAP.CREATE_FEATURE does not use a TOPO_MAP cache. Oracle Spatial 10g: Advanced
288
Signature to Build Hierarchical Features
The SDO_TOPO_MAP.CREATE_FEATURE returns an SDO_TOPO_GEOMETRY new feature constructor. Constructor ready for INSERT into specified feature layer SDO_TOPO_MAP.CREATE_FEATURE (Signature to Build Hierarchical Features) Continuing from the previous page: Returns an SDO_TOPO_GEOMETRY new feature constructor, ready to insert into a feature layer. When the feature is inserted into the new feature layer, the hierarchy association is written to the RELATION$ table, but not committed. The other CREATE_FEATURE signature to convert an SDO_GEOMETRY feature into an SDO_TOPO_GEOMETRY feature was discussed previously in the slide titled “Signature to Convert SDO_GEOMETRY.” Oracle Spatial 10g: Advanced
289
Oracle Spatial 10g: Advanced 1-293
SDO_TOPO_MAP.CREATE_FEATURE (Parameters to Build a Hierarchical Feature) <topology_name> Name of the topology <table_name> Name of the table with the SDO_TOPO_GEOMETRY column <column_name> Name of the SDO_TOPO_GEOMETRY column <dml_condition> DML condition applied to feature table at level N-1 DML condition determines which level N-1 features are grouped to generate the level N feature. Level N features do not include coincident edges of level N-1 features. SDO_TOPO_MAP.CREATE_FEATURE: (Parameters to Build a Hierarchical Feature) <topology_name>: Name of the topology <table_name>: Name of the table that contains the SDO_TOPO_GEOMETRY column <column_name>: Name of the SDO_TOPO_GEOMETRY column <dml_condition>: DML condition to apply to the table that contains the N-1 feature layer The set of features that result from the DML execution will be grouped into a level N hierarchical feature. Level N features will not include coincident edges of level N-1 features. Oracle Spatial 10g: Advanced
290
Putting It All Together
exec sdo_topo.delete_topo_geometry_layer('TEST_TOPOLOGY', 'UNIONED_COUNTIES', 'FEATURE'); -- unioned_counties(feature) is a hierarchy layer of counties_topo(feature). -- Each feature groups a state’s counties. DROP TABLE unioned_counties; CREATE TABLE unioned_counties (state_name VARCHAR2(30), feature SDO_TOPO_GEOMETRY); -- Register hierarchical feature layer with topology DECLARE child_layer_id_v NUMBER; BEGIN -- This select statement helps populate the -- child_layer_id parameter of SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER. SELECT tg_layer_id INTO child_layer_id_v FROM all_sdo_topo_info WHERE OWNER = 'TEST_TOPO' Replace TEST_TOPO with correct topology owner AND TOPOLOGY = 'TEST_TOPOLOGY' AND TABLE_SCHEMA = 'TEST_TOPO' Replace TEST_TOPO with correct table owner AND TABLE_NAME = 'COUNTIES_TOPO' AND COLUMN_NAME = 'FEATURE'; -- Since unioned_counties is a hierarchy layer, need to specify the child_layer_id parameter. SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER('TEST_TOPOLOGY', 'UNIONED_COUNTIES', 'FEATURE', 'POLYGON', CHILD_LAYER_ID => child_layer_id_v); END; / Putting It All Together This example builds on the previous code example: Creates an Oracle table with a feature layer called UNIONED_COUNTIES. UNIONED_COUNTIES will contain a hierarchical feature layer that unions sets of counties features from the COUNTIES table. Registers the hierarchical feature layer with TEST_TOPOLOGY. Registering hierarchical features layers requires supplying the CHILD_LAYER_ID parameter to SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER. CHILD_LAYER_ID is the unique TG_LAYER_ID of the feature layer the registering feature layer is derived from. A sample SQL statement is supplied that demonstrates how to query ALL_SDO_TOPO_INFO to get the CHILD_LAYER_ID value. Example continues on the next slide. Oracle Spatial 10g: Advanced
291
Putting It All Together
-- Insert the hierarchical feature that groups all the counties in Connecticut -- Internally, state_name='Connecticut' is added when SELECTing features from the -- COUNTIES_TOPO layer INSERT INTO unioned_counties (state_name, feature) VALUES ('Connecticut', SDO_TOPO_MAP.CREATE_FEATURE ('TEST_TOPOLOGY', 'UNIONED_COUNTIES', 'FEATURE', 'state_name = ''Connecticut''')); -- Insert the hierarchical feature that groups all the counties in Maine -- Internally, state_name='Maine' is added when SELECTing features from the ('Maine', 'state_name = ''Maine''')); -- Select the SDO_GEOMETRY representation SET PAGESIZE 1000 SELECT a.feature.get_geometry() FROM unioned_counties a WHERE a.state_name = 'Maine'; Putting It All Together (continued) Continuing this example: SDO_TOPO_MAP.CREATE_FEATURE returns a SDO_TOPO_GEOMETRY new feature constructor. There are two INSERT statements in the example. One INSERT statement creates a hierarchical feature for all the counties in the state of Connecticut. One INSERT statement creates a hierarchical feature for all the counties in the state of Maine. A call to GET_GEOMETRY() method of the hierarchical feature returns the SDO_GEOMETRY representation of the feature. Adjacent county boundaries in the hierarchical feature are dissolved. Oracle Spatial 10g: Advanced
292
<topology_name>_RELATION$ in a Hierarchy
Association table - mapping between parent features and child features (many to many relationship) TG_LAYER_ID Unique ID associated with a feature layer Generated by Oracle when SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER is invoked TG_ID Unique ID associated with a feature Generated by Oracle when a new feature is created TOPO_ID TG_LAYER_ID of child feature TOPO_TYPE TG_ID of child feature TOPO_ATTRIBUTE Used internally by Oracle Spatial F E A T U R P A R E N T F E A T U R C H I L D <topology_name>_RELATION$ in a Hierarchy <topology_name>_RELATION$ in a hierarchy is an association table that maps parent features child features, a many to many relationship. A single parent feature can be associated with many child features. A child feature can be associated with many parent features. The following uniquely identifies a feature: TG_LAYER_ID – Contains a unique ID associated with the layer in the topology. TG_ID – Unique to each feature in the layer The following uniquely identifies a lower level feature: TOPO_ID – Represents the TG_LAYER_ID of a child feature TOPO_TYPE – Represents the unique TG_ID of the child feature The TOPO_ATTRIBUTE column stores information in an internal format used only by Oracle Spatial Topology. Oracle Spatial 10g: Advanced
293
Topology Data Model Spatial Queries
Oracle Spatial 10g: Advanced
294
SDO_TOPO_GEOMETRY: GET_GEOMETRY Member Method
Example: Return the SDO_GEOMETRY object representation of a FEATURE COUNTIES_TOPO(FEATURE) is of type SDO_TOPO_GEOMETRY Note: When accessing an attribute or member method of an object, the Oracle database requires the use of a table alias. In this example, the COUNTIES_TOPO table is aliased to a. SELECT a.county_name, a.feature.get_geometry() FROM counties_topo a WHERE a.county_name = 'Kennebec' and a.state_name = 'Maine'; SDO_TOPO_GEOMETRY: GET_GEOMETRY Member Method This example shows GET_GEOMETRY() returning the SDO_GEOMETRY spatial feature representation of the SDO_TOPO_GEOMETRY spatial feature. Similar to requirements when accessing any attribute within an object, the GET_GEOMETRY() method also requires aliasing the table name specified in the FROM clause. In this example, the table named COUNTIES_TOPO was aliased to a. The example in this slide returns the COUNTY_NAME and the SDO_GEOMETRY representation for Kennebec County in the COUNTIES_TOPO table. Oracle Spatial 10g: Advanced
295
Operators with SDO_TOPO_GEOMETRY
The Oracle Spatial operators supporting the SDO_TOPO_GEOMETRY type are: SDO_FILTER SDO_ANYINTERACT SDO_COVERS SDO_COVEREDBY SDO_CONTAINS SDO_INSIDE SDO_ON SDO_EQUAL SDO_OVERLAPBDYINTERSECT SDO_OVERLAPBDYDISJOINT SDO_OVERLAPS SDO_TOUCH Operators with SDO_TOPO_GEOMETRY Many Spatial operators support the SDO_TOPO_GEOMETRY data type. The operators that support SDO_TOPO_GEOMETRY include SDO_FILTER and all of the named mask operators. Operators not currently supported by the SDO_TOPO_GEOMETRY data type include: SDO_RELATE (equivalent functionality provided through named mask operators) SDO_NN SDO_WITHIN_DISTANCE Oracle Spatial 10g: Advanced
296
Operators with SDO_TOPO_GEOMETRY
SDO_FILTER ( <feature_layer>, <query_window> ) = 'TRUE' <feature_layer>: SDO_TOPO_GEOMETRY column in a table Search layer <query_window> SDO_GEOMETRY OR SDO_TOPO_GEOMETRY SDO_MASK ( <feature_layer>, <query_window> ) = 'TRUE' Operators with SDO_TOPO_GEOMETRY (continued) The Oracle Spatial operators return rows in a feature layer that have the specified interaction with the query window. SDO_FILTER returns data based on whether the feature in the layer is likely to have an interaction with the query window (using a query window approximation). The named mask operators return exact results based on the mask specified. For more information, please see the Oracle Spatial User’s Guide and Reference 10g. The query window can be specified using either an SDO_TOPO_GEOMETRY value from a table or an SDO_GEOMETRY value (either from a table or as a constructor). Oracle Spatial 10g: Advanced
297
SDO_FILTER with SDO_TOPO_GEOMETRY Query Window
Finds all of the counties likely to have an interaction with a county named “Kennebec”: Uses SDO_TOPO_GEOMETRY as the query window Uses SDO_TOPO_GEOMETRY as the feature layer Note: When using an SDO_TOPO_GEOMETRY query window and an SDO_TOPO_GEOMETRY feature layer, using SDO_FILTER is equivalent to using SDO_ANYINTERACT. SELECT /*+ ordered */ d.county_name FROM counties_topo c, counties_topo d WHERE c.county_name = 'Kennebec' AND c.state_name = 'Maine' AND SDO_FILTER(d.feature, c.feature) = 'TRUE'; SDO_FILTER with SDO_TOPO_GEOMETRY Query Window This example shows the use of SDO_FILTER with an SDO_TOPO_GEOMETRY feature layer and an SDO_TOPO_GEOMETRY query window. All of the features that are likely to interact with SDO_TOPO_GEOMETRY feature query window are returned. Oracle Spatial 10g: Advanced
298
SDO_FILTER with SDO_GEOMETRY Query Window
Finds all of the counties likely to have an interaction with the specified query window SELECT county_name FROM counties_topo WHERE SDO_FILTER (feature, sdo_geometry(2003,8307,null, sdo_elem_info_array(1,1003,3), sdo_ordinate_array(-71.5,44, -70.5,46))) = 'TRUE'; Uses SDO_GEOMETRY as the query window Uses SDO_TOPO_GEOMETRY as the feature layer SDO_FILTER with SDO_TOPO_GEOMETRY Query Window This example shows the use of SDO_FILTER with an SDO_TOPO_GEOMETRY feature layer and an SDO_GEOMETRY query window. All of the features that are likely to interact with the SDO_GEOMETRY query window (based on the R-tree approximation of the query window) are returned. Note: SDO_FILTER operations may return different results based on SDO_TOPO_GEOMETRY or SDO_GEOMETRY query windows due to differing SDO_FILTER implementations Oracle Spatial 10g: Advanced
299
SDO_MASK Operators with SDO_TOPO_GEOMETRY Query Window
Find all of the counties that touch Kennebec County in Maine: SELECT /*+ ordered */ d.county_name FROM counties_topo c, counties_topo d WHERE c.county_name = 'Kennebec' AND c.state_name = 'Maine' AND sdo_touch(d.feature, c.feature) = 'TRUE'; SDO_MASK Operators with SDO_TOPO_GEOMETRY Query Window All of the Oracle Spatial named mask operators work with SDO_TOPO_GEOMETRY objects. The operators work the same as an Oracle Spatial SDO_RELATE operator with the named mask specified. In this case, SDO_TOUCH is specified with an SDO_TOPO_GEOMETRY query window. It returns rows associated with SDO_TOPO_GEOMETRY features that have any interaction with the query window, specified using an SDO_TOPO_GEOMETRY feature from the COUNTIES_TOPO table. Uses SDO_TOPO_GEOMETRY as the query window Uses SDO_TOPO_GEOMETRY as the feature layer Oracle Spatial 10g: Advanced
300
SDO_MASK Operators with SDO_GEOMETRY Query Window
Find all of the counties that have any interaction with the SDO_GEOMETRY query window. Uses SDO_GEOMETRY as the query window Uses SDO_TOPO_GEOMETRY as the feature layer Note: All named mask operations will return exact results regardless of the query window type (SDO_TOPO_GEOMETRY or SDO_GEOMETRY). SELECT county_name FROM counties_topo c WHERE SDO_ANYINTERACT(c.feature, SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY(-71.5,44, -70.5,44, -70.5,46, -71.5,46, -71.5,44))) = 'TRUE'; SDO_MASK Operators with SDO_GEOMETRY Query Window The Oracle Spatial operator SDO_ANYINTERACT works with SDO_TOPO_GEOMETRY objects. It is similar to an Oracle Spatial SDO_RELATE operator with the ANYINTERACT mask specified. SDO_ANYINTERACT works with the SDO_GEOMETRY type. It returns rows associated with a feature layer that have any interaction with the query window. The query window can be specified with either an SDO_TOPO_GEOMETRY value from a table or an SDO_GEOMETRY value (either from a table or as a constructor). Oracle Spatial 10g: Advanced
301
Sharing a Topology Among Multiple Users (Cross-Schema Considerations)
Oracle Spatial 10g: Advanced
302
Sharing a Topology Between Oracle Users
Only the topology owner can: Create the topology SDO_TOPO.CREATE_TOPOLOGY Drop the topology SDO_TOPO.DROP_TOPOLOGY Initialize metadata SDO_TOPO.INITIALIZE_METADATA Register feature layers (can specify OWNER.TABLE) SDO_TOPO.ADD_TOPO_GEOMETRY_LAYER Deregister feature layers SDO_TOPO.DELETE_TOPO_GEOMETRY_LAYER Sharing a Topology Between Oracle Users As the topology owner, you must perform certain topology operations. Only you can create or drop a topology. You must initialize the topology metadata and register or deregister the feature layers in the topology. Oracle Spatial 10g: Advanced
303
Sharing a Topology Between Oracle Users
In order to share a topology between Oracle users, privileges may need to granted For read access to a topology named p3, the topology owner has to grant these privileges to a user (named b): GRANT SELECT ON p3_node$ TO b; GRANT SELECT ON p3_edge$ TO b; GRANT SELECT ON p3_face$ TO b; GRANT SELECT ON p3_relation$ TO b; Sharing a Topology Between Oracle Users (continued) For read access, the privileges above must be granted to each user requiring write access to the topology. Oracle Spatial 10g: Advanced
304
Sharing a Topology Between Oracle Users
For write access to a topology named p3, the topology owner has to grant these privileges to a user (named b): GRANT INSERT,SELECT,UPDATE ON p3_node$ TO b; GRANT INSERT,SELECT,UPDATE ON p3_edge$ TO b; GRANT INSERT,SELECT,UPDATE ON p3_face$ TO b; GRANT INSERT,SELECT,UPDATE ON p3_relation$ TO b; GRANT SELECT ON p3_node_s TO b; GRANT SELECT ON p3_edge_s TO b; GRANT SELECT ON p3_face_s TO b; Sharing a Topology Between Oracle Users (continued) For write access, the privileges above must be granted to each user requiring write access to the topology. Oracle Spatial 10g: Advanced
305
Sharing Feature Layers Between Oracle Users
The owner of the topology needs to grant feature layer users appropriate privileges: SELECT privilege may be required on the NODE$, EDGE$, and FACE$ tables: -- Read access GRANT SELECT ON p3_relation$ TO d; -- Write access GRANT INSERT,SELECT,UPDATE ON p3_relation$ TO d; GRANT SELECT ON p3_node$ TO d; GRANT SELECT ON p3_edge$ TO d; GRANT SELECT ON p3_face$ TO d; Sharing Feature Layers Between Oracle Users If a user accesses the feature layer (SDO_TOPO_GEOMETRY column in the table) then the topology owner also needs to grant appropriate privileges to the user. For read or write access to the feature layer, read access may be required to the node, edge, and face tables. For instance, if you want to instantiate the SDO_GEOMETRY associated with a feature by using the GET_GEOMETRY() member function, access to the NODE$, EDGE$, and/or FACE$ tables is required. Oracle Spatial 10g: Advanced
306
Sharing Feature Layers Between Oracle Users
The owner of the feature table needs to grant appropriate privileges to other users: -- Access to topology owner before the topology -- owner registers the feature layer GRANT SELECT,INDEX ON city_streets TO topo_owner; -- Read access to user d GRANT SELECT ON city_streets TO d; -- Write access to user d GRANT INSERT,SELECT,UPDATE ON city_streets TO d; Sharing Feature Layers Between Oracle Users (continued) The owner of the feature table needs to grant appropriate privileges to users who access the feature table. Oracle Spatial 10g: Advanced
307
Oracle Spatial 10g Release 2 New Features
Oracle Spatial 10g: Advanced
308
Oracle Spatial 10g Release 2 New Topology Data Model Features
SDO_TOPO_MAP.ADD_LINEAR_GEOMETRY Adds one or more edges for a specified line string SDO_TOPO_MAP.ADD_POINT_GEOMETRY Adds a node representing a specified point SDO_TOPO_MAP.ADD_POLYGON_GEOMETRY Adds one or more faces for a specified polygon SDO_TOPO_MAP.CREATE_FEATURE Creates a feature from a Spatial geometry SDO_TOPO_MAP.LOAD_TOPO_MAP Available as a procedure Use when you do not need to know which topological elements were loaded Simplified process for exporting and importing topologies New Topology Data Model Features in Oracle Spatial 10g Release 2 The new Topology Data Model features in Oracle Spatial 10g Release 2 include: SDO_TOPO_MAP.ADD_LINEAR_GEOMETRY: Adds one or more edges for a specified line string SDO_TOPO_MAP.ADD_POINT_GEOMETRY: Adds a node representing a specified point SDO_TOPO_MAP.ADD_POLYGON_GEOMETRY: Adds one or more faces for a specified polygon SDO_TOPO_MAP.CREATE_FEATURE: Creates a feature from a Spatial geometry SDO_TOPO_MAP.LOAD_TOPO_MAP Available as a procedure Use when you do not need to know which topological elements were loaded Simplified process for exporting and importing topologies Oracle Spatial 10g: Advanced
309
Oracle Spatial 10g Release 2 New Topology Data Model Features
SDO_TOPO_GEOMETRY: New GET_TGL_OBJECTS member function Returns the SDO_TOPO_OBJECT_ARRAY object for an SDO_TOPO_GEOMETRY in a geometry layer with a hierarchy level greater than 0 (zero) in a topology Collection layers: An SDO_TOPO_GEOMETRY layer that can contain topology elements of different topology geometry types For example, a collection layer can contain specific land parcel, city street, and traffic sign elements Feature hierarchy can include topology primitives In a topology hierarchy, each layer can contain features built from topological elements (nodes, edges, faces) as well as features built from features at the next lower level Other enhancements… New Topology Data Model Features in Oracle Spatial 10g Release 2 (continued) New Topology Data Model features in Oracle 10g Release 2 include: SDO_TOPO_GEOMETRY: New GET_TGL_OBJECTS member function Returns the SDO_TOPO_OBJECT_ARRAY object for an SDO_TOPO_GEOMETRY in a geometry layer with a hierarchy level greater than 0 (zero) in a topology Collection layers An SDO_TOPO_GEOMETRY layer that can contain topology elements of different topology geometry types For example, a collection layer can contain specific land parcel, city street, and traffic sign elements Feature hierarchy can include topology primitives In a topology hierarchy, each layer can contain features built from topological elements (nodes, edges, faces) as well as features built from features at the next lower level Other enhancements There are many other enhancements to the Topology Data Model in Oracle Spatial 10g Release 2. Oracle Spatial 10g: Advanced
310
Oracle Spatial 10g: Advanced 1-314
Summary In this lesson, you should have learned how to: Explain the topology concepts Describe the Oracle Spatial Topology Data Model Create a topology Load topology primitives Explain topology feature model Use the topology data type: SDO_TOPO_GEOMETRY Describe topology caches Use SDO_TOPO_MAP.CREATE_FEATURE Explain topology hierarchies Discuss spatial queries with topology Share a topology between Oracle users Oracle Spatial 10g: Advanced
311
Oracle Spatial Network Data Model
312
Oracle Spatial 10g: Advanced 1-316
Objectives After completing this lesson, you should be able to: Explain network concepts Discuss the Oracle Spatial Network Data Model Describe node, link, and path tables Detail the network metadata Include geometry data in a network List the types of analysis done in the Oracle Spatial Network Data Model Identify network constraints Objectives This section introduces you to the concepts associated with Oracle Spatial Network Data Model. Oracle Spatial 10g: Advanced
313
Spatial Analysis Versus Network Analysis
Oracle Locator and Oracle Spatial solve spatial proximity problems. Another type of analysis required by users and applications is network analysis. Network applications deal with the connectivity and (optionally) cost of features. Spatial data is optional. Spatial proximity Connectivity Distance Spatial Analysis Versus Network Analysis Network applications deal with the connectivity and (optionally) cost of features (with or without spatial information). Oracle Spatial deals with spatial proximity problems. In the example shown above, distance with respect to spatial proximity is calculated based on the closest distance between the points. In the network data model, distance is based on cost information stored with the link that connects the two nodes. In the same example, the closest feature in the spatial case is determined strictly by using the straight line distance between the points, independent of the ability to traverse from one point to the other. In network analysis, connectivity of the nodes is a prerequisite; then the link with the shortest stored length is chosen. Closest feature Oracle Spatial 10g: Advanced
314
Oracle Spatial 10g: Advanced 1-318
What Is a Network? A network (also called a graph) is a model that represents relationships between objects of interest. In a network model, objects of interest are defined as nodes. A cost may be associated with a node. A direct relationship between two objects (nodes) is defined as a link. A link connects two nodes. A link may have associated cost (time or distance). Links can be directed or bidirected. The ability to traverse links to go from one node to another node is known as accessibility. The sets of ordered links between two nodes is called a path. What Is a Network? A network is a model that represents relationships between objects of interest. In a network model, objects of interest are defined as nodes. A node can have an associated cost, which is the cost to pass through the node. In a network model, a direct relationship between two objects (nodes) is defined as a link. When a link exists, the two nodes are connected. Links can have an associated cost such as time or distance. Links can be directed (unidirectional) or bidirected (can be traversed in two directions). The ability to traverse links to go from one node to another node is known as accessibility. The defined route (the set of ordered links) between two nodes is called a path. A path can be a simple path where there is only one set of ordered links defined between two nodes. A path can be a complex path where there is more than one simple path defined between two nodes. Oracle Spatial 10g: Advanced
315
Oracle Spatial 10g: Advanced 1-319
A Simple Network Node Link Path N1 N2 N6 N5 N7 N8 N9 N10 N11 N12 N4 N3 L1 L2 L3 L4 L14 L13 L18 L10 L7 L5 L8 L6 L9 L17 L15 L16 L11 L12 L19 If this network represented streets and intersections: Nodes are intersections Links are streets A path is a route between two nodes A Simple Network This is an example of a simple network. It can represent streets and intersections, it can be a layout of utilities, or any set of features to be modeled using a network. In this example, nodes (objects) are represented as points. Links, which define connectivity between two objects, are shown as the thinner lines. Note that adjacent nodes in this model are nearly all connected, but the connectivity is defined by the user or application, and is dependent on the characteristics of what is being modeled. In this case, there is no connectivity between the nodes N3 and N7. Paths are used to show accessibility between any two objects. One path between node N1 and node N10 is shown. There are other paths that can also show accessibility between nodes N1 and N10. Oracle Spatial 10g: Advanced
316
A More Complicated Network
New York City Streets Data A More Complicated Network This is an example of a more complicated network. It is the streets data for New York City. Oracle Spatial 10g: Advanced
317
A More Complicated Network
New York City Streets Data (zoomed in) A More Complicated Network (continued) This is a zoomed-in example of streets data for New York City. Oracle Spatial 10g: Advanced
318
What Is the Oracle Spatial Network Data Model?
The Oracle Spatial Network Data Model stores and analyzes network data. Connectivity is determined using links and nodes: Each link has a start node and an end node. Analysis is done based on connectivity and optionally cost information. Common analysis includes: Accessibility Shortest path analysis Within cost analysis Minimum cost spanning tree Traveling salesman problem Reachable nodes Reaching nodes Result of analysis is often a path. A path has start and end nodes, and one or more links. What Is the Oracle Spatial Network Data Model? The network data model is a way to store and analyze network data based on connectivity information. Spatial data is not required to perform network analysis. Connectivity is determined via the use of links and nodes, where each link has an identifier, a start node, and an end node. All of the analysis done using the network data model is based on connectivity information and optionally cost information. Some of the analysis supported using network management includes: Accessibility: Determines connectivity between any two nodes (can node X reach node Y) Shortest path analysis: Routes based on the least-expensive path based on stored cost information (the cheapest path from X to Y) Within cost analysis: Routing based on stored cost information (given a cost limit and a start node, which nodes can be reached) Minimum cost spanning tree: The least expensive way to connect all nodes in the network Oracle Spatial 10g: Advanced
319
Oracle Spatial Network Data Model
Oracle Spatial Network Data Model is a feature of Oracle Spatial that models, stores, manages, and analyzes generic connectivity relationships. A storage model to represent networks: Logical or spatial networks Directed or not With or without cost A PL/SQL API to manage the network: Creating network structures Validation Oracle Spatial Network Data Model Oracle Spatial Network Data Model is a component of Oracle Spatial used for modeling, storing, managing, and analyzing network information. An open network data model is used. A network can include spatial information (a spatial network), but spatial information is neither required, nor used for any analysis. A network can be directed (each link can be traversed in a single direction), or bidirected, where each link can be traversed in both directions. Cost data is not required. Additionally, SQL and PL/SQL can be used to store and retrieve network information. A PL/SQL API is provided to create and manage network structures. Oracle Spatial 10g: Advanced
320
Oracle Spatial Network Data Model
A Java API to perform network analysis: Shortest path, within cost, nearest neighbors Traveling salesman problem, spanning tree Reaching/reachable nodes, and others Oracle Spatial Network Data Model (continued) Finally, a Java API is provided for complex analysis as well as for editing and updating network data. There is no requirement to store geometry data in the Oracle Spatial Network model. Oracle Spatial 10g: Advanced
321
Oracle Spatial Network Data Model
Separates the application and the attributes from the generic network data model and attributes: Application manages application data The network data model manages and analyzes network data Analysis results can return optional SDO_GEOMETRY data, using any of the following geometry types in the network: SDO_GEOMETRY Linear-referenced SDO_GEOMETRY SDO_TOPO_GEOMETRY (Oracle Topology) Oracle Spatial Network Data Model (continued) The Oracle Spatial Network Data Model separates the management of application-specific data from network-specific data. For instance, a routing application may use the network data model to determine the route from Point A to Point B. The network data model returns the path information, but the application has to manage street name information to make the routing information useful to end users. Applications and/or end users model data to maintain the mapping between the network information (nodes and links) and the application information. This modeling could be done by adding columns in the node, link, and path tables, or by using whatever method works for the application. Oracle Spatial Network Data Model directly integrates with Oracle Spatial, and can return spatial data using: SDO_GEOMETRY: The network data model can store geometry data with network data. LRS_GEOMETRY (SDO_GEOMETRY with linear referencing information): The network data model can associate network data with a linear referenced SDO_GEOMETRY objects. Oracle Topology: The network data model stores SDO_TOPO_GEOMETRY features with network data. Oracle Spatial 10g: Advanced
322
Oracle Spatial Network Data Model
Queries and GUI (Web) Clients PL/SQL API Java API Network Loading/Caching/ Maintenance/Analysis (Java API) Network Data Model Persistent Network Data Management (PL/SQL Package) Database Oracle Spatial Network Data Model (continued) Client applications interact with Oracle Spatial Network Data Model via the Java and/or PL/SQL APIs. These APIs connect to the network data model, which analyzes information stored in the database, and return results to the client application. Oracle Spatial 10g: Advanced
323
Oracle Spatial Network Data Model
Persistent data associated with the Oracle Spatial Network schema includes: Network metadata Node table Link table Optionally, persistent data can include: Path table and Path-Link table Network Geometry Layer – one of: SDO_GEOMETRY Linear-referenced SDO_GEOMETRY Topology (SDO_TOPO_GEOMETRY) Application-specific information Oracle Spatial Network Data Model (continued) Oracle Spatial Network Data Model requires storage of some basic persistent information. That information includes: Metadata about the network information to be stored A Node table A Link table Optional persistent data can include: A Path table and a Path-Link table Typically used to store the results of analysis SDO_GEOMETRY, linear-referenced SDO_GEOMETRY, or SDO_TOPO_GEOMETRY information Application-specific information Oracle Spatial 10g: Advanced
324
Oracle Spatial 10g: Advanced 1-329
The Node Table Every network requires a table to hold nodes. User-defined, or the network data model can create Stores all nodes in the network Requires a unique NODE_ID column Optional columns include: Cost One of SDO_GEOMETRY, SDO_TOPO_GEOMETRY, or a pointer to an LRS geometry and its measure Active Hierarchy information Any application-specific information Other optional columns The Node Table Every Oracle Spatial Network Data Model implementation requires a table to hold nodes. Either you, or the application, creates this table or the network data model can create it. The node table stores all of the nodes in a network. A node table must have a NODE_ID column to hold the unique ID of each node. Optionally, the node table can contain other information such as cost, geometry, active (whether the node participates in analysis), hierarchy information, application-specific information, and more. Hierarchies are an advanced concept in the Network Data Model. You can read more about hierarchies in the Spatial Topology and Network Data Models User’s Guide. Oracle Spatial 10g: Advanced
325
Network Node Table: Example
SQL> desc MYNETWORK_NODE$; Name Type NODE_ID NUMBER (Primary Key) NODE_NAME VARCHAR2(32) NODE_TYPE VARCHAR2(24) COST NUMBER ACTIVE VARCHAR2(1) GEOMETRY MDSYS.SDO_GEOMETRY GEOM_ID NUMBER MEASURE NUMBER TOPO_GEOMETRY MDSYS.SDO_TOPO_GEOMETRY HIERARCHY_LEVEL NUMBER PARENT_NODE_ID NUMBER PARTITION_ID NUMBER O p t i o n a l Network Node Table: Example The node table is used by Oracle Spatial Network Data Model. The node table can be created with a user-defined name, or it can be assigned a name by Oracle Spatial Network Data Model. When assigned a name, it is of the form <network_name>_NODE$. It includes: NODE_ID: The required numeric primary key in the node table. The value of NODE_ID is determined by application or user. This is the only required column in the NODE$ table. NODE_NAME: Value is determined by application or user NODE_TYPE: Value is determined by application or user COST: Column that contains numeric cost information. User or application specifies this column name. ACTIVE: Contains Y if the node is active in the network, N if the node is inactive. GEOMETRY: If GEOMETRY_TYPE in the metadata is SDO_GEOMETRY, then the node table has a column of type SDO_GEOMETRY. User or application can specify this column name. GEOM_ID: If GEOMETRY_TYPE in the metadata is LRS_GEOMETRY, this points to the row containing the LRS_GEOMETRY in the table specified in the metadata by LRS_TABLE_NAME. The node table typically includes either no geometry information, or one of SDO_GEOMETRY, SDO_TOPO_GEOMETRY, or LRS_GEOMETRY information. Oracle Spatial 10g: Advanced
326
Oracle Spatial 10g: Advanced 1-332
The Link Table Every network requires a table containing links. User-defined, or the network data model can create Stores all links in the network Requires LINK_ID column to store unique link IDs Requires START_NODE_ID and END_NODE_ID columns Optional columns include: Cost One of SDO_GEOMETRY, SDO_TOPO_GEOMETRY, or a pointer to an LRS geometry and start and end measures Active Hierarchy information Any application-specific information Other optional columns The Link Table Every Oracle Spatial Network Data Model implementation requires a link table. Either the user/application creates this table, or the network data model can create it. The table containing links stores all of the links in a network. The link table must have a START_NODE_ID column and an END_NODE_ID column to hold the start and end node ID of each link. Optionally, the link table can contain other information such as cost, geometry, active (whether the node participates in analysis), hierarchy information, application-specific information, and more. Oracle Spatial 10g: Advanced
327
Network Link Table: Example
SQL> desc MYNETWORK_LINK$; Name Type LINK_ID NUMBER (Primary Key) START_NODE_ID NUMBER END_NODE_ID NUMBER LINK_NAME VARCHAR2(32) LINK_TYPE VARCHAR2(24) ACTIVE VARCHAR2(1) LINK_LEVEL NUMBER COST NUMBER GEOMETRY MDSYS.SDO_GEOMETRY GEOM_ID NUMBER START_MEASURE NUMBER END_MEASURE NUMBER TOPO_GEOMETRY MDSYS.SDO_TOPO_GEOMETRY PARENT_LINK_ID NUMBER O p t i o n a l Network Link Table: Example The link table is used by Oracle Spatial Network Data Model. The link table can be created with a user-defined name, or it can be assigned a name by Oracle Spatial Network Data Model. When assigned a name, it is of the form <network_name>_LINK$. It includes required columns (LINK_ID, START_NODE_ID, and END_NODE_ID) as well as optional columns. LINK_ID: The numeric primary key in the link table. Value is determined by the application or user. START_NODE_ID: The NODE_ID of the beginning of this link END_NODE_ID: The NODE_ID of the end of this link LINK_NAME: Value is determined by the application or user LINK_TYPE: Value is determined by the application or user ACTIVE: Contains Y if the node is active in the network, N if the node is inactive LINK_LEVEL: Can be used by the application to prioritize or group links COST: Column which contains numeric cost information. The user or application specifies this column name. GEOMETRY: If GEOMETRY_TYPE in the metadata is SDO_GEOMETRY, then the link table has a column of type SDO_GEOMETRY. The user or application specifies this column name. The node table typically includes either no geometry information, or one of SDO_GEOMETRY, SDO_TOPO_GEOMETRY, or LRS_GEOMETRY information. Oracle Spatial 10g: Advanced
328
Oracle Spatial 10g: Advanced 1-335
Network Metadata SQL> desc user_sdo_network_metadata; Name Type NETWORK VARCHAR2(24) NETWORK_ID NUMBER NETWORK_CATEGORY VARCHAR2(12) GEOMETRY_TYPE VARCHAR2(24) NETWORK_TYPE VARCHAR2(24) NO_OF_HIERARCHY_LEVELS NUMBER NO_OF_PARTITIONS NUMBER LRS_TABLE_NAME VARCHAR2(32) LRS_GEOM_COLUMN VARCHAR2(32) NODE_TABLE_NAME VARCHAR2(32) NODE_GEOM_COLUMN VARCHAR2(32) NODE_COST_COLUMN VARCHAR2(32) LINK_TABLE_NAME VARCHAR2(32) LINK_GEOM_COLUMN VARCHAR2(32) LINK_DIRECTION VARCHAR2(12) LINK_COST_COLUMN VARCHAR2(32) PATH_TABLE_NAME VARCHAR2(32) PATH_GEOM_COLUMN VARCHAR2(32) PATH_LINK_TABLE_NAME VARCHAR2(32) PARTITION_TABLE_NAME VARCHAR2(32) Network Metadata The metadata stored by the network data model includes: NETWORK: The name of the network. It is a primary key for each user, so it must be unique. NETWORK_ID: Reserved for future use NETWORK_CATEGORY: LOGICAL if no spatial data associated with network, or SPATIAL if spatial data associated with the network GEOMETRY_TYPE: If SPATIAL is specified for NETWORK_CATEGORY, then GEOMETRY_TYPE is one of SDO_GEOMETRY LRS_GEOMETRY TOPO_GEOMETRY NETWORK_TYPE: Value is determined by application/user. NO_OF_HIERARCHY_LEVELS: Number of levels in the hierarchy. The number 1 means the network is non-hierarchical. NO_OF_PARTITIONS: Used when partitioning the network. The number 1 means the network is not partitioned. Oracle Spatial 10g: Advanced
329
Optional Network Path Tables
SQL> desc MYNETWORK_PATH$; Name Type PATH_ID NUMBER (Primary Key) PATH_NAME VARCHAR2(32) PATH_TYPE VARCHAR2(24) START_NODE_ID NUMBER END_NODE_ID NUMBER GEOMETRY MDSYS.SDO_GEOMETRY COST NUMBER SIMPLE VARCHAR2(1) SQL> desc MYNETWORK_PLINK$; PATH_ID NUMBER LINK_ID NUMBER SEQ_NO NUMBER Optional Network Path Tables The path tables are optional tables for use with Oracle Spatial Network Data Model. When an analysis results in a path, the results can be stored in the path tables. The path tables can be created with user-defined names, or they can be assigned a name by Oracle Spatial Network Data Model. When assigned names, they are of the form <network_name>_PATH$ and <network_name>_PLINK$. The <network_name>_PATH$ table includes: PATH_ID: The numeric primary key in the path table. Value is determined by application/user PATH_NAME: Value is determined by application/user PATH_TYPE: Value is determined by application/user START_NODE_ID: The NODE_ID of the beginning of this PATH END_NODE_ID: The NODE_ID of the end of this PATH GEOMETRY: If NETWORK_CATEGORY in the metadata is SPATIAL, then the path table has a column of type SDO_GEOMETRY. The user/application can specify this column name. SDO_GEOMETRY is the only geometry type used in the path table. COST: Column that contains numeric cost of this path. The user/application can specify this column name. Oracle Spatial 10g: Advanced
330
The Network Data Model: Process
Set up the Network Data Model: Create the node table and the link table. Insert into USER_SDO_NETWORK_METADATA. Load network and application data: Use SQL/Loader Insert statements Programmatic Analyze and/or edit network data Application Java program The Network Data Model: Process To use the network data model requires first that the node and link tables be created along with the metadata used by the Network Data Model. Next, network data has to be loaded along with any optional applications-related data that is used either by the network data model or by the application. After the data is loaded, then analysis and/or editing of network data can be done. Oracle Spatial 10g: Advanced
331
Setting Up the Network Data Model
The Oracle Spatial Network Data Model requires tables to hold nodes and links, and network metadata. There are many ways to create required information. Manually: Create the node table and the link table. Insert into USER_SDO_NETWORK_METADATA. Automatically: Use the SDO_NET.CREATE_SDO_NETWORK procedure to automatically create tables and populate metadata. BEGIN sdo_net.create_sdo_network ( network => 'NYC_ROADS', no_of_hierarchy_levels => 1, is_directed => true, node_with_cost => false ); END; Setting Up the Network Data Model The network data model requires that the node and link tables be created and populated. Also, metadata must be loaded into the USER_SDO_NETWORK_METADATA view. There are many ways to do this. You can create the nodes and link tables manually, and manually insert these into USER_SDO_NETWORK_METADATA. You can execute the SDO_NET.CREATE_SDO_NETWORK procedure, and if the node and link table names are not specified, the tables are created automatically, and the USER_SDO_NETWORK_METADATA view is automatically populated. Setting node_with_cost => false means that cost information will not be associated with nodes. Oracle Spatial 10g: Advanced
332
Setting Up the Network Data Model
Other ways to create the required network data model infrastructure include: Hybrid: Semi-automatic SDO_NET.CREATE_SDO_NETWORK specifying user-created node and link tables Populates USER_SDO_NETWORK_METADATA automatically Hybrid: Semi-manual SDO_NET.CREATE_NODE_TABLE creates the node table SDO_NET.CREATE_LINK_TABLE creates the link table User populates USER_SDO_NETWORK_METADATA Setting Up the Network Data Model (continued) Another way of setting up the required infrastructure in the network data model is for you to create node and link tables, then use the SDO_NET.CREATE_SDO_NETWORK procedure to automatically populate the metadata. Yet another way to set up required tables is to use SDO_NET.CREATE_NODE_TABLE and SDO_NET.CREATE_LINK_TABLE procedures to create node and link tables, then manually populate (or use SDO_NET.CREATE_SDO_NETWORK to automatically populate) the metadata. Oracle Spatial 10g: Advanced
333
Using Geometry Data with the Network Data Model
If GEOMETRY_TYPE in metadata is SDO_GEOMETRY, then: Insert the point geometry in the node table Insert the line string geometry in the link table If GEOMETRY_TYPE in metadata is LRS_GEOMETRY, then: Need another table with linear-referenced geometries Metadata includes pointer to table and column GEOM_ID is pointer to specific LRS geometry If node: MEASURE is used to extract the point geometry when needed If link: START_MEASURE and END_MEASURE are used to extract the link geometry (dynamic segmentation) when needed Using Geometry Data with the Network Data Model If the GEOMETRY_TYPE in the USER_SDO_NETWORK_METADATA view is SDO_GEOMETRY: Insert the point geometry that represents each node with the node in the node table Insert the line-string geometry that represent each link with the link in the link table Note that a link has a START_NODE_ID and an END_NODE_ID. The location of the first and last points of the link should be coincident with the geometry specified for the NODE_ID associated with each of START_NODE_ID and END_NODE_ID. If the GEOMETRY_TYPE in the USER_SDO_NETWORK_METADATA view is LRS_GEOMETRY: A separate table with linear-referenced geometries is required. That table requires a geometry column and a numeric key that can be used to join the node and links to the LRS geometry data. A procedure is provided that can create this table (SDO_NET.CREATE_LRS_TABLE) or the user/application can create this table. USER_SDO_NETWORK_METADATA provides a pointer to the LRS table and geometry column Oracle Spatial 10g: Advanced
334
Using Geometry Data with the Oracle Spatial Network Data Model
If GEOMETRY_TYPE in metadata is TOPO_GEOMETRY, then: Topology feature tables for nodes must include the columns required in the node table Topology feature tables for links must include the columns required in the link table You register these tables with the topology ADD_TOPO_GEOMETRY_LAYER You populate the tables with LINK, START_NODE, and END_NODE information Users or applications derive connectivity from topology tables Using Geometry Data with Oracle Spatial Network Data Model If the GEOMETRY_TYPE in the USER_SDO_NETWORK_METADATA view is TOPO_GEOMETRY: The feature tables associated with the topology are the node and link tables of the network. Topology feature tables for nodes include the columns required (NODE_ID) by the network data model in the node table. Topology feature tables for links must include the columns required (LINK_ID, START_NODE_ID, and END_NODE_ID) by the network data model in the link table. The node and link feature tables are registered using the Topology Data Model command: ADD_TOPO_GEOMETRY_LAYER. The connectivity information to be stored can be derived by applications or users from information stored in the topology tables. Note: Analysis in the Network Data Model uses connectivity and optionally cost information. Analysis is never based on geometry information. Some analysis results may include SDO_GEOMETRY data. Oracle Spatial 10g: Advanced
335
Network Data Model Analysis
The network data model supports many kinds of network analysis including: Shortest path between two nodes Determines the shortest path between two nodes All paths between two nodes Finds N paths between two nodes All nodes within cost of a given node Finds all nodes within a specified cost from a given node Traveling salesman problem Finds the shortest route between an arbitrary number of nodes (closed or open) Network Data Model Analysis The network data model includes the ability to perform the following network analysis: Shortest path between two nodes: Determines the shortest path between two nodes All paths between two nodes: Finds N paths between two nodes All nodes within cost of a given node: Finds all nodes within a specified cost from a given node Traveling salesman problem: Finds the shortest route between an arbitrary number of nodes. The shortest route can be open (the end node is not the same as the start node) or closed (the end node is the same as the start node.) Oracle Spatial 10g: Advanced
336
Network Data Model Analysis
Additional analysis includes: Nodes reachable from a specified node Finds nodes that can be reached from a given node Nodes capable of reaching a given node Finds the nodes that can reach a given node All nodes within the cost of a given node Given a node and a cost, what nodes can be reached All nodes within reaching cost of a given node Given a node and a cost, what nodes can reach it Network Data Model Analysis (continued) Additional network data model analysis includes: Nodes reachable from a specified node: Finds the nodes that can be reached from a given node Nodes capable of reaching a given node: Finds the nodes that can reach a given node All nodes within cost of a given node: Given a node and a cost, which nodes can be reached within the specified cost All nodes within reaching cost of a given node: Given a node and a cost, which nodes can reach it within the specified cost Oracle Spatial 10g: Advanced
337
Network Data Model Analysis
Other network data model analysis includes: Nearest n nodes of a given node Determines the nearest n nodes from a specified node Nearest n reachable nodes of a given node Determines the nearest n nodes capable of reaching the given node Minimum cost spanning tree Finds the least expensive way to connect all nodes in a network Network Data Model Analysis (continued) Other network data model analysis includes: Nearest n nodes of a given node: Determines the nearest n nodes from a specified node Nearest n reachable nodes of a given node: Determines the nearest n nodes capable of reaching the given node Minimum cost spanning tree: Finds the least expensive way to connect all nodes in a network Oracle Spatial 10g: Advanced
338
Oracle Spatial Network Data Model Editor
A visualization, editing, and analysis tool Java stand-alone application for Oracle Spatial Network Data Model Ships with Oracle Spatial 10g as a demo program Requires Oracle Spatial 10g and some Java .jar files Only used with spatial networks (networks with spatial information) Visualize Edit Perform network analysis Oracle Spatial Network Data Model Editor The Oracle Spatial Network Data Model Editor is a sample tool to enable visualization, editing, and analysis of network data model information. This sample tool is shipped in the Oracle 10g companion CD, and requires Oracle Spatial 10g, and associated network data model sample Java .jar files. The tool can be used only with spatial networks. Oracle Spatial 10g: Advanced
339
Oracle Spatial Network Data Model Editor
Editing functions of the Network Data Model Editor Editing Functions of the Oracle Spatial Network Data Model Editor The drop-down menu shows the editing functions available with the Oracle Spatial Network Data Model Editor. Oracle Spatial 10g: Advanced
340
Oracle Spatial Network Data Model Editor
Analysis functions of the Network Data Model Editor Analysis Functions of the Oracle Spatial Network Data Model Editor The drop-down menu shows the analysis functions available with the Oracle Spatial Network Data Model Editor. Note that Max Flow is supported only in Oracle Spatial 10g Release 2. Oracle Spatial 10g: Advanced
341
Network Data Model Analysis: Shortest Path Between Two Nodes
This illustrates the shortest route calculated between two nodes. NetworkManager.shortestPath (NYC_Net, startNodeId, endNodeId) Oracle Spatial 10g: Advanced
342
Network Data Model Analysis: All Paths Between Two Nodes
This is an example of finding 20 paths between two nodes. NetworkManager.allPaths(NYC_NET, startNodeId, endNodeId, maxSolutions) Oracle Spatial 10g: Advanced
343
Network Data Model Analysis: All Nodes Within Cost
This example shows all nodes capable of being reached within the given cost from the given start node. NetworkManager.withinCost (NYC_NET, startNodeId, maxCost); Oracle Spatial 10g: Advanced
344
Network Data Model Analysis: Traveling Salesman Problem–Setup
This is an example of setting up a Traveling Salesman Problem through the Oracle Spatial Network Data Model Editor. In this example, you create the fastest route between all the specified nodes. The path is closed, so the resulting path will have the start node equal to the end node. NetworkManager.tspPath (NYC_NET, nodeIds, isClosed, useExactCost, null); Oracle Spatial 10g: Advanced
345
Network Data Model Analysis: Traveling Salesman Problem–Result
This is the result of the analysis set up in the previous slide. NetworkManager.tspPath (NYC_NET, nodeIds, isClosed, useExactCost, null); Oracle Spatial 10g: Advanced
346
Oracle Spatial 10g: Advanced 1-356
Network Constraints Network searches can be constrained with custom Java code using network constraints. Implement the NetworkConstraint interface. Pass constraint to analysis functions. The constraint is checked during analysis Accept or reject the next link or node combination Network constraints require users to implement two methods. requiresPathLinks() Returns TRUE if the entire path is required for constraint processing isSatisfied (AnalysisInfo information) Returns TRUE if the next link or node is allowed Returns FALSE if the link or node cannot be used Network Constraints The network data model includes support for constraining network analysis based on custom code. Either you or your application implements the constraint using custom Java code, and for each link considered the network constraint is applied during the analysis. The constraint interface either allows the link to be used in the analysis, or disallows the link in the analysis. Network constraints require that users implement two methods. The requiresPathLinks method returns TRUE if the entire path is required for processing, and FALSE if the entire path is not required for processing. The isSatisfied method returns TRUE if the next link can be considered during analysis, and returns FALSE if the next link cannot be used in the network analysis. Oracle Spatial 10g: Advanced
347
Oracle Spatial 10g: Advanced 1-357
Network Constraints Application-specific data can be used in network constraint processing: Can be stored in the database Example: Modeling turn restrictions For each link, store the LINK_ID of links that cannot follow this link: SQL> desc MYNETWORK_LINK$; Name Type LINK_ID NUMBER (Primary Key) START_NODE_ID NUMBER END_NODE_ID NUMBER RESTRICTED_LINKS VARRAY(NUMBER) Network Constraints (continued) Application-specific data can be used when network constraints are applied during analysis. The application-specific data can be stored in the database. It can be stored directly in the node or link tables. For example, to model turn restrictions each link may have a VARRAY with a list of restricted turns from the current link. Oracle Spatial 10g: Advanced
348
Network Constraint: Turn Restriction
Modeling a turn restriction: Implement the NetworkConstraint interface. Model turn restrictions using application-specific data. LINK START END RESTRICTED ID NODE NODE LINKS ID ID N S2,W2 S1 N2 E1 E2 Current Node 225 W2 W1 Network Constraint: Example Network constraints offer a flexible way for users and applications to guide network data model searches. In this example, turn restrictions can be modeled in the database. The search can be guided using the NetworkConstraint feature to enable or disable turns as appropriate when the network data model is used in a routing application. S2 N1 START_NODE_ID for Link N1 = 165 Oracle Spatial 10g: Advanced
349
Oracle Spatial 10g: Advanced 1-359
Network Constraints During network constraint processing, AnalysisInfo is available, and contains: Start node, current node, next node Current link, next link Current depth (number of links), current cost Path links and nodes (if requiresPathLinks() is true) public class TurnRestrictions implements NetworkConstraint { … // path link info. not needed public boolean requiresPathLinks() { return false ; } public boolean isSatisfied(AnalysisInfo info) { Link currentLink = info.getCurrentLink(); if ( currentLink == null ) return true; // start node if current link == null Link nextLink = info.getNextLink(); return validTurn(currentLink.getID(),nextLink.getID()); } Network Constraints (continued) There is a lot of contextual information available to you during network constraint processing. AnalysisInfo has node, link, cost, and depth information. Additionally, if desired, path and link information is available. The example shows the requiresPathLinks method implemented, returning FALSE. The example also shows the isSatisfied method, which gets the current link and the next link, and it returns whether the next link is valid or invalid for use in the analysis. The validTurn function implements the function to determine if the next link being considered in the analysis can be used. Oracle Spatial 10g: Advanced
350
More Network Data Model Features
Multiple cost columns: Multiple cost columns can be used in the same physical network data model tables. Separate metadata entries are used for each cost column. Multiple geometry types: Multiple geometry types can be used in the same physical network data model tables. Separate metadata entries are used for each geometry column. Subnetwork support: Create by using views into node and link tables Requires additional network metadata entry More Network Data Model Features The Network Data Model supports multiple cost columns. The user or application creates multiple cost columns in the node and/or link tables, and separate networks are specified in the USER_SDO_NETWORK_METADATA view. The Network Data Model supports more than one geometry type. In this case, a network of a different name is created by inserting data into USER_SDO_NETWORK_METADATA. The differences between the new network and the old network are in the different network names, and the different GEOMETRY_TYPE columns. Additional changes may be required. For instance, if the GEOMETRY_TYPE is changing from SDO_GEOMETRY to LRS_GEOMETRY, then: Pointers to the external LRS tables must be set up in the metadata Columns with measure information have to be populated in the node and link tables If path data is stored, then a new set of path tables associated with the new network must be created, and the metadata pointing to the path tables must be updated. The Network Data Model supports subnetworks using views into the node and link tables. Oracle Spatial 10g: Advanced
351
More Network Data Model Features
Referential integrity checks between nodes, links, and paths When a node is deleted, links and paths that depend on it are deleted as well. When a link is deleted, paths that depend on it are deleted as well. More Network Data Model Features (continued) The network data model includes referential integrity checks between nodes, links, and paths. For instance, paths are composed of links and nodes. If a link or a node associated with a path is deleted, the path is deleted as well. Also, links are defined in terms of the nodes they connect. If node is deleted, all of the links associated with it are removed also. Oracle Spatial 10g: Advanced
352
Oracle Spatial 10g Release 2 Network Data Model Features
PL/SQL API for network editing and analysis SDO_NET_MEM package Implements the same functionality as Java API Bidirected links Within a directed network, any link can be bidirected (traversed in both directions) The link table can contain a column named BIDIRECTED Must have the same cost in both directions Cost computation by a PL/SQL function Subnetwork loading and analysis Oracle Spatial 10g Release 2 Network Data Model Features The network data model in Oracle Spatial 10g Release 2 includes the following enhancements: PL/SQL API for network editing and analysis SDO_NET_MEM package Implements the same functionality as Java API Bidirected links Within a directed network, any link can be bidirected (traversed both from the start node to the end node and traversed from the end node to the start node). The link table can contain a column named BIDIRECTED. Cost computation by a PL/SQL function: The NODE_COST_COLUMN and LINK_COST_COLUMN columns in the USER_SDO_NETWORK_METADATA and ALL_SDO_NETWORK_METADATA views can specify a PL/SQL function to compute the cost value. Subnetwork loading and analysis Load based on bounding box Load based on WHERE clause applied to NODE and LINK tables Oracle Spatial 10g: Advanced
353
Oracle Spatial 10g: Advanced 1-363
Summary In this lesson, you should have learned how to: Explain network concepts Discuss the Oracle Spatial Network Data Model Describe node, link, and path tables Detail the network metadata Include geometry data in a network List the types of analysis used in the Oracle Spatial Network Data Model Identify network constraints Summary This section introduced the concepts associated with the Oracle Spatial Network Data Model. It described what a network is, and the metadata and data associated with Oracle Spatial Network Data Model. Also, node, link, and path tables were introduced. The types of queries used in the network data model were described. The association of geometry data with network data was described, as were network constraints. Oracle Spatial 10g: Advanced
354
Spatial Analysis and Mining (SAM)
355
Oracle Spatial 10g: Advanced 1-365
Objectives After completing this lesson, you should be able to describe the following: Neighborhood analysis Spatial binning Spatial clustering Objectives This section introduces you to the concepts associated with Oracle Spatial Analysis and Mining functionality. Oracle Spatial 10g: Advanced
356
Spatial Analysis and Mining
Everything is related to everything else, but nearby things are more related than distant things. Tobler’s first law of geography Spatial Analysis and Mining Oracle Spatial provides functionality to analyze, estimate, and predict the influence of new objects based on the location of nearby objects. Oracle Spatial 10g: Advanced
357
Spatial Analysis in Oracle Database 10g
Spatial Analysis and Mining includes functions for: Neighborhood analysis Aggregates a theme layer attribute for a given area of interest (AOI) Applies the overlap ratio of theme layer and AOI to the aggregated attribute Spatial binning Classifies data based on location Spatial clustering Determines patterns based on location Colocation analysis Determines how the location of one thing correlates to the location of something else Spatial Analysis in Oracle Database 10g Spatial analysis functions materialize spatial relationships that can subsequently be used in Data Mining applications (Oracle Data Mining). These spatial relationships are derived by analyzing data of nearby objects. There are different types of analysis functions supplied with Oracle Spatial SAM, including the following: Neighborhood analysis: Determines specific information about an area of interest. For example, use Census block polygons to find the population within a 2-mile radius around a proposed store location. The aggregated population values are adjusted by the “area overlap ratio” of the 2-mile buffer and census block polygon. Spatial binning: Classifies data based on location. For example, break the spatial extent (the bounds) of all customer location data into 64 bins, assign each customer to the appropriate location-based bin, and analyze the data in each bin. Spatial clustering: Determines patterns based on location. For example, law enforcement organizations may identify patterns in location with respect to particular crimes. Colocation analysis: Determines how the location of one thing correlates to the location of something else Oracle Spatial 10g: Advanced
358
Spatial Analysis and Mining: Neighborhood Analysis
Oracle Spatial 10g: Advanced
359
More Accurate Neighborhood Analysis
Kings Pop ( , ) Queens Pop NY Pop Sum populations within 3 miles of of a point (– , ) If overlap ratios are not applied, result is: 1,487, ,951, ,300,664 = 5,745,778 Can be accomplished with SDO_WITHIN_DISTANCE If overlap ratios are applied (with SAM), a more accurate result is: (1,487,536 * 0.19%) + (1,951,598 * 0.54%)+ (2,300,664 * 31.04%) = 724, More Accurate Neighborhood Analysis SDO_SAM.AGGREGATES_FOR_GEOMETRY This is an example of the use of the SDO_SAM.AGGREGATES_FOR_GEOMETRY function. In this example, the function buffers an input geometry by 3 miles, and then finds the sum of the total population of all the counties that intersect that buffered location, using the proportion of the population for each county that is equivalent to the proportion of the county that overlaps the buffered input geometry. Oracle Spatial 10g: Advanced
360
SDO_SAM.AGGREGATES_FOR_GEOMETRY
<NUMERIC_AGGREGATE> = SDO_SAM.AGGREGATES_FOR_GEOMETRY( <THEME_TABLE_NAME>, <THEME_GEOMETRY_COLUMN_NAME>, <AGGREGATE_TYPE>, <THEME_AGGREGATE_COLUMN>, <WINDOW_GEOMETRY> [,<distance_specification>]) Compares WINDOW_GEOMETRY with all geometries in a theme layer, and aggregates the THEME_AGGREGATE_COLUMN <distance_specification> : Topological operation applied between the WINDOW_GEOMETRY and the theme layer. For example: ANYINTERACT DISTANCE=n (within distance) SDO_NUM_RES (nearest neighbor) For ANYINTERACT and DISTANCE=n Each THEME_AGGREGATE_COLUMN value is adjusted by the overlap ratio of WINDOW_GEOMETRY and the corresponding theme layer geometry it intersects. <THEME_GEOMETRY_COLUMN_NAME> must be spatially indexed. SDO_SAM.AGGREGATES_FOR_GEOMETRY The SDO_SAM.AGGREGATES_FOR_GEOMETRY function compares the geometry passed into the function with all the geometries in the “theme” layer and aggregates numeric data from the theme layer for the passed-in geometry. The aggregate is based on the proportion of the area of the theme that overlaps the query window for ANYINTERACT and WITHIN_DISTANCE processing. For instance, if one-half of the area of one theme geometry overlaps the query window, and one-third of another theme geometry overlaps the query window, the returned aggregate value takes into account only one-half of first theme value and one-third of the second theme value. The function assumes an uniform distribution of data throughout the area in the proportion calculations. For nearest neighbor processing, the function aggregates values based on the n nearest neighbors (no proportions are applied). This function returns a number, which is the aggregated numeric value associated with theme geometries that satisfy the spatial analysis performed. Oracle Spatial 10g: Advanced
361
SDO_SAM.AGGREGATES_FOR_GEOMETRY Parameters
THEME_TABLE_NAME and THEME_GEOMETRY_COLUMN_NAME Identify the theme layer Theme layer must be spatially indexed. AGGREGATE_TYPE Type of aggregate to apply to THEME_AGGREGATE_COLUMN For example: SUM, MIN, MAX, AVG THEME_AGGREGATE_COLUMN Column from theme table whose value is aggregated WINDOW_GEOMETRY Query window SDO_GEOMETRY from a table or constructor SDO_SAM.AGGREGATES_FOR_GEOMETRY Parameters The parameters for SDO_SAM.AGGREGATES_FOR_GEOMETRY include: THEME_TABLE_NAME and THEME_COLUMN_NAME Uniquely identify the theme layer The theme layer must be spatially indexed. Using simplified geometries can enhance the performance of this function. AGGREGATE_TYPE Type of aggregate to apply to THEME_AGGREGATE_COLUMN, for example, SUM, MIN, MAX, AVG THEME_AGGREGATE_COLUMN Column from theme table whose value is aggregated WINDOW_GEOMETRY Query window from a table, or a constructor Oracle Spatial 10g: Advanced
362
SDO_SAM.AGGREGATES_FOR_GEOMETRY Parameters
DISTANCE_SPEC (OPTIONAL) Topological operation applied between WINDOW_GEOMETRY and the theme layer. For example: ANYINTERACT (Default) DISTANCE=n [unit=unit] (within distance) SDO_NUM_RES=n (nearest neighbor) For ANYINTERACT and DISTANCE=n, each THEME_AGGREGATE_COLUMN value is adjusted by the overlap ratio of WINDOW_GEOMETRY and the corresponding theme layer geometry it intersects. SDO_SAM.AGGREGATES_FOR_GEOMETRY Parameters (continued) DISTANCE_SPEC (optional) Topological operation applied between WINDOW_GEOMETRY and the theme layer. For example: -ANYINTERACT (Default) -DISTANCE=n [unit=unit] (within distance) -SDO_NUM_RES=n (nearest neighbor) For ANYINTERACT and DISTANCE=n, each THEME_AGGREGATE_COLUMN value is adjusted by the overlap ratio of WINDOW_GEOMETRY and the corresponding theme layer geometry it intersects. For SDO_NUM_RES (or nearest neighbor analysis), the THEME_AGGREGATE_COLUMN value is not adjusted. Oracle Spatial 10g: Advanced
363
SDO_SAM.AGGREGATES_FOR_GEOMETRY: Example
% AREA COUNTY ST TOTPOP COVERED Queens NY Kings NY New York NY SELECT sdo_sam.aggregates_for_geometry( 'GEOD_COUNTIES', 'GEOM', 'sum', 'totpop', SDO_GEOMETRY(2001, 8307, SDO_POINT_TYPE( , ,NULL), NULL, NULL), 'distance=3 unit=mile') FROM dual; =========== is the proportioned aggregate population SDO_SAM.AGGREGATES_FOR_GEOMETRY: Example This is an example of the use of the SDO_SAM.AGGREGATES_FOR_GEOMETRY function. In this example, the function buffers an input geometry by 3 miles, and then finds the sum of the total population of all the counties that intersect that buffered location, using the proportion of the population for each county that is equivalent to the proportion of the county that overlaps the buffered input geometry. Note that this simple function replaces more complicated spatial analysis that can be done using other spatial functions. For instance, the data shown above was generated using the SQL on the following page. Oracle Spatial 10g: Advanced
364
SDO_SAM.AGGREGATES_FOR_LAYER
Similar to SDO_SAM.AGGREGATES_FOR_GEOMETRY Instead of comparing a single window geometry to a theme layer, it compares all window geometries in a layer with all the geometries in a theme layer. The result is a table of aggregate values. One aggregate value per window geometry in the window layer MDSYS.SDO_REGAGGRSET (described in the next slide) contains the result. SDO_SAM.AGGREGATES_FOR_LAYER The SDO_SAM.AGGREGATES_FOR_LAYER function is similar to SDO_SAM.AGGREGATES_FOR_GEOMETRY. Instead of comparing a single window geometry to a theme layer, it compares a set of persistently stored window geometries (in a window layer) to a theme layer. The result is a table of aggregate values (MDSYS.SDO_REGAGGRSET), one aggregate value per window geometry in the window layer. The MDSYS.SDO_REGAGGRSET type is described in the next slide. Oracle Spatial 10g: Advanced
365
Oracle Spatial 10g: Advanced 1-376
MDSYS.SDO_REGAGGRSET Description (Return Value for Several SAM Functions) SQL> DESC mdsys.sdo_regaggrset mdsys.sdo_regaggrset TABLE OF mdsys.sdo_regaggr Name Type =============== ============ REGION_ID VARCHAR2(24) GEOMETRY SDO_GEOMETRY AGGREGATE_VALUE NUMBER REGION_ID Row ID of window geometry in window layer GEOMETRY Window geometry from the window layer AGGREGATE_VALUE Aggregate value from column in theme layer MDSYS.SDO_REGAGGRSET Description (Return Value for Several SAM Functions) The MDSYS.SDO_REGAGGRSET (region aggregate set) type is a table of MDSYS.SDO_REGAGGR (region aggregate) objects. Each MDSYS.SDO_REGAGGR object contains the aggregation result for one region. The attributes of the MDSYS.SDO_REGAGGR object are the following: REGION_ID Region’s row ID, to uniquely identify the region GEOMETRY Window, represented as an SDO_GEOMETRY object AGGREGATE_VALUE Aggregated value of a column in the theme layer Oracle Spatial 10g: Advanced
366
SDO_SAM.AGGREGATES_FOR_LAYER
SDO_REGAGGRSET = SDO_SAM.AGGREGATES_FOR_LAYER ( <THEME_TABLE_NAME>, <THEME_GEOMETRY_COLUMN_NAME>, <AGGREGATE_TYPE>, <THEME_AGGREGATE_COLUMN>, <WINDOW_TABLE_NAME>, <WINDOW_COLUMN_NAME> [, <distance_specification>]) Compares all the window geometries in a layer with all geometries in a theme layer, and aggregates the THEME_AGGREGATE_COLUMN. <distance_specification> : Topological operation applied between a window geometry and the theme layer. For example: ANYINTERACT DISTANCE=n (within distance) SDO_NUM_RES (nearest neighbor) For ANYINTERACT and DISTANCE=n Each THEME_AGGREGATE_COLUMN value is adjusted by the overlap ratio of the window geometry and the corresponding theme layer geometry it intersects. <THEME_GEOMETRY_COLUMN_NAME> must be spatially indexed. SDO_SAM.AGGREGATES_FOR_LAYER The SDO_SAM.AGGREGATES_FOR_LAYER function is similar to SDO_SAM.AGGREGATES_FOR_GEOMETRY. Instead of comparing a single window geometry to a theme layer, it compares a set of persistently stored window geometries (in a window layer) to a theme layer. The result is a table of aggregate values (MDSYS.SDO_REGAGGRSET), one aggregate value per window geometry in the window layer. An optional distance specification instructs the function about what type of topological operation to perform between the window geometries and the theme layer. Oracle Spatial 10g: Advanced
367
SDO_SAM.AGGREGATES_FOR_LAYER Parameters
THEME_TABLE_NAME and THEME_GEOMERTY_COLUMN_NAME Identify the theme layer Theme layer must be spatially indexed AGGREGATE_TYPE Type of aggregate to apply to AGGREGATE_COLUMN For example: SUM, MIN, MAX, AVG THEME_AGGREGATE_COLUMN Column from theme table whose value is aggregated WINDOW_TABLE_NAME, WINDOW_COLUMN_NAME Identify the window layer SDO_SAM.AGGREGATES_FOR_LAYER Parameters THEME_TABLE_NAME and THEME_COLUMN_NAME Uniquely identify the theme layer The theme layer must be spatially indexed. Simplified geometries can enhance the performance of this function. AGGREGATE_TYPE Type of aggregate to apply to the THEME_AGGREGATE_COLUMN, for example, SUM, MIN, MAX, AVG THEME_AGGREGATE_COLUMN Column from theme table whose value is aggregated WINDOW_TABLE_NAME and WINDOW_COLUMN_NAME Uniquely identify the window layer Oracle Spatial 10g: Advanced
368
SDO_SAM.AGGREGATES_FOR_LAYER Parameters
DISTANCE_SPEC (OPTIONAL) Topological operation applied between the window geometry and the theme layer. For example: ANYINTERACT (Default) DISTANCE=n [unit=unit] (within distance) SDO_NUM_RES=n (nearest neighbor) For ANYINTERACT and DISTANCE=n, each THEME_AGGREGATE_COLUMN value is adjusted by the overlap ratio of the window geometry and the corresponding theme layer geometry it intersects. SDO_SAM.AGGREGATES_FOR_LAYER Parameters (continued) DISTANCE_SPEC (optional) Topological operation applied between the WINDOW_GEOMETRY and the theme layer. For example: - ANYINTERACT (Default) - DISTANCE=n [unit=unit] (within distance) - SDO_NUM_RES=n (nearest neighbor) For ANYINTERACT and DISTANCE=n, each THEME_AGGREGATE_COLUMN value is adjusted by the overlap ratio of WINDOW_GEOMETRY and the corresponding theme layer geometry it intersects. For SDO_NUM_RES (or nearest neighbor analysis), the THEME_AGGREGATE_COLUMN value is not adjusted. Oracle Spatial 10g: Advanced
369
SDO_SAM.AGGREGATES_FOR_LAYER: Example
For each city, sum the population of all the counties within 3 miles of that city. Proportion the population by the percentage of county area that intersects the 3-mile buffer. SELECT b.city, b.state_abrv, a.aggregate_value FROM (SELECT region_id, aggregate_value FROM TABLE(sdo_sam.aggregates_for_layer( 'GEOD_COUNTIES', 'GEOM', 'sum', 'totpop', 'GEOD_CITIES', 'LOCATION', 'distance=3 unit=mile'))) a, geod_cities b WHERE a.region_id=b.rowid ORDER BY a.aggregate_value; SDO_SAM.AGGREGATES_FOR_LAYER:Example This is an example of the use of the SDO_SAM.AGGREGATES_FOR_LAYER function. Each point in the GEOD_CITIES layer is buffered by 3 miles, and the ratio of each overlapping county is applied to the total population value (TOTPOP) during aggregation. Oracle Spatial 10g: Advanced
370
SDO_SAM.TILED_AGGREGATES
Similar to SDO_SAM.AGGREGATES_FOR_LAYER, except that the window geometries are dynamically generated by this function, and not persistently stored in a table. You specify a TILING_DOMAIN (or coordinate system bounds) and a TILING_LEVEL, and: The function dynamically creates 4<TILING_LEVEL> tiles, each used as a query window against a theme layer. Tiles are not stored in a table. The function assigns a unique ID to each tile. SDO_SAM.TILED_AGGREGATES The SDO_SAM.AGGREGATES_TILED_AGGREGATES function is similar to SDO_SAM.AGGREGATES_FOR_LAYER. Instead of comparing a set of persistently stored window geometries (in a window layer) to a theme layer, this function dynamically creates the set of window geometries. After you specify a TILING_DOMAIN (or coordinate system bounds) and a TILING_LEVEL: The function dynamically creates 4<TILING_LEVEL> tiles, each used as a query window against a theme layer. Tiles are not stored in a table. The function assigns a unique ID to each tile. The result is a table of aggregate values (MDSYS.SDO_REGAGGRSET), one aggregate value per window geometry. An optional distance specification instructs the function about what type of topological operation to perform between the window geometries and the theme layer. Oracle Spatial 10g: Advanced
371
SDO_SAM.TILED_AGGREGATES: Example
In this example, a coordinate system that bounds the northeastern part of the U.S. is tiled into 42 (or 16) tiles. The geometry associated with each tile is compared to the GEOD_COUNTIES table. For each tile that interacts with counties: The function returns the sum of the population of counties that interact with the tile. Each population value is proportioned by the percentage of county area that intersects the tile. SDO_SAM.TILED_AGGREGATES: Example In this example, a coordinate system that bounds the northeastern part of the U.S. is tiled into 42 (or 16) tiles. Each tile is compared with the GEOD_COUNTIES spatial layer. For each tile that interacts with counties: Returns the sum of the population of counties that interact with the tile During aggregation, each population value is proportioned by the percentage of county area that intersects the tile. Oracle Spatial 10g: Advanced
372
SDO_SAM.TILED_AGGREGATES
SDO_REGAGGRSET = SDO_SAM.TILED_AGGREGATES ( <THEME_TABLE_NAME>, <THEME_COLUMN_NAME>, <AGGREGATE_TYPE>, <THEME_AGGREGATE_COLUMN>, <TILING_LEVEL> [,<TILING_DOMAIN>]) Dynamically tiles a coordinate system, and uses each tile as a query window against the theme layer (ANYINTERACT operation). Each THEME_AGGREGATE_COLUMN value is adjusted by the overlap ratio of a tile, and the corresponding theme layer geometry it intersects. Result is an SDO_REGAGGRSET. SDO_REGAGGRSET (discussed earlier) is a TABLE of SDO_REGAGGR objects. Each SDO_REGAGGR object contains: REGION_ID – Oracle-assigned ID for the tile GEOMETRY – Oracle-generated tile geometry (or window geometry) AGGREGATE_VALUE – Proportioned aggregate value for this tile Only tiles that intersect theme geometries are returned in SDO_REGAGGRSET. SDO_SAM.TILED_AGGREGATES The SDO_SAM.AGGREGATES_TILED_AGGREGATES function is similar to SDO_SAM.AGGREGATES_FOR_LAYER. Instead of comparing a set of persistently stored window geometries (in a window layer) to a theme layer, this function dynamically creates the set of window geometries. After you specify a TILING_DOMAIN (or coordinate system bounds) and a TILING_LEVEL: The function dynamically creates 4<TILING_LEVEL> tiles, each used as a query window against a theme layer. Tiles are not stored in a table. This function assigns a unique ID to each tile. The result is a table of aggregate values (MDSYS.SDO_REGAGGRSET), one aggregate value per window geometry. An optional distance specification instructs the function about what type of topological operation to perform between the window geometries and the theme layer. Oracle Spatial 10g: Advanced
373
SDO_SAM.TILED_AGGREGATES Parameters
THEME_TABLE_NAME and THEME_GEOMERTY_COLUMN_NAME Identify the theme layer Theme layer must be spatially indexed AGGREGATE_TYPE Type of aggregate to apply to THEME_AGGREGATE_COLUMN For example: SUM, MIN, MAX, AVG THEME_AGGREGATE_COLUMN Column from theme table whose value is aggregated TILING_LEVEL The number of times to divide the coordinate system. 4<TILING_LEVEL> tiles are created. TILING_DOMAIN (optional) An optional parameter that specifies the lower and upper bounds of the coordinate system SDO_SAM.TILED_AGGREGATES Parameters THEME_TABLE_NAME and THEME_COLUMN_NAME Uniquely identify the theme layer The theme layer must be spatially indexed. AGGREGATE_TYPE Type of aggregate to apply to the THEME_AGGREGATE_COLUMN, for example, SUM, MIN, MAX, AVG THEME_AGGREGATE_COLUMN Column from theme table whose value is aggregated TILING_LEVEL The number of times to divide the coordinate system. 4<TILING_LEVEL> tiles are dynamically created by this function. Oracle Spatial 10g: Advanced
374
SDO_SAM.TILED_AGGREGATES: Example
Generate 45 (or 1,024) tiles, and sum the population of intersecting counties. Proportion the population by the percentage of county area that intersects each tile. SELECT aggregate_value, region_id, geometry FROM TABLE (SELECT sdo_sam.tiled_aggregates( 'GEOD_COUNTIES','GEOM', 'SUM', 'TOTPOP', 5) FROM dual); ========== SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 3), SDO_ORDINATE_ARRAY( , , -135, 67.5)) SDO_ORDINATE_ARRAY( , 67.5, -135, )) SDO_SAM.TILED_AGGREGATES: Example This is an example of the use of the SDO_SAM.TILED_AGGREGATES. In this example, 1,024 tiles are dynamically generated. For each tile that intersects counties, the function calculates the proportioned sum of the total population of all the counties that intersect the tile. The function returns a table of aggregate values, one for each tile that intersects county geometries. This slide displays the results of the first two tiles. Oracle Spatial 10g: Advanced
375
Spatial Analysis and Mining: Spatial Binning
Oracle Spatial 10g: Advanced
376
Oracle Spatial 10g: Advanced 1-387
Spatial Binning A spatial bin is analogous to a tile. Spatial binning: Creates bins, and assigns a unique numeric ID to each bin Given a set of geometries, associates a bin ID to each geometry Each geometry assigned to one (and only one) bin Chooses most overlapping bin (if more than one equally overlap, picks one) The process (each step demonstrated in upcoming slides): Create a table to persistently store bin geometries. Add a column in the spatial layer table to hold the bin ID. Associate each geometry in a spatial layer with a bin ID. Aggregate data based on bin ID. As new geometries are added, assign corresponding bin IDs. Spatial Binning The term “spatial bin” is analogous to a tile. The spatial binning process: First creates a set of uniform, nonoverlapping bins. A numeric ID is assigned to each bin. Then, given a set of geometries, each geometry is associated to one (and only one) bin. The bin with the greatest area overlap is assigned to the geometry. In the case where two bins equally overlap a geometry, the binning process picks one. Spatial binning process steps (each of the following steps are discussed in detail in upcoming slides): Create a table to persistently store bin geometries. Add a numeric column in the table that contains the spatial layer. Associate each geometry in the spatial layer with a bin ID. Perform analysis by aggregating by bin ID. As new geometries are added, assign corresponding bin IDs. Oracle Spatial 10g: Advanced
377
SDO_SAM.TILED_BINS (Creates Bin Geometries)
SDO_REGIONSET = SDO_SAM.TILED_BINS( <LOWER_BOUND_X>,<UPPER_BOUND_X>, <LOWER_BOUND_Y>, <UPPER_BOUND_Y>, <TILING_LEVEL>, <SRID>) LOWER_BOUND_X, UPPER_BOUND_X LOWER_BOUND_Y, UPPER_BOUND_Y Lower and upper bounds of coordinate system to bin TILING_LEVEL The number of times to subdivide the coordinate system. Each increment causes every bin at the previous level to be subdivided into 4 bins (for a total of 4<TILING_LEVEL> bins). SRID Coordinate system to associate with each bin geometry Returns SDO_REGIONSET (described in the next slide) SDO_SAM.TILED_BINS (Creates Bin Geometries) SDO_SAM.TILED_BINS subdivides a user-specified coordinate system into a set of bin geometries. The following describes the parameters of SDO_SAM.TILED_BINS: <LOWER_BOUND_X>,<UPPER_BOUND_X> <LOWER_BOUND_Y>,<UPPER_BOUND_Y> Define the bounds of the coordinate system to subdivide. <TILING_LEVEL> The number of times to subdivide the coordinate system. Each increment causes every bin at the previous level to be subdivided into 4 bins (for a total of 4<TILING_LEVEL> bins). <SRID> Coordinate system to associate with each bin geometry SDO_SAM.TILED_BINS returns SDO_REGIONSET, described in the next slide. Oracle Spatial 10g: Advanced
378
Oracle Spatial 10g: Advanced 1-389
MDSYS.SDO_REGIONSET SQL> DESCRIBE mdsys.sdo_regionset MDSYS.SDO_REGIONSET TABLE OF MDSYS.SDO_REGION Name Type ID NUMBER GEOMETRY SDO_GEOMETRY ID Oracle-generated ID to uniquely identify bin geometry GEOMETRY Bin geometry MDSYS.SDO_REGIONSET MDSYS.SDO_REGIONSET returns a set of MDSYS.SDO_REGIONs (or bins). A unique ID is assigned to each bin geometry. Oracle Spatial 10g: Advanced
379
Spatial Binning Process: Example
Create a table to persistently store bin geometries. Populate the table with a call to SDO_SAM.TILED_BINS. This example creates 45 (or 1,024) bin geometries. CREATE TABLE bin_tiles AS SELECT a.id, a.geometry FROM TABLE(SELECT sdo_sam.tiled_bins( -180,180,-90,90, 5, 8307) FROM dual) a; Spatial Binning Process: Example Create a table and persistently store bin geometries created by SDO_SAM.TILED_BINS. The example in this slide subdivides a geodetic coordinate system, and creates 45 bin geometries. In this example, each bin geometry: Is associated with the SRID 8307, a WGS84 geodetic coordinate system Is assigned a unique numeric ID Oracle Spatial 10g: Advanced
380
Spatial Binning Process: Example
Add a BIN_ID column to a table with a spatial layer. BIN_ID is a foreign key to the table that contains the bin geometries (the BIN_TILES table). BIN_ID contains the ID of the associated bin geometry. Bin association can be accomplished with SDO_SAM.BIN_LAYER, discussed in the next slide. ALTER TABLE geod_cities ADD (bin_id NUMBER); Spatial Binning Process: Example (continued) Add a numeric column called BIN_ID to the table that contains the spatial layer to bin: ALTER TABLE geod_cities ADD (bin_id NUMBER); The BIN_ID is a foreign key to the table that contains the bin geometries (the BIN_TILES table created in the previous slide). The infrastructure is now set up, and the bin association can be accomplished with SDO_SAM.BIN_LAYER, discussed in the next slide. Oracle Spatial 10g: Advanced
381
SDO_SAM.BIN_LAYER (Associates Each Geometry with a Single Bin)
LAYER_TABLE_NAME, LAYER_COLUMN_NAME, BIN_TABLE_NAME, BIN_GEOMETRY_COLUMN_NAME, LAYER_BIN_ID_COLUMN_NAME); LAYER_TABLE_NAME and LAYER_COLUMN_NAME Identify the spatial layer to associate with bin geometries BIN_TABLE_NAME and BIN_GEOMETRY_COLUMN_NAME Identify the names of the table and column that contain the bin geometries LAYER_BIN_ID_COLUMN_NAME Numeric column added to spatial layer that contains the bin association SDO_SAM.BIN_LAYER (Associates Each Geometry with a Single Bin) SDO_SAM.BIN_LAYER compares each of the geometries in a spatial layer with a set of persistently stored bin geometries. Spatial binning works optimally with point data. If polygon data is binned, each geometry is assigned a single bin, which is the bin that is covered most completely by the polygon. If multiples bins are covered by the same amount, either of those bins may be chosen by SDO_SAM.BIN_LAYER. LAYER_TABLE_NAME and LAYER_COLUMN_NAME Identify the spatial layer to bin BIN_TABLE_NAME and BIN_GEOMETRY_COLUMN_NAME Identify the names of the table and column that contain the bin geometries LAYER_BIN_ID_COLUMN_NAME Column name that is added to the table that contains the spatial layer. This is the numeric column that gets populated (with a BIN_ID) when bins are associated with geometries. Oracle Spatial 10g: Advanced
382
Spatial Binning Process: Example
Associate a BIN_ID with each geometry in the GEOD_CITIES(LOCATION) spatial layer. The GEOD_CITIES table and the LOCATION column identify the spatial layer to associate. The BIN_TILES table and the GEOMETRY column identify the persistently stored bin geometries. BIN_ID is the column added to the GEOD_CITIES table that maintains the bin association. BEGIN SDO_SAM.BIN_LAYER('GEOD_CITIES','LOCATION', 'BIN_TILES','GEOMETRY', 'BIN_ID'); END; / Spatial Binning Process: Example The example in this slide associates a bin id with each geometry in the GEOD_CITIES (LOCATION) spatial layer. The BIN_ID column in the GEOD_CITIES table gets populated with a county’s associated bin. Oracle Spatial 10g: Advanced
383
Spatial Binning Process: Example
After BIN_ID is populated, perform geographic aggregation analysis. Sum the population associated with each bin, ordered by most populated bins. SELECT SUM(pop90) population_sum, bin_id FROM geod_cities GROUP BY bin_id ORDER BY population_sum DESC; POPULATION_SUM BIN_ID Spatial Binning Process: Example (continued) After spatial bin information has been completed, data can be analyzed using the spatial bin id to aggregate data. In the slide example, the sum of the population for each bin is returned, sorted by bins with the highest population down to the bins with the lowest population. Oracle Spatial 10g: Advanced
384
Spatial Binning Process: Example
Further drill-down analysis can be performed by creating bins based on the results of previous bin creation. For example, if bin 311 has the highest population, the geometry associated with bin 311 can be used as the input to create more bins. -- Get extent of bin 311, the extent to further drill down. SELECT geometry FROM bin_tiles WHERE id=311; -- Use extent of bin 311 to create 43 (or 64) new bins CREATE TABLE drill_down_bins AS SELECT a.id, a.geometry FROM TABLE(SELECT sdo_sam.tiled_bins( -78.75,-67.5,39.375,45,3,8307) FROM dual) a; -- Repeat analysis Spatial Binning Process: Example (continued) Further drill-down analysis can be performed by creating new bins based on the previous analysis, and re-binning the data of interest. For example, the previous analysis identified bin 311 as the bin with the highest population. The geometry identified with bin 311 can serve as the input extents to additional bin creation. The spatial layer data can be assigned to these new bins and further detailed analysis accomplished. Oracle Spatial 10g: Advanced
385
Oracle Spatial 10g: Advanced 1-396
SDO_SAM.BIN_GEOMETRY Associate a single geometry with a bin by calling SDO_SAM.BIN_GEOMETRY. GEOMETRY Identifies geometry to bin Tolerance Tolerance of geometry to bin BIN_TABLE_NAME and BIN_GEOMETRY_COLUMN_NAME Identify the bin geometry column The SDO_SAM.BIN_GEOMETRY function returns the bin ID associated with the geometry. number = SDO_SAM.BIN_GEOMETRY( GEOMETRY, TOLERANCE, BIN_TABLE_NAME, BIN_GEOMETRY_COLUMN_NAME) SDO_SAM.BIN_GEOMETRY If geometries in a binned spatial layer need to be changed or added, the SDO_SAM.BIN_GEOMETRY function can discover what bin to associate with a single geometry. This function takes a geometry, a tolerance, and the names of the table and column that contain the bin geometries as input, and returns a bin ID that can be stored in the table that contains the spatial layer. Oracle Spatial 10g: Advanced
386
Spatial Binning Process: Example
Insert a new city along with its associated BIN_ID. DECLARE geom SDO_GEOMETRY := SDO_GEOMETRY(2001, 8307, SDO_POINT_TYPE( , ,NULL), NULL, NULL); BEGIN INSERT INTO geod_cities VALUES ( geom,'New City','ST',329469,199, SDO_SAM.BIN_GEOMETRY(geom, 0.5, 'BIN_TILES','GEOMETRY')); END; / Spatial Binning Process: Example This example adds a new row into a table that contains a binned spatial layer. The bin ID of the newly added geometry is calculated by a call to SDO_SAM.BIN_GEOMETRY. Oracle Spatial 10g: Advanced
387
Spatial Analysis and Mining: Cluster Analysis
Oracle Spatial 10g: Advanced
388
Oracle Spatial 10g: Advanced 1-399
Clustering Analysis Spatial clustering generates patterns based on data density. Geometries are grouped by proximity to create cluster geometries. Cluster geometries can help perform analysis in applications related to: Epidemiology (identifying disease occurrence patterns) Law enforcement (identifying crime patterns) Others Clustering Analysis Spatial clustering generates patterns based on data density. Geometries are grouped by proximity to create cluster geometries. Spatial clustering analysis is performed in many applications, including those associated with: Epidemiology, to identify patterns associated with disease occurrence Law enforcement, to identify crime patterns Oracle Spatial 10g: Advanced
389
SDO_SAM.SPATIAL_CLUSTERS
SDO_REGIONSET = SDO_SAM.SPATIAL_CLUSTERS( TABLE_NAME, COLUMN_NAME, MAX_CLUSTERS [,ALLOW_OUTLIERS [, PARTITION_NAME]]) Spatial clustering generates patterns based on data density. Geometries in a spatial layer are grouped by proximity to create cluster geometries. Result is of type SDO_REGIONSET (discussed in an earlier slide). SDO_REGIONSET is a TABLE of (ID, geometry) pairs. SDO_SAM.SPATIAL_CLUSTERS SDO_SAM.SPATIAL_CLUSTERS generates patterns based on data density. Geometries in a spatial layer are grouped by proximity to create cluster geometries. The result of SDO_SAM.SPATIAL_CLUSTERS is of type SDO_REGIONSET (discussed in an earlier slide). SDO_REGIONSET is a table of (ID, geometry) pairs, where each geometry represents a cluster boundary. Oracle Spatial 10g: Advanced
390
SDO_SAM.SPATIAL_CLUSTERS Parameters
TABLE_NAME and COLUMN_NAME Identify the spatial layer to cluster MAX_CLUSTERS The maximum number of clusters to create ALLOW_OUTLIERS (optional) Include all geometries (including outliers) in cluster generation Default is TRUE If it is set to FALSE, outliers are ignored PARTITION_NAME (optional) Clusters a single partition of a partitioned table SDO_SAM.SPATIAL_CLUSTERS Parameters The following describes the parameters of the SDO_SAM.SPATIAL_CLUSTERS function: TABLE_NAME and COLUMN_NAME Identify the spatial layer to cluster MAX_CLUSTERS The maximum number of clusters to create ALLOW_OUTLIERS (optional) TRUE by default; includes all geometries in cluster generation If it is set to FALSE, outliers (or isolated geometries that deviate from most of the others) are ignored in cluster generation. PARTITION_NAME(optional) Clusters a single partition of a partitioned table Oracle Spatial 10g: Advanced
391
SDO_SAM.SPATIAL_CLUSTERS
Cluster the GEOD_CITIES(LOCATION)layer into four regions: SELECT a.id, a.geometry FROM TABLE (SELECT sdo_sam.spatial_clusters( 'GEOD_CITIES','LOCATION', 4) FROM dual) a; ========= 1 SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY( , , , , , , , , , , , , , , , , , )) . Cluster the GEOD_CITIES(LOCATION)layer into four regions SDO_SAM.SPATIAL_CLUSTERS Cluster the geometries in the GEOD_CITIES(LOCATION) spatial layer table into four optimal clusters. The result in this slide displays the first of the four cluster polygons returned. Oracle Spatial 10g: Advanced
392
Oracle Spatial 10g: Advanced 1-403
Summary In this lesson, you should have learned about the following types of analysis available with Oracle Spatial Analysis and Mining: Neighborhood analysis Spatial binning Spatial clustering Summary This section introduced the concepts associated with Oracle Spatial Analysis and Mining. It described neighborhood analysis, spatial binning, spatial clustering, and colocation analysis. Oracle Spatial 10g: Advanced
393
Oracle Spatial 10g Enhancements
Appendix A Oracle Spatial 10g Enhancements
394
Oracle Spatial 10g: Advanced 1-405
Objectives After completing this lesson, you should be able to understand the following Oracle Spatial 10g enhancements: R-tree enhancements New/updated spatial operators New geometry types New spatial utility functions New LRS functions and updates Other miscellaneous enhancements Objectives This is a summary of the enhancements discussed in this lesson. In the subsequent lessons of Oracle Spatial 10g: Advanced you learn about the other major features in Oracle Spatial. Oracle Spatial 10g: Advanced
395
Oracle Spatial 10g: Advanced 1-406
R-tree Enhancements Oracle Spatial 10g: Advanced
396
Oracle Spatial 10g: Advanced 1-407
R-tree Enhancements R-tree enhancements include: Concurrency Performance Parallelism Partitioning R-tree Index Sizing function Work tablespace Nonleaf index table Oracle Spatial 10g: Advanced
397
Oracle Spatial 10g: Advanced 1-408
Concurrency Oracle Spatial 10g: Advanced
398
Oracle Spatial 10g: Advanced 1-409
R-tree Concurrency Concurrency before Oracle Spatial 10g: Updating an indexed SDO_GEOMETRY column from multiple sessions tended to cause lock waits. There were two ways to avoid these wait states: Serializing all INSERTs/UPDATEs/DELETEs through a single session Committing after each INSERT/UPDATE/DELETE operation, if issued from multiple sessions These wait states are eliminated in Oracle Spatial 10g Conflicts are resolved automatically Multiple session INSERTs/UPDATEs/DELETEs are fully supported without a commit after each operation R-tree Concurrency Before Oracle Spatial 10g: If multiple concurrent sessions updated data when using R-tree indexes, wait states due to locking could occur. There were two ways to avoid these lock waits: Ensuring that all updates to the same indexed SDO_GEOMETRY column occurred in the same Oracle session Committing after each update if multiple sessions were issuing updates to the same indexed SDO_GEOMETRY column In Oracle Spatial 10g: In Oracle Spatial 10g, R-tree index lock waits are eliminated. Conflicts between updates within the R-tree are automatically resolved. Multiple sessions are supported for all DML INSERT, UPDATE, and DELETE operations. Oracle Spatial 10g: Advanced
399
Improved R-tree Index: Performance of INSERT/UPDATE/DELETE
Oracle Spatial 10g: Advanced
400
Improved R-tree Performance: INSERT/UPDATE/DELETE
R-tree indexes in Oracle Spatial 10g offer improved performance for INSERT, UPDATE, and DELETE operations. Index updates within a transaction are not directly applied to the spatial index table. There is an option for intermediate storage. All index changes are batched at commit time: Longer commit time, but shorter elapsed time Improvements occur when a large number of pending changes are committed in a transaction: Transactions with few changes may not benefit as much from the index batching enhancement. Improved R-tree Performance In Oracle Spatial 10g, the performance of the INSERT, UPDATE, and DELETE operations is improved on tables with spatial indexes. Index updates are not directly applied to the spatial index table, but are included in intermediate storage. Spatial index changes are batched into the database at commit time, resulting in faster end-to-end performance, but longer commit times. Performance improvements occur when a large number of pending changes are committed. Transactions with few changes to the spatial index (few INSERTS/UPDATES/DELETES of SDO_GEOMETRY data) will not share the performance benefits of this enhanced model. Oracle Spatial 10g: Advanced
401
Improved R-tree Performance: INSERT/UPDATE/DELETE
More features of improved performance: Queries in the same session consider all pending index changes (including intermediate storage). Queries outside the editing session do not consider the pending index changes, as expected. When the pending changes are committed, all the changes can be seen from the other sessions. For optimal performance, commit after a large number of changes (approximately 2,000). Improved R-tree Performance (continued) Oracle Spatial queries see the pending changes based on normal transaction rules, and changes are not seen outside the context of the user’s transaction. Oracle Spatial 10g: Advanced
402
R-tree Index Sizing Function Work Tablespace
Oracle Spatial 10g: Advanced
403
R-tree Index Sizing Function
ESTIMATE_RTREE_INDEX_SIZE function is introduced for estimating R-tree index size based on existing table, or knowledge about a table: SIZE(Mb) = SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE (SCHEMA, TABLE_NAME, COLUMN_NAME [,PARTITION_NAME]) or (NUMBER_OF_GEOMS, DB_BLOCK_SIZE [,SDO_RTR_PCTFREE] [,NUM_DIMENSIONS] [,IS_GEODETIC]) R-tree Index Sizing Function A new function called SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE is provided in Oracle Spatial 10g to help users, applications, and DBAs to estimate the size of an R-tree index before it is built. Oracle Spatial 10g: Advanced
404
SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE
SCHEMA The owner of the table TABLE_NAME The name of the table COLUMN_NAME The name of the SDO_GEOMETRY column in the table TABLE_NAME PARTITION_NAME The name of the partition NUMBER_OF_GEOMS The number of rows in the table SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE These are the parameters for SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE: SCHEMA_NAME: The owner of the table TABLE_NAME: The name of the table COLUMN_NAME: The name of the column of type SDO_GEOMETRY in the TABLE_NAME table PARTITION_NAME: The name of the partition for which you want to estimate the index size NUMBER_OF_GEOMS: The number of rows in the table Oracle Spatial 10g: Advanced
405
SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE
DB_BLOCK_SIZE The DB_BLOCK_SIZE of the tablespace that will contain the index table SDO_RTR_PCTFREE The amount of free space to be left in the index table (default: 10) NUM_DIMENSIONS The number of dimensions to be indexed (default: 2) IS_GEODETIC If the data being indexed is geodetic, set to 1; otherwise set to 0 (default: 0) SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE (continued) These are the parameters for SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE: DB_BLOCK_SIZE: The DB_BLOCK_SIZE of the tablespace that will contain the index table SDO_RTR_PCTFREE: The amount of free space to be left in the index table (default: 10) NUM_DIMENSIONS: The number of dimensions to be indexed (default: 2) IS_GEODETIC: If the data being indexed is geodetic, set to 1; otherwise set to 0 (default: 0) Oracle Spatial 10g: Advanced
406
R-tree Index Sizing: Examples
Estimate the size of an R-tree index for a user SCOTT on the GEOD_COUNTIES table with the column GEOM: Estimate the size of an R-tree index on a table with 250,000 geometries, 8 KB DB_BLOCK_SIZE, SDO_RTR_PCTFREE 15, two dimensional data, and a geodetic SRID: SELECT SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE ('SCOTT','GEOD_COUNTIES','GEOM') FROM dual; SELECT SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE (250000, 8192, 15, 2, 1) FROM dual; R-tree Index Sizing: Examples The examples in the slide show you the usage of the function for a given table that is already loaded and also the function is showing information about a table. The top example shows the usage of the SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE function for a table that is already loaded. The bottom example shows the usage of the SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE function using parameters describing the R-tree index to be created. Oracle Spatial 10g: Advanced
407
R-tree Index Sizing: Usage Notes and WORK_TABLESPACE
The number returned estimates the size of the R-tree index table (in MB). During R-tree index creation, users may require three times the size returned. Users or applications can control where the extra 2X space is used via a new CREATE INDEX parameter: WORK_TABLESPACE=<TABLESPACE_NAME> CREATE INDEX tablename_sidx ON tablename(geometry) INDEXTYPE IS MDSYS.SPATIAL_INDEX PARAMETERS('work_tablespace = my_work_tbs'); R-tree Index Sizing: Usage Notes and WORK_TABLESPACE The SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE function returns a number that estimates the size of the R-tree index, given the set of input parameters. During index creation, up to three times the estimated size is needed for various temporary tables used during spatial index creation (note: these tables are never put in the TEMP tablespace) . Users can control where that extra space is written to by using the WORK_TABLESPACE spatial parameter of the CREATE INDEX command. If this parameter is not specified, all temporary tables go in the tablespace the user specifies for the index, or, if no tablespace is specified, in the user’s DEFAULT tablespace. Oracle Spatial 10g: Advanced
408
R-tree Nonleaf Index Table
Oracle Spatial 10g: Advanced
409
R-tree Nonleaf Index Table
For reasons of performance, a DBA can pin R-tree index tables in memory. An R-tree index table can be very big. The SDO_NON_LEAF_TBL parameter allows a DBA to break the R-tree index into two during index creation: Nonleaf table (smaller table) Leaf table (ROWID and MBR) The nonleaf table can be pinned in memory. The leaf table can cache its blocks when they are accessed via ordinary Oracle data block caching. R-tree Nonleaf Index Table In a limited set of workloads and applications, a DBA may pin a table in memory for optimal performance. An R-tree index table is like any other table, and can be pinned in memory. R-tree index tables can be very large, making it impractical to pin the entire R-tree index table in memory. Specifying SDO_NON_LEAF_TBL=TRUE in the parameter list of the CREATE INDEX statement causes the index table to be split into two pieces: A nonleaf index table, which is the smaller of the two tables and contains all of the higher level R-tree nodes (except for the leaf nodes). Because this table is always accessed during spatial queries, caching it in memory can help query performance. A leaf index table, which contains the ROWID and MBR for each of the geometries indexed The DBA can then pin the nonleaf table in memory, allowing the leaf table to be cached with ordinary Oracle data block caching. Oracle Spatial 10g: Advanced
410
R-tree Nonleaf Index Table Example
-- Create the index CREATE INDEX geod_counties_sidx ON geod_counties(geom) INDEXTYPE IS MDSYS.SPATIAL_INDEX PARAMETERS ('sdo_non_leaf_tbl=TRUE'); -- Find the non leaf index table name SELECT sdo_nl_index_table FROM user_sdo_index_metadata WHERE sdo_index_name='GEOD_COUNTIES_SIDX'; MDNT_A930$ -- Pin the table in memory ALTER TABLE MDNT_A930$ STORAGE(BUFFER_POOL KEEP); R-tree Nonleaf Index Table: Example Here you see an example of a CREATE INDEX statement with a spatial parameter (sdo_non_leaf_tbl) that forces the creation of a nonleaf index table. The example also demonstrates how to pin the nonleaf index table in memory. Oracle Spatial 10g: Advanced
411
Oracle Spatial 10g: Advanced 1-422
New Operators Oracle Spatial 10g: Advanced
412
Oracle Spatial 10g: Advanced 1-423
Spatial Join A spatial join is used to compare all the geometries in one layer with all the geometries in another layer. Also useful when comparing most of one layer with all or most of another layer Very similar to an operator: Requires two R-tree indexed layers A spatial join is used in the FROM clause. Spatial Join Oracle Spatial 10g includes a new spatial join function. The spatial join function is used to join all the geometries in one layer with all the geometries in another layer. The function behaves much like an operator because it requires layers passed in to be indexed. The indexes must be R-tree indexes of the same dimensionality with the same spatial reference ID (SRID). The join function takes all the rows in one layer and compares them with all the rows in the other layer. The driver table is determined automatically by Oracle Spatial. The SDO_JOIN table function uses the R-tree height to determine the relative size of the two tables involved in the query and uses the smaller table as the driver table. Additionally, if the heights are the same, and a table with LAYER_GTYPE=POLYGON or LAYER_GTYPE=MULTIPOLYGON exists, it is used as the driver table. Oracle Spatial 10g: Advanced
413
Oracle Spatial 10g: Advanced 1-424
Spatial Join SDO_JOIN( <table_name-1>, <column_name-1>, <table_name-2>, <column_name-2> [,'parameters'] [, preserve_join_order]) RETURN SDO_ROWIDSET SQL> DESCRIBE SDO_ROWIDSET SDO_ROWIDSET TABLE OF MDSYS.SDO_ROWIDPAIR Name Null? Type ROWID VARCHAR2(24) ROWID VARCHAR2(24) Spatial Join (continued) The results of the spatial join are ROWID pairs that match the join condition between the two tables. Oracle Spatial 10g: Advanced
414
SDO_JOIN Syntax: Arguments
<table_name-1>, <table_name-2> Tables that contain the SDO_GEOMETRY columns <column_name-1>, <column_name-2> Indexed columns of type SDO_GEOMETRY PARAMETERS (optional): Any one of the following: If not specified, SDO_JOIN does a primary filter operation 'MASK=<mask>': Similar to SDO_RELATE SDO_JOIN Syntax: Arguments <table_name-n>: Specifies each of the tables that contain the SDO_GEOMETRY column. <column_name-n>: Specifies the indexed SDO_GEOMETRY column associated with TABLE_NAME-N. PARAMETERS (optional): Any one of the following: If no parameters are specified, SDO_JOIN matches all the geometries in one table with all the geometries in the other table based only on comparing geometry approximations stored in the index (filter operation). MASK=<mask>: The mask specification is the relationship of COLUMN_NAME-1 to COLUMN_NAME-2. Valid mask specifications include the following: TOUCH OVERLAPBDYDISJOINT OVERLAPBDYINTERSECT EQUAL INSIDE Oracle Spatial 10g: Advanced
415
SDO_JOIN Syntax: Arguments
PARAMETERS (continued) 'DISTANCE_SPEC': Similar to SDO_WITHIN_DISTANCE DISTANCE=N [UNIT=DISTANCE_UNIT] PRESERVE_JOIN_ORDER (optional): SDO_JOIN does not automatically adjust the order in which the tables are joined. The second table-and-column pair is the driving table. SDO_JOIN Syntax: Arguments (continued) PARAMETERS (continued) MASK=<mask> (continued): COVEREDBY CONTAINS COVERS ANYINTERACT ON Masks can be ORed together. For example, use MASK=INSIDE+COVEREDBY to OR together the INSIDE and COVEREDBY masks. DISTANCE_SPEC: Use the DISTANCE parameter to invoke a “within distance” join query. The distance corresponds to the maximum distance two geometries can be apart from each other. PRESERVE_JOIN_ORDER: Preserves the join order of tables. To optimize spatial joins, Oracle Spatial makes an educated guess as to which tables should be the driving tables. If you do not want Oracle Spatial to alter the join order of the tables, then specify PRESERVE_JOIN_ORDER. When PRESERVE_JOIN_ORDER is specified, the second table and column pair is the driving table. That is, for each geometry in the second layer, the index of the first layer is searched. Oracle Spatial 10g: Advanced
416
Oracle Spatial 10g: Advanced 1-427
Spatial JOIN: Example Find all the city and county pairs that have any interaction: SELECT /*+ ordered */ a.city, b.county FROM TABLE(SDO_JOIN( 'GEOD_COUNTIES', 'GEOM', 'GEOD_CITIES', 'LOCATION', 'MASK=ANYINTERACT')) c, geod_cities a, geod_counties b WHERE c.rowid1 = b.rowid AND c.rowid2 = a.rowid ORDER BY a.city; Spatial JOIN: Example In this example all the city and county pairs are returned where cities and counties interact. The TABLE syntax flattens the SDO_ROWIDSET returned by SDO_JOIN into ROWID1, ROWID2 pairs. The TABLE keyword flattens SDO_ROWIDSET returned by SDO_JOIN into ROWID1, ROWID2 pairs. Oracle Spatial 10g: Advanced
417
Oracle Spatial 10g: Advanced 1-428
Spatial JOIN: Example Find all cities within 10 miles of all interstate highways: SELECT /*+ ordered */ a.city, b.highway FROM TABLE(SDO_JOIN( 'GEOD_INTERSTATES', 'GEOM', 'GEOD_CITIES', 'LOCATION', 'DISTANCE=10 UNIT=MILE')) c, geod_cities a, geod_interstates b WHERE c.rowid1 = b.rowid AND c.rowid2 = a.rowid ORDER BY a.city; Spatial JOIN: Example (continued) In this second example all the (city, highway) pairs are returned where cities are within 10 miles of a highway. The TABLE keyword flattens SDO_ROWIDSET returned by SDO_JOIN into ROWID1, ROWID2 pairs. Oracle Spatial 10g: Advanced
418
Simplified Relationship Operators
In Oracle Spatial 10g, all SDO_RELATE mask values have corresponding operators: <RELATIONSHIP> can be: ANYINTERACT, INSIDE, COVERS, ON, COVEREDBY, CONTAINS, OVERLAPBDYDISJOINT, OVERLAPBDYINTERSECT, TOUCH, or EQUAL New: OVERLAPS to find any overlapping relationship. GEOMETRY-1 An indexed column in a table of type SDO_GEOMETRY GEOMETRY-2 A variable or column in a table of type SDO_GEOMETRY SDO_<RELATIONSHIP> (<geometry-1>, <geometry-2>) = 'TRUE' Simplified Relationship Operators In Oracle Spatial 10g, there are new operators associated with each of the named topological relationships supported in Oracle Spatial. These new operators are a simplified alternative to the SDO_RELATE operator. <RELATIONSHIP> can take on any of the values passed in as a mask to SDO_RELATE: SDO_<RELATIONSHIP> (GEOMETRY-1,GEOMETRY-2) = 'TRUE' GEOMETRY-1 is the spatially indexed layer to be searched GEOMETRY-2 is the query window, which can be a variable or column in a table of type SDO_GEOMETRY. Here you see the addition of a new mask associated only with the operator SDO_OVERLAPS. Overlap finds any overlapping relationship (OVERLAPBDYINTERSECT+OVERLAPBDYDISJOINT). This simplifies the searches for overlap relationships. Oracle Spatial 10g: Advanced
419
Relationship Operators: Example
Find all the counties around Passaic County in New Jersey: SELECT /*+ ordered */ a.county FROM geod_counties b, geod_counties a WHERE b.county = 'Passaic' AND b.state = 'New Jersey' AND SDO_TOUCH(a.geom,b.geom) = 'TRUE'; Previously: . . . AND SDO_RELATE(a.geom,b.geom, 'MASK=TOUCH QUERYTYPE=WINDOW') = 'TRUE'; Relationship Operators: Example The example in the slide returns all the counties that have a touch relationship with Passaic County in New Jersey. The example in the slide uses the SDO_TOUCH operator: SDO_TOUCH(a.geom,b.geom)= 'TRUE' The SDO_TOUCH operator is a simplified version of SDO_RELATE with the TOUCH mask: SDO_RELATE(a.geom, b.geom, 'mask=touch querytype=window') = 'TRUE' Oracle Spatial 10g: Advanced
420
QUERYTYPE=WINDOW Default for SDO_RELATE and SDO_FILTER
In Oracle Spatial 10g, SDO_FILTER and SDO_RELATE no longer require specifying QUERYTYPE=WINDOW SELECT c.city, c.pop90 FROM proj_cities c WHERE sdo_filter ( c.location, mdsys.sdo_geometry (2003, 32775, null, mdsys.sdo_elem_info_array (1,1003,3), mdsys.sdo_ordinate_array ( , , , ))) = 'TRUE'; SELECT /*+ ordered */ b.county, b.state_abrv FROM geod_states a, geod_counties b WHERE a.state = 'New Hampshire' AND sdo_relate (b.geom, a.geom, 'mask=TOUCH')='TRUE'; QUERYTYPE=WINDOW Default for SDO_RELATE and SDO_FILTER Prior to Oracle Spatial 10g, SDO_FILTER and SDO_RELATE required specifying QUERYTYPE=WINDOW. The examples above show the use of SDO_FILTER and SDO_RELATE without specifying QUERYTYPE=WINDOW. Oracle Spatial 10g: Advanced
421
Oracle Spatial 10g: Advanced 1-432
New Geometry Types Oracle Spatial 10g: Advanced
422
Geodetic Optimized Rectangle Support
New support for geodetic data Example: Internally, Oracle Spatial and Oracle Locator: Densify along a constant latitude in one-degree increments May divide a large optimized rectangle into a multi-element geometry, where each element is guaranteed to be smaller than half the Earth’s surface area Can span the 180-degree meridian, but not the poles SDO_GEOMETRY(2003,8307,NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(-112,33,-86,40)) Geodetic Optimized Rectangle Support Optimized rectangles are now supported with geodetic data. Internally, Oracle Spatial densifies geometries at one-degree intervals along a constant latitude. Oracle Spatial may divide a single large optimized rectangle into a multi-element geometry, where each element is guaranteed to be smaller than half the surface area of the Earth (to conform to the rules of geodetic polygons). A geodetic optimized rectangle can span the 180-degree meridian, but cannot span the poles. Oracle Spatial 10g: Advanced
423
Geodetic Optimized Rectangle Densified Along Latitude Lines
(-112,33) (-86,40) The user specifies lower-left and upper-right rectangle vertices. Oracle Spatial derives lower-right, and upper-left vertices. Lines that follow a longitude line implicitly follow a geodesic. Oracle Spatial densifies along latitude lines at one-degree intervals (shown as a dotted black line) instead of following the geodesic (shown as the two curved lines, as indicated by the arrows). Geodetic Optimized Rectangle Densified Along Latitude Lines For geodetic optimized rectangles, users specify the lower-left and upper-right vertices. The upper-left and lower-right vertices are derived by Oracle Spatial. In general, when creating a geometry associated with a geodetic coordinate system, Oracle Spatial considers geodesic distances between consecutive vertices. But the geodetic optimized rectangle is an exception. The north-to-south line segments in the optimized rectangle run along constant longitude lines. Lines of longitude implicitly follow a geodesic. The desired effect for east-to-west lines is that they follow a constant latitude. Except for along the equator, lines of latitude do not follow a geodesic. To accomplish the desired effect for an east-to-west line to stay close to a constant line of latitude, Oracle Spatial densifies the east-to-west lines at one-degree intervals along the latitude line. Oracle Spatial 10g: Advanced
424
Geodetic Optimized Rectangle Densified Along Latitude Lines
Densified line from previous slide, zoomed in: Oracle Spatial still uses geodesics between vertices along the densified line at one-degree intervals. If your application requires more accuracy than one-degree intervals, create your own densified polygon (do not use the geodetic optimized rectangle). Geodetic Optimized Rectangle Densified Along Latitude Lines (continued) The internal representation of the geodetic optimized rectangle densifies at one degree intervals along constant lines of latitude. When performing spatial analysis, Oracle Spatial still considers geodesics between the densified vertices. If your application requires following a constant line of latitude more closely than one-degree densification, do no use the geodetic optimized rectangle. Instead, create your own polygon densified along constant latitudes at an interval smaller than one degree. Oracle Spatial 10g: Advanced
425
Geodetic Optimized Rectangle
For geodetic optimized rectangles equal to or larger than half the Earth’s surface area: The internal spatial representation is a multipolygon Limit use to: SDO_FILTER SDO_RELATE with the ANYINTERACT mask SDO_ANYINTERACT Geodetic Optimized Rectangle Here you see an example of a possible internal representation of a geodetic optimized rectangle. Note that the internal representation may be a multipolygon whose edges touch. This is done to ensure that each of the polygon elements of the returned geometry has an area less than half the Earth’s surface area. Because the interior of the original optimized rectangle may get broken up into a geodetic multipolygon geometry, the new geometry should be used only for the following operations: As a window for SDO_FILTER queries As a window for SDO_RELATE queries, but only for the ANYINTERACT mask As a window for SDO_ANYINTERACT Oracle Spatial 10g: Advanced
426
Geodetic Optimized Rectangle Support
Eliminates the need for VIEWPORT_TRANSFORM Storing as persistent object not recommended Use only with: SDO_FILTER SDO_RELATE with ANYINTERACT mask SDO_ANYINTERACT Geodetic Optimized Rectangle Support Because a single optimized rectangle can be transformed internally in Spatial into multiple smaller elements, Oracle Corporation recommends that geodetic optimized rectangles should not be stored as persistent objects. When using the optimized rectangle as a query window in an operator, it should be used only with: SDO_FILTER SDO_RELATE with the ANYINTERACT mask SDO_ANYINTERACT Oracle Spatial 10g: Advanced
427
Oriented Point Support
Oriented points are typically used for orienting symbology or text for maps and other display applications. An oriented point includes: The coordinates of the point An additional set of coordinates that define the orientation vector. The origin (0,0) of the orientation vector is located at the coordinates of the point it is associated with. SDO_ELEM_INFO_ARRAY contains two triplets: The first triplet describes the point, and includes: The ordinate offset Element type of 1 (for point) Interpretation of 1 (single point) The second triplet describes the orientation, and includes: The ordinate offset of the point used for orientation Interpretation of 0 (exclusively used for the orientation) Oriented Point Support Oriented points are useful for orienting symbology used in mapping and other display applications. Oriented points contain coordinates for the point being stored as well as a set of coordinates that define the orientation vector. The origin (0,0) of the orientation vector is located at the point associated with the vector. The orientation vector is used to orient symbology and/or text for labeling in mapping and other display applications. The SDO_ELEM_INFO_ARRAY for an oriented point contains two triplets. The first triplet has: The element offset of the point An element type of 1 (to denote a point element type) An interpretation of 1 (single point) The second triplet has: The element offset for the orientation vector An interpretation of 0 to specify that this is an orientation vector for the point Oracle Spatial 10g: Advanced
428
Oriented Point Support
Oriented point example: The point location is (71, 42). A symbol associated with the point would be oriented along a vector from (71, 42) through (72, 43), at a 45 degree angle. SDO_GEOMETRY(2001, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1,1, 3,1,0), SDO_ORDINATE_ARRAY(71, 42, 1, 1)) 71,42 Oriented Point Support (continued) Oriented points contain coordinates for the point being stored as well as a set of coordinates that are relative to the point specified. The relative coordinates are used to orient symbology for mapping and other display applications. Given the coordinates of the orientation vector (i,j), the following equation can be used to calculate the orientation vector angle: Angle = arctan (j/i) In the orientation vector example above, arctan (1/1) = 45 degrees. Oracle Spatial 10g: Advanced
429
Oriented Point Support
The rules for creating oriented points are: The point must be followed by its orientation. The origin (0,0) of the orientation vector is located at the coordinates of the point it is associated with. Multipoint oriented points are allowed, but orientation information must follow the point being oriented. The orientation vector values must be between –1 and 1. Oracle Spatial 10g: Advanced
430
Oriented Point Support
Oriented point rules (continued): A 2D point will have a 2D orientation vector. A 2D point with an LRS measure (SDO_GTYPE=3301) will have a 2D orientation vector. A 3D point (SDO_GTYPE=3001) will have a 3D orientation vector. A 3D point with an LRS measure (SDO_GTYPE=4401) will have a 3D orientation vector. A 4D point (SDO_GTYPE=4001) will have a 3D orientation vector. Oriented Point Support (continued) The rules for oriented points related to dimensionality are shown above. Oracle Spatial 10g: Advanced
431
Oracle Spatial 10g: Advanced 1-442
New Utility Functions Oracle Spatial 10g: Advanced
432
Oracle Spatial 10g: Advanced 1-443
SDO_UTIL.SIMPLIFY Applies the Douglas-Peucker algorithm to generate a less detailed geometry: GEOMETRY: The geometry to be simplified THRESHOLD: Removes vertices from a segment that deviate less than or equal to the threshold value: The smaller the threshold value, the more similar the returned geometry is to the input geometry. The larger the threshold value, the fewer the points in the returned geometry. GEOM = SDO_UTIL.SIMPLIFY(GEOMETRY, THRESHOLD) SDO_UTIL.SIMPLIFY Oracle Spatial 10g includes a new geometry generalization routine named SDO_UTIL.SIMPLIFY. This routine accepts a geometry and a threshold and returns a generalized geometry with less granularity than the original geometry. The generalization is based on the Douglas-Peucker line simplification algorithm. The threshold value is used to determine how much simplification is done. If very small threshold values are used, the simplified geometry may be very close to the original geometry. As the threshold values get larger, the returned geometry has fewer coordinates and the geometry is more coarse. The geometry simplification routines work with line and polygon geometries as input. You use the simplification routines when the use of generalized data is preferable to higher resolution data. For example, assume that you have a layer with very detailed polygon regions (about 3,000 vertices in each polygon). When you are zoomed out very far, it does not make sense to display these very detailed polygons. The detail of the polygons is lost because the many coordinates in these polygons are being forced to render onto just a few pixels. Instead, create a simplified layer (generalized version of the detailed polygons). The generalized layer is displayed when you are zoomed out very far, and the detailed layer is displayed when you are zoomed closer in. Oracle Spatial 10g: Advanced
433
Oracle Spatial 10g: Advanced 1-444
SDO_UTIL.SIMPLIFY Can be applied to lines or polygons Does not alter the tolerance at which data is validated Adjacent polygons with registered edges may not register after generalization SDO_UTIL.SIMPLIFY (continued) Note that if the boundaries of adjacent polygons are registered before the simplification process, the boundaries in resulting geometries may no longer be registered. The simplification routines are used when generalized data is preferable to higher resolution data. For example, when zoomed out to an area that shows 100 counties in the United States, drawing all 100 counties at full resolution may be time-consuming, and the data may not be displayed at full resolution due to screen pixel density limitations. Saving the simplified, coarser data for display may be appropriate for this case. When zoomed in very close, perhaps to look at details of a county boundary, then displaying data at full resolution may be required, so the original higher-density data would be used. Oracle Spatial 10g: Advanced
434
SDO_UTIL.SIMPLIFY: Example
Generalize the given line segment: SELECT SDO_UTIL.SIMPLIFY( SDO_GEOMETRY(2002,NULL,NULL, SDO_ELEM_INFO_ARRAY(1,2,1), SDO_ORDINATE_ARRAY(1,1, 4,1, 7,2, 10,1)), 1) FROM DUAL; Returns: SDO_GEOMETRY(2002, NULL, NULL, SDO_ORDINATE_ARRAY(1, 1, 10, 1)) SDO_UTIL.SIMPLIFY: Example In this example, the line string that is nearly straight with four coordinates simplifies to a straight line with two coordinates. Even though all the points in the original geometry were more than one unit apart in distance, the line still became more simplified by specifying a threshold of one. This is because the algorithm removes vertices from a segment that deviate less than or equal to the threshold value. It is important to note that line segments can be generalized to single points, and that polygons can be generalized to lines or points. Note: It is possible for polygons to simplify to lines or points. Oracle Spatial 10g: Advanced
435
SDO_UTIL.ELLIPSE_POLYGON Parameters
Returns a geodetic polygon that approximates and is covered by the specified ellipse: CENTER_LONGITUDE and CENTER_LATITUDE Define the center point of the ellipse GEOM = SDO_UTIL.ELLIPSE_POLYGON ( CENTER_LONGITUDE, CENTER_LATITUDE, SEMI_MAJOR_AXIS, SEMI_MINOR_AXIS, AZIMUTH, ARC_TOLERANCE) SDO_UTIL.ELLIPSE_POLYGON Parameters The SDO_UTIL.ELLIPSE_POLYGON function returns a polygon that approximates and is covered by the specified ellipse. The signature for this function is shown in the slide. CENTER_LONGITUDE and CENTER_LATITUDE define the center point of the ellipse. Oracle Spatial 10g: Advanced
436
SDO_UTIL.ELLIPSE_POLYGON Parameters
SEMI_MAJOR_AXIS and SEMI_MINOR_AXIS The largest and smallest distances from the center of the ellipse (in meters) Semi-major axis Semi-minor axis SDO_UTIL.ELLIPSE_POLYGON Parameters (continued) <SEMI_MAJOR_AXIS> is the maximum distance from the center of the ellipse to the boundary of the ellipse. <SEMI_MINOR_AXIS> is the minimum distance from the center of the ellipse to the boundary of the ellipse. Oracle Spatial 10g: Advanced
437
SDO_UTIL.ELLIPSE_POLYGON Parameters
45) AZIMUTH Clockwise rotation of the major axis from north, in degrees. It is a numeric value from 0 to 180. ARC_TOLERANCE The maximum deviation between the specified ellipse and the polygon that approximates it. SDO_UTIL.ELLIPSE_POLYGON Parameters (continued) <AZIMUTH> is the number of degrees to rotate the major axis of the returned geometry clockwise from north. For example, set the azimuth to 90 to rotate the major axis so that it is aligned with the x axis. The valid values for azimuth are 0 to 180. <ARC_TOLERANCE> is the maximum distance between the specified ellipse and the line segments of the polygon that approximate it. A polygon that covers the ellipse can be generated by adding the arc tolerance to each of the <SEMI_MAJOR_AXIS> and the <SEMI_MINOR_AXIS>, and specifying each of the new values as the <SEMI_MAJOR_AXIS> and the <SEMI_MINOR_AXIS>. Oracle Spatial 10g: Advanced
438
SDO_UTIL.ELLIPSE_POLYGON: Example
Returns geometry in WGS 84 (SDO_SRID=8307) SELECT SDO_UTIL.ELLIPSE_POLYGON( , , 5000, 4000, 90, 200) FROM dual; SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY( , , , , , , , , , , , , , , , , , , , , , , , , , )) SDO_UTIL.ELLIPSE_POLYGON Example The graphic contains an example of the use of SDO_UTIL.ELLIPSE_POLYGON. The function returns a polygon in the WGS 84 coordinate system. This example includes the following parameters: The center point of the ellipse is – degrees longitude, and degrees latitude. The semi-major axis is 5,000 meters. The semi-minor axis is 4,000 meters. The output polygon is rotated 90 degrees, causing the major axis to be parallel to the x axis. The output geometry does not deviate by more than 200 meters from the actual ellipse that was specified. Oracle Spatial 10g: Advanced
439
Oracle Spatial 10g: Advanced 1-450
New Utility Functions SDO_UTIL.POLYGONTOLINE Generates a new geometry by converting all polygon elements in a geometry to line elements, and sets the proper SDO_GTYPE SDO_UTIL.REMOVE_DUPLICATE_VERTICES Generates a new geometry by removing adjacent vertices closer together than a specified tolerance SDO_UTIL.APPEND Accepts two geometries as input and returns a single geometry with the second geometry appended to the first New Utility Functions Other utility functions that ship starting with Oracle Spatial 10g include the following: SDO_UTIL.POLYGONTOLINE: This function generates a new geometry by converting all polygon elements into line string elements, and appropriately setting the SDO_GTYPE. SDO_UTIL.REMOVE_DUPLICATE_VERTICES: This function generates a new geometry by removing adjacent vertices in the input geometry that are closer together than a specified tolerance. This function may affect the registration of adjacent polygons. SDO_UTIL.APPEND: This function accepts two geometries as input, and returns a single geometry with the second geometry appended to the first geometry. This differs from SDO_UNION in that no geometric union is completed. For example, if two overlapping polygons are input, the resulting geometry will contain two separate polygon elements that overlap. Note that this resulting geometry would be an invalid multipolygon due to the overlapping polygon elements. Oracle Spatial 10g: Advanced
440
SDO_UTIL.POLYGONTOLINE
Example: Convert a geodetic optimized rectangle to a line string SELECT SDO_UTIL.POLYGONTOLINE( SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 3), SDO_ORDINATE_ARRAY( , , , ))) FROM dual; SDO_GEOMETRY(2002, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( , , , , , , , , , , , , , )) SDO_UTIL.POLYGONTOLINE Here you see an example of SDO_UTIL.POLYGONTOLINE. The example above converts a geodetic optimized rectangle to a line. The returned line string returned is based on the densified optimized rectangle. In other words, the line string is densified at one-degree intervals for constant latitude lines and The example above passed in a geodetic optimized rectangle smaller than half the Earth’s surface area. If the geodetic optimized rectangle passed in was larger than half the Earth’s surface area, SDO_UTIL.POLYGONTOLINE would return a multiline string. The line string returned is based on the densified optimized rectangle Oracle Spatial 10g: Advanced
441
SDO_UTIL.REMOVE_DUPLICATE_VERTICES: Example
SELECT SDO_UTIL.REMOVE_DUPLICATE_VERTICES( SDO_GEOMETRY(2002, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( , , , , , , , , , )), 0.5) FROM dual; , , , )) SDO_UTIL.REMOVE_DUPLICATE_VERTICES: Example Here you see an example of SDO_UTIL.REMOVE_DUPLICATE_VERTICES. The function returns a geometry without duplicate vertices by removing vertices closer together than the specified tolerance. The TOLERANCE value is the second parameter to the function. Oracle Spatial 10g: Advanced
442
SDO_UTIL.APPEND: Example
SELECT SDO_UTIL.APPEND( SDO_GEOMETRY(2002, null, null, SDO_ELEM_INFO_ARRAY(1,2,1), SDO_ORDINATE_ARRAY(4,4, 7,4, 10,5)), SDO_GEOMETRY(2003, null, null, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(6,6, 8,8))) FROM dual; SDO_GEOMETRY(2004, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,2,1, 7,1003,3), SDO_ORDINATE_ARRAY(4,4, 7,4, 10,5, 6,6, 8,8)) SDO_UTIL.APPEND: Example The graphic contains an example of SDO_UTIL.APPEND. The function appends the second geometry to the first geometry. Because a polygon was appended to a line string, the SDO_GTYPE of the result was set to 2004 (heterogeneous collection). Oracle Spatial 10g: Advanced
443
Oracle Spatial 10g: Advanced 1-454
New Utility Functions SDO_UTIL.CONCAT_LINES Concatenates two line string or multiline string 2D geometries to create a new geometry, matching equivalent start/end points Only matches start and end points, no other overlaps between line strings are allowed Faster than SDO_UNION Used for road networks SDO_UTIL.REVERSE_LINESTRING Accepts a two-dimensional line string geometry as input and returns a line string with the coordinates in reverse order New Utility Functions Other utility functions that ship starting with Oracle Spatial 10g include the following: SDO_UTIL.CONCAT_LINES accepts two, 2D line string geometries as input, and concatenates them to make a new geometry. The new geometry can be a single line string if the boundaries (start/end points) of the input geometries match or a multiline string geometry if the boundaries are disjoint. SDO_UTIL.CONCAT_LINES does not accept circular arcs, compound line strings or line strings that topologically interact at any point other than start/end points. If the input is a multiline string, the individual elements in the multiline string cannot interact. SDO_UTIL.CONCAT_LINES should only be used where matching start/end points is required. When this is the requirement, SDO_UTIL.CONCAT_LINES is faster than SDO_GEOM.SDO_UNION. SDO_UTIL.REVERSE_LINESTRING: This function accepts a two-dimensional line string geometry as input and returns a line string with the coordinates in reverse order. Oracle Spatial 10g: Advanced
444
SDO_UTIL.CONCAT_LINES: Example
The result of this example is in the next slide. SELECT SDO_UTIL.CONCAT_LINES( SDO_GEOMETRY(2006,NULL,NULL, SDO_ELEM_INFO_ARRAY(1,2,1, 5,2,1), SDO_ORDINATE_ARRAY(1,1, 5,1, 7,1, 9,1)), SDO_ORDINATE_ARRAY(9,1, 10,1, 7,1, 5,1))) FROM dual; SDO_GEOMETRY(2002, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY(10,1, 9,1, 7,1, 5,1, 1,1)) SDO_UTIL.CONCAT_LINES: Example The slide above contains an example of SDO_UTIL.CONCAT_LINES. The function concatenates line strings if start and end points match; otherwise, it returns a multiline string. Oracle Spatial 10g: Advanced
445
SDO_UTIL.CONCAT_LINES Result from Previous Slide
(1,1) (5,1) (7,1) (9,1) Line 2: (5,1) (7,1) (9,1) (10,1) Result: SDO_UTIL.CONCAT_LINES: Example (continued) Here is the result of the previous example. The graphic contains an example of SDO_UTIL.CONCAT_LINES. The function attaches line strings together if appropriate; otherwise, it returns a multiline string. (1,1) (5,1) (7,1) (9,1) (10,1) Oracle Spatial 10g: Advanced
446
SDO_UTIL.REVERSE_LINESTRING: Example
SELECT SDO_UTIL.REVERSE_LINESTRING( SDO_GEOMETRY(2002, 8307, NULL, SDO_ELEM_INFO_ARRAY(1,2,1), SDO_ORDINATE_ARRAY( -72,43, -71.5,43.5, -71,42, -70,40))) FROM dual; -70,40, -71,42, -71.5,43.5, -72,43)) SDO_UTIL.REVERSE_LINESTRING: Example This is an example of SDO_UTIL.REVERSE_LINESTRING. The function returns a geometry that reverses the coordinates of the input line string. Oracle Spatial 10g: Advanced
447
Oracle Spatial 10g: Advanced 1-458
New Utility Functions SDO_UTIL.GETNUMELEM Returns the number of elements in a geometry Useful when calling SDO_UTIL.EXTRACT in a loop Input geometry requires a four-digit SDO_GTYPE SDO_UTIL.GETNUMVERTICES Returns the number of vertices in a geometry New Utility Functions More utility functions that are shipped with Oracle Spatial 10g include the following: SDO_UTIL.GETNUMELEM: This function takes a geometry as input, and returns the number of elements the geometry is composed of. A compound line string or compound polygon is considered one element. A single exterior polygon with one or more holes is considered a single element. The second argument of SDO_UTIL.EXTRACT identifies which element to extract. When extracting all the elements of a geometry in a loop, the result of SDO_UTIL.GETNUMELEM helps determine how many times to loop. The input geometry requires a four-digit SDO_GTYPE. SDO_UTIL.GETNUMVERTICES: This function takes a geometry as input and returns the number of vertices stored in the geometry. Oracle Spatial 10g: Advanced
448
SDO_UTIL.GETNUMELEM and SDO_UTIL.GETNUMVERTICES: Example
This geometry is used in the example on the next slide to show the use of: SDO_UTIL.GETNUMELEM SDO_UTIL.GETNUMVERTICES (15,60) (45,60) (85,50) (10,50) (30,50) (50,50) (10,50) (35,40) (75,45) SDO_UTIL.GETNUMELEM and SDO_UTIL.GETNUMVERTICES: Example The slide above shows you the geometry used in the example of SDO_UTIL.GETNUMELEM and SDO_UTIL.GETNUMVERTICES. (25,35) (10,30) (50,30) Oracle Spatial 10g: Advanced
449
SDO_UTIL.GETNUMELEM and SDO_UTIL.GETNUMVERTICES: Example
SET SERVEROUTPUT ON; DECLARE geom SDO_GEOMETRY := SDO_GEOMETRY(2007, NULL, NULL, SDO_ELEM_INFO_ARRAY (1,1005,2, 1,2,1, 7,2,2, 17,2003,3, 21,1003,3), SDO_ORDINATE_ARRAY (10,50, 10,30, 50,30, 50,50, 40,60, 30,50, 20,60, 10,50, 25,35, 35,40, 75,45, 85,50)); numelements NUMBER; numvertices NUMBER; BEGIN numelements := SDO_UTIL.GETNUMELEM(geom); numvertices := SDO_UTIL.GETNUMVERTICES(geom); DBMS_OUTPUT.PUT_LINE ('num_elems= '||numelements); DBMS_OUTPUT.PUT_LINE ('num_vertices= '||numvertices); END; / num_elems = 2 num_vertices = 12 SDO_UTIL.GETNUMELEM and SDO_UTIL.GETNUMVERTICES: Example (continued) The slide shows an example of using SDO_UTIL.GETNUMELEM and SDO_UTIL.GETNUMVERTICES. Oracle Spatial 10g: Advanced
450
Oracle Spatial 10g: Advanced 1-461
New Utility Functions SDO_UTIL.CONVERT_UNIT Converts a number from one unit to another The following conversions are supported: From one angle unit to another angle unit From one distance unit to another distance unit From one area unit to another area unit SDO_UTIL.POINT_AT_BEARING Returns a point a specified distance and bearing from a start point New Utility Functions More utility functions that are shipped starting with Oracle Spatial 10g include the following: SDO_UTIL.CONVERT_UNIT: This function converts a number from one unit to another unit. Conversions are supported: Between angle units Between distance units Between area units SDO_UTIL.POINT_AT_BEARING: This function returns a point a specified distance from a start point at a given bearing. Oracle Spatial 10g: Advanced
451
SDO_UTIL.CONVERT_UNIT
NUMBER = SDO_UTIL.CONVERT_UNIT ( START_NUMBER, FROM_UNIT, TO_UNIT ) START_NUMBER:The number to convert FROM_UNIT: The unit to convert from TO_UNIT: The unit to convert to FROM_UNIT and TO_UNIT parameters must come from the SDO_UNIT column of the same table. Choose one of the following tables: MDSYS.SDO_AREA_UNITS MDSYS.SDO_DIST_UNITS MDSYS.SDO_ANGLE_UNITS SDO_UTIL.CONVERT_UNIT Another utility function that ships starting with Oracle Spatial 10g includes SDO_UTIL.CONVERT_UNIT. SDO_UNIT.CONVERT_UNIT takes a number and converts it from one unit to another. For example, it can convert between feet and meters, or radians and degrees. Both units must come from the same one of the following tables: MDSYS.SDO_AREA_UNITS MDSYS.SDO_DIST_UNITS MDSYS.SDO_ANGLE_UNITS Oracle Spatial 10g: Advanced
452
SDO_UTIL.CONVERT_UNIT: Example
SELECT SDO_UTIL.CONVERT_UNIT( 180, 'degree', 'radian') converted_unit FROM dual; CONVERTED_UNIT 1, 'degree', 'minute') converted_unit SDO_UTIL.CONVERT_UNIT: Example The example above shows the use of the SDO_UTIL.CONVERT_UNIT function. Note: Angle conversions performed in radians Oracle Spatial 10g: Advanced
453
SDO_UTIL.POINT_AT_BEARING
GEOM = SDO_UTIL.POINT_AT_BEARING ( <GEOMETRY START_POINT>, <BEARING>, <DISTANCE> ) <GEOMETRY_START_POINT> The start point Must be longitude/latitude <BEARING> The bearing, specified in radians Valid values from –pi to pi (0 is North) To convert degrees to radians, use SDO_UTIL.CONVERT_UNIT. SDO_UTIL.POINT_AT_BEARING SDO_UTIL.POINT_AT_BEARING returns a point geometry a specified distance and bearing from a start point. The input parameters to this function are: GEOMETRY_START_POINT: A point geometry in a geodetic coordinate system that represents the start point. BEARING: The bearing, specified in radians. The valid range –pi (–180 degrees) to pi (180 degrees), and 0 degrees represents north. SDO_UTIL.CONVERT_UNIT can be used to convert degrees to radians. Oracle Spatial 10g: Advanced
454
SDO_UTIL.POINT_AT_BEARING
<DISTANCE> The distance, specified in meters Must be less than half the circumference of the Earth SDO_UTIL.POINT_AT_BEARING (continued) DISTANCE is the distance to travel (in meters) from the start point along the specified bearing to determine the end point. Oracle Spatial 10g: Advanced
455
SDO_UTIL.POINT_AT_BEARING:Example
Find the point 3,000,000 meters due south of the point (-160,85): SELECT SDO_UTIL.POINT_AT_BEARING( SDO_GEOMETRY(2001,8307, SDO_POINT_TYPE(-160, 85, NULL), NULL, NULL), , ) FROM dual; SDO_GEOMETRY(2001, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1, 1), SDO_ORDINATE_ARRAY(-160, )) SDO_UTIL.POINT_AT_BEARING: Example This is an example of how you use the SDO_UTIL.POINT_AT_BEARING function. The bearing is specified directly in radians. Due south is or pi radians Oracle Spatial 10g: Advanced
456
SDO_UTIL.POINT_AT_BEARING:Example
Find the point 3,000,000 meters due south of the point (-160,85): SELECT SDO_UTIL.POINT_AT_BEARING( SDO_GEOMETRY(2001,8307, SDO_POINT_TYPE(-160, 85, NULL), NULL, NULL), SDO_UTIL.CONVERT_UNIT(180, 'degree', 'radian'), ) FROM dual; SDO_GEOMETRY(2001, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1, 1), SDO_ORDINATE_ARRAY(-160, )) SDO_UTIL.POINT_AT_BEARING: Example (continued) This is another example of how you use the SDO_UTIL.POINT_AT_BEARING function. In this case the bearing is converted from radians to degrees by using the SDO_UTIL.CONVERT_UNIT function. Uses SDO_UTIL.CONVERT_UNIT to convert 180 degrees to radians Oracle Spatial 10g: Advanced
457
New Utility Functions: Geography Markup Language Support
Geography Markup Language (GML) is an XML-based encoding standard for geographic information. Oracle Spatial currently supports GML Oracle Spatial includes a function to publish SDO_GEOMETRY as GML: SDO_UTIL.TO_GMLGEOMETRY. This function converts one geometry at a time: Each geometry is a separate GML document. The XML Forest functionality can be used to generate a GML document for a set of geometries. Geography Markup Language (GML) Support Geography Markup Language (GML) is an XML standard for encoding geographic information. Oracle Spatial provides a function that accepts a geometry as input and returns a string in GML format. This function is SDO_UTIL.TO_GMLGEOMETRY. The output of SDO_UTIL.TO_GMLGEOMETRY is a GML document associated with the input geometry. Oracle Spatial 10g: Advanced
458
Geography Markup Language Support
The result of this example is in the next slide. set long 5000 SELECT SDO_UTIL.TO_GMLGEOMETRY( SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1,1003,1,11,2003,1), SDO_ORDINATE_ARRAY(1,1,4,1,4,4,1,4,1,1, 2,2,3,2,3,3,2,3,2,2))) FROM dual; New Utility Functions Example: Geography Markup Language Support The example in this slide invokes SDO_UTIL.TO_GMLGEOMETRY to return a geometry in Geography Markup Language format. Oracle Spatial 10g: Advanced
459
Geography Markup Language Support
Result: <gml:Polygon srsName="SDO:8307" xmlns:gml=" <gml:outerBoundaryIs> <gml:LinearRing> <gml:coordinates decimal="." cs="," ts=" "> 1.0, , , , ,1.0 </gml:coordinates> </gml:LinearRing> </gml:outerBoundaryIs> <gml:innerBoundaryIs> 2.0, , , , ,2.0 </gml:innerBoundaryIs> </gml:Polygon> New Utility Functions Example: Geography Markup Language Support (continued) This is the result of the query in the previous slide. Oracle Spatial 10g: Advanced
460
Linear Referencing System (LRS) New Features
Oracle Spatial 10g: Advanced
461
Oracle Spatial 10g: Advanced 1-472
LRS: New Features SDO_LRS.PROJECT_PT: New optional out parameter to get the signed offset SDO_LRS.FIND_OFFSET: Returns just the signed offset of a point to an LRS segment Some functions require TOLERANCE where TOLERANCE was previously optional Consistent use of TOLERANCE: Previously, TOLERANCE sometimes was applied to measure information. Now TOLERANCE is applied only to geometry. LRS: New Features Oracle Spatial’s Linear Referencing in Oracle Spatial 10g includes the following new features: A new function, SDO_LRS.FIND_OFFSET, which returns the signed offset of a point to a linear referenced geometry. The sign is positive if the point is on the left side of the linear referenced geometry as it is traversed in the order the vertices are defined. The sign is negative if the point is on the right of the segment. A new optional output parameter with SDO_LRS.PROJECT_POINT that returns the signed offset of the projected point to determine which side of the linear referenced geometry the point is The TOLERANCE value should be specified in the functions where previously TOLERANCE was optional. All LRS functions apply TOLERANCE consistently to the geometry data only, and not to the measure information. Oracle Spatial 10g: Advanced
462
SDO_LRS.PROJECT_PT: Example
SET SERVEROUTPUT ON; DECLARE lrs_geom SDO_GEOMETRY := SDO_GEOMETRY(3302, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( , , 0, , , , , , , , , )); pt_geom SDO_GEOMETRY := SDO_GEOMETRY (2001,8307, SDO_POINT_TYPE( , ,null), NULL,NULL); proj_geom SDO_GEOMETRY; offset NUMBER; BEGIN proj_geom := sdo_lrs.project_pt(lrs_geom, pt_geom, 0.5, offset); dbms_output.put_line('offset = '||offset); END; / offset = SDO_LRS.PROJECT_PT: Example Above is an example of SDO_LRS.PROJECT_PT with the new output parameter that returns the signed offset. The function requires: An LRS geometry as the first argument A point to project onto the LRS geometry as the second argument A tolerance as the third argument An optional numeric fourth argument that is an output parameter containing the signed offset. In addition to the signed offset returned in the optional fourth parameter, the function returns the projection point (the closest location) on the linear referenced geometry. The graphic illustrates the defined linear referenced line string, with the point to project passed into the second argument of the function. The returned offset is negative. Negative offsets denote that the point being projected is to the right of the linear referenced geometry. Oracle Spatial 10g: Advanced
463
SDO_LRS.FIND_OFFSET: Example
SELECT sdo_lrs.find_offset( SDO_GEOMETRY(3302, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( , , , , , , , , , , , )), SDO_GEOMETRY(2001,8307, SDO_POINT_TYPE( , ,null), NULL,NULL),0.5) offset FROM dual; OFFSET SDO_LRS.FIND_OFFSET: Example SDO_LRS.FIND_OFFSET is similar to SDO_LRS.PROJECT_POINT, but returns only the signed offset. The function requires: An LRS geometry as the first argument A point to project onto the LRS geometry as the second argument A tolerance as the third argument. The function returns the minimum signed offset of a point projected onto a linear referenced geometry. The graphic illustrates the defined linear referenced line string, with the point to project passed into the second argument of the function. The returned offset is negative. Negative offsets denote that the point being projected is to the right of the linear referenced geometry. Oracle Spatial 10g: Advanced
464
Miscellaneous Features
Oracle Spatial 10g: Advanced
465
Oracle Spatial 10g: Advanced 1-476
Interior Buffer Generates a buffer polygon inside a polygon geometry object Works with simple polygons and polygons with holes Specify negative buffer distance in SDO_GEOM.SDO_BUFFER to generate an interior buffer. SELECT SDO_GEOM.SDO_BUFFER( SDO_GEOMETRY(2003,null,null, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY( 0,0,10,10 )), -1, 0.5) FROM dual; SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY( 1, 9, 1, 1, 9, 1, 9, 9, 1, 9 )) Interior Buffer Interior buffers are supported in Oracle Spatial 10g using negative buffer distances. The signature of the function remains the same, but the buffer distance is specified as a negative number. Applying a negative buffer distance to a point or a line geometry returns NULL. Oracle Spatial 10g: Advanced
466
Coordinate System Validation
Validates the “well known text” (WKTEXT) of user-defined coordinate systems in the CS_SRS table: SRID Spatial reference system ID to validate Returns TRUE or FALSE Example: STATUS = SDO_CS.VALIDATE_WKT(SRID) SELECT SDO_CS.VALIDATE_WKT(8307) FROM dual; TRUE Coordinate System Validation SDO_CS.VALIDATE_WKT is a function that validates the “well known text” associated with user-defined coordinate systems. The input parameter is the SRID of the coordinate system to validate. The function returns TRUE or FALSE. Oracle Spatial 10g: Advanced
467
SDO_AGGR_CONCAT_LINES
Concatenates a set of line strings into a single geometry Same rules for SDO_UTIL.CONCAT_LINES apply: Concatenates line string or multiline string 2D geometries, matching equivalent start/end points Only matches start and end points, no other overlaps between line strings are allowed Faster than SDO_AGGR_UNION SDO_AGGR_CONCAT_LINES SDO_AGGR_CONCAT_LINES operates on a set of two dimensional line string geometries to return a single geometry (either a single line string or a multiline string that is the concatenation of the set of input line strings). SDO_AGGR_CONCAT_LINES does not accept the following geometries as input: Circular arcs Compound line strings Line strings that topologically interact at any point other than the boundaries (endpoints) Also, if any of the input geometries is a multiline string, the individual line strings in that multiline string cannot interact topologically. Oracle Spatial 10g: Advanced
468
SDO_AGGR_CONCAT_LINES: Example
Concatenate all the interstates that interact with the state of New Hampshire: SELECT /*+ ordered */ SDO_AGGR_CONCAT_LINES(b.geom) FROM geod_states a, geod_interstates b WHERE SDO_ANYINTERACT(b.geom, a.geom)='TRUE' AND a.state_abrv='NH'; SDO_AGGR_CONCAT_LINES: Example Concatenate all the interstates that interact with the state of New Hampshire. Oracle Spatial 10g: Advanced
469
New SQL/MM Member Methods for SDO_GEOMETRY
GET_WKB() Returns Well Known Binary format of the geometry GET_WKT() Returns Well Known Text format of the geometry ST_CoordDim() Returns the dimensionality of the geometry Requires a four-digit SDO_GTYPE ST_IsValid() Validates the geometry Returns 1 if valid, 0 otherwise New SQL/MM Member Methods for SDO_GEOMETRY There are several new SQL/MM–compliant member methods for the SDO_GEOMETRY object. The new member methods are: GET_WKB(): Returns the Well Known Binary format of the geometry as defined by SQL/MM. GET_WKT(): Returns the Well Known Text format of the geometry as defined by SQL/MM. ST_CoordDim(): Returns the dimensionality of the geometry. Requires input geometry to have a four-digit SDO_GTYPE ST_IsValid(): Validates the geometry Returns 1 if valid, 0 otherwise Always uses tolerance If the data is invalid, use SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT to determine if the data is truly invalid (at true tolerance) and to find out more information about why the data is invalid. Oracle Spatial 10g: Advanced
470
New SQL/MM Member Methods for SDO_GEOMETRY: Examples
set long 500; SELECT A.GEOM.GET_WKT() FROM (SELECT SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY(146,66, 148,66, 148,68, 146,68, 146,66)) geom FROM dual) a; A.GEOM.GET_WKT() POLYGON (( , , , , )) New SQL/MM Member Methods for SDO_GEOMETRY: Examples This example shows the use of the SDO_GEOMETRY member method GET_WKT(). Note that the returned SQL/MM Well Known Text does not include coordinate system information. Oracle Spatial 10g: Advanced
471
New SQL/MM Member Methods for SDO_GEOMETRY: Examples
SELECT a.geom.ST_IsValid() FROM (SELECT SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY(146,66, 148,66, 148,68, 146,68, 146,66)) geom FROM dual) a; 1 SELECT A.GEOM.ST_COORDDIM() FROM (SELECT SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY(146,66, 148,66, 148,68, 146,68, 146,66)) geom FROM dual) a; 2 New SQL/MM Member Methods for SDO_GEOMETRY: Examples (continued) These examples show the use of the SDO_GEOMETRY member methods ST_IsValid and ST_CoordDim. The ST_IsValid function simply returns 1 or 0. For more comprehensive reporting, use SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT. Oracle Spatial 10g: Advanced
472
New Constructors for SDO_GEOMETRY
Constructor input can be either: SQL/MM Well Known Text (WKT) SQL/MM Well Known Binary (WKB) Constructors all return SDO_GEOMETRY object: Argument Name Type In/Out Default? WKT CLOB IN ASRID NUMBER IN DEFAULT ------ WKT VARCHAR2 IN WKB BLOB IN New Constructors for SDO_GEOMETRY There are three new constructors defined for SDO_GEOMETRY that take as input either: SQL/MM Well Known Text (WKT) SQL/MM Well Known Binary (WKB) The also take an optional SRID value as input. All constructors return an SDO_GEOMETRY object. If no SRID value is input, the default value for the SDO_SRID attribute of the constructed SDO_GEOMETRY object is NULL. Otherwise, the input SRID value is included in the SDO_SRID attribute in the SDO_GEOMETRY object. Oracle Spatial 10g: Advanced
473
New Constructors for SDO_GEOMETRY WKT: Examples
SELECT SDO_GEOMETRY( 'POLYGON (( , , , , ))') FROM dual; SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY(146,66, 148,66, 148,68, 146,68, 146,66)) SELECT SDO_GEOMETRY( 'POLYGON (( , , , , ))', 8307) FROM dual; SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY(146,66, 148,66, 148,68, 146,68, 146,66)) New Constructors for SDO_GEOMETRY WKT: Examples These examples show the use of the new SDO_GEOMETRY constructors that take SQL/MM Well Known Text as input and change it to SDO_GEOMETRY. The first example takes a “well known text” string as input. The second example includes a spatial reference system ID, to populate the SDO_SRID value of the SDO_GEOMETRY object. Oracle Spatial 10g: Advanced
474
Oracle Spatial 10g: Advanced 1-485
Miscellaneous The MDSYS user is no longer needed when referring to spatial types, for example: New JAVA API Ships with Oracle Spatial and available on OTN Fully supported SQL*Loader direct path support for any spatial object Was SDO_POINT_TYPE in Oracle 9i database CREATE TABLE TEST (ID NUMBER, GEOM SDO_GEOMETRY); INSERT INTO TEST VALUES (1, SDO_GEOMETRY(2002,8307,NULL, SDO_ELEM_INFO_ARRAY (1, 2, 1), SDO_ORDINATE_ARRAY( ,38.442, , )) Miscellaneous The MDSYS schema owner prefix is no longer needed when referring to spatial types. New JAVA API for SDO_GEOMETRY. This API is fully supported, and can be downloaded from the Oracle Technology Network (OTN). The JAVA API can access geometries from Oracle databases and later. SQL*Loader direct path load is supported for any SDO_GEOMETRY object. In the Oracle9i database, direct path loads could only be performed on SDO_GEOMETRY objects that did not populate the SDO_ELEM_INFO or SDO_ORDINATE varrays. Oracle Spatial 10g: Advanced
475
SDO_NN Self-Tuning Batch Size
SDO_BATCH_SIZE = 0 Self-tuning version of SDO_BATCH_SIZE Batch size starts small and automatically increases Default for the two-parameter signature SELECT /*+ ordered */ c.city, c.pop90 FROM geod_interstates i, geod_cities c WHERE i.highway = 'I170' AND sdo_nn ( c.location, i.geom ) = 'TRUE' AND c.pop90 > AND ROWNUM < 6; SDO_NN Self-Tuning Batch Size Specifying an SDO_BATCH_SIZE of 0 allows Oracle Spatial to tune the batch size as the query executes. The batch size starts small and increases automatically in each probe back to the database to satisfy the additional predicates in the WHERE clause. SDO_BATCH_SIZE=0 is the default for the two-parameter signature of SDO_NN. Oracle Spatial 10g: Advanced
476
Oracle Spatial 10g: Advanced 1-487
Miscellaneous MBR functions supported for geodetic data: SDO_GEOM.SDO_MBR SDO_GEOM.MIN_MBR_ORDINATE SDO_GEOM.MAX_MBR_ORDINATE SDO_AGGR_MBR SELECT SDO_GEOM.SDO_MBR(geom) MBR FROM geod_counties WHERE state_abrv = 'IL' and county = 'Saline'; MBR(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), . . . SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY( 1,1003,3 ), SDO_ORDINATE_ARRAY( , , , )) Miscellaneous (continued) MBR functions are supported for geodetic (longitude/latitude) data. Oracle Spatial 10g: Advanced
477
Oracle Spatial 10g: Advanced 1-488
Summary In this lesson, you should have learned about the following Oracle Spatial 10g enhancements: R-tree enhancements New and updated Spatial operators New geometry types New Spatial utility functions New LRS functions and updates Other miscellaneous enhancements Objectives This is a summary of the enhancements talked about in this lesson. In future lessons you learn about other major features in Oracle Spatial. Oracle Spatial 10g: Advanced
478
Appendix B: Optional Workspace Manager
479
Oracle Spatial 10g: Advanced 1-490
Objectives After completing this lesson, you should be able to do describe Workspace Manager benefits. Oracle Spatial 10g: Advanced
480
Oracle Spatial 10g: Advanced 1-491
Workspace Manager Feature of the Oracle database (all versions) for application developers and DBAs since Oracle9i Database Manages current, proposed, and historical values for data in the same database by versioning rows Isolates a collection of changes to production data Keeps a history of changes to data Performs “what if” analysis Saves money, time, and labor Workspace Manager Workspace Manager is a feature of the Oracle database for application developers and DBAs. It manages current, proposed, and historical values for data in the same database. Potential uses of Workspace Manager include isolating a collection of changes to production data, keeping a history of changes to data, and creating multiple data scenarios for “what if” analysis. Oracle Spatial 10g: Advanced
481
Oracle Spatial 10g: Advanced 1-492
Usage Examples Manage long-duration projects for example, parcel changes. Create multiple scenarios for example, “what if” analysis. Retain history of changes, for example, GoToDate to see parcel data as of a particular point in time. LIVE workspace Parcel A subdivision Parcel B zoning change Open Space Conventional Usage Examples The first example in the slide illustrates how workspaces can be used to enhance concurrency while isolating changes for long-duration projects; in this case, to manage the development of a subdivision on Parcel A and a potential zoning change to Parcel B. Users in the Parcel A and Parcel B workspaces both can update any row in the database, while the original version of this row in LIVE remains unchanged and is available in all other workspaces. The second example illustrates another common use of workspaces, that is, to create multiple data scenarios from the current production data for analysis. It illustrates the use of workspaces to model the effects of two different residential development configurations. If a table is version-enabled with history, then the GoToDate procedure can be used to view previous versions. Oracle Spatial 10g: Advanced
482
Oracle Spatial 10g: Advanced 1-493
Benefits Saves money City of Edmonton consolidated 49 physical asset databases into one database HMO cut hardware requirements by 50% and software licensing for a half-terabyte data store Saves time Concurrent access to current, proposed, and historical data without replicating tables Saves labor Single point of update and management No custom code or application-specific version data Benefits Workspace Manager saves money by reducing the amount of hardware and corresponding software licensing needed to manage this data, as compared to scenarios where data is copied and synchronized across multiple database instances. It saves time by allowing concurrent access to current, proposed, and historical data without the latency associated with making copies of the data. It saves labor by allowing a single point of update and management for this data while freeing the application developer from writing custom code and creating application-specific metadata to keep track of multiple data versions. Oracle Spatial 10g: Advanced
483
Workspace Manager Architecture
Application Enterprise Manager PL/SQL APIs SQL Table Mgmt. WS Mgmt. Privilege Mgmt. Lock Mgmt. Conflict Mgmt. Metadata Views Oracle database with Workspace Manager Workspace Manager Architecture Workspace Manager controls all access to a version-enabled table. It provides PL/SQL procedures that are called by the application in order to use the product’s features. The procedures are in a single PL/SQL package, but they can be logically grouped into the following categories: Table Management Workspace Management (including savepoints) Privilege Management Lock Management Conflict Management Metadata Views Oracle Spatial 10g: Advanced
484
Begin by Version-Enabling a Table
All row versions are stored in the _LT table. All access to table is through Workspace Manager. UPDATE catalog SET . . . DBMS_WM.ENABLEVERSIONING('CATALOG'); RENAME… CATALOG: Base table CATALOG_LT: Renamed base table with four new columns CATALOG: View with instead-of triggers Begin by Version-Enabling a Table The unit of versioning is the table. Any user table in an existing or new database can be version-enabled. When a user in a workspace updates a row in a version-enabled table, a new version of the row is created in the same table. When a table is versioned: It is renamed to tablename_LT. At least four versioning metadata columns are added. The primary index is rebuilt using these new columns to uniquely identify each versions of a row. A view is created with the original table name. Instead-of triggers are placed on the view, so inserts, updates, and deletes are applied to the underlying _LT table. Benefits: Storage expansion is minimized by versioning only the changed rows. Application SQL transparency is achieved with version-enabled tables by creating a view with the same name as the table and instead-of triggers for inserts, updates, and deletes. Oracle Spatial 10g: Advanced
485
Oracle Spatial 10g: Advanced 1-496
Workspace Facts Parcel A subdivision Parcel B zoning change LIVE workspace A WS is a logical view (not physical storage) that can be shared by users. A WS isolates one or more changes (row versions) from one or more version-enabled tables. Workspace hierarchies can be of any depth and width. The LIVE workspace is automatically created at installation time. By default, a workspace is created as a child of LIVE. Changes in a workspace are made by conventional short transactions. Workspace Facts A workspace (WS) provides a logical view of a set of changes to one or more version-enabled tables. Users can share a workspace. Changes are isolated by the workspace until explicitly merged with the parent workspace. A workspace can include one or more versions of rows from one or more version-enabled tables. Workspaces are organized into hierarchies. The LIVE workspace is automatically created when Workspace Manager is installed. By default, when a workspace is created, it is created as the child of LIVE. All changes in a workspace are made by conventional short transactions to ensure data integrity. Oracle Spatial 10g: Advanced
486
Oracle Spatial 10g: Advanced 1-497
More Workspace Facts Open Space Conventional Parcel A subdivision Parcel B zoning change LIVE workspace The GoToWorkspace procedure sets session context to a WS. Workspaces provide concurrency. The current version is the one that is queried and changed. Changes are only accessible in the child workspace until explicitly merged with the parent workspace. Changes in the parent can also be refreshed to the child. A WS provides a transactionally consistent view. No changes to application SQL are required. Database optimizer hints are supported. Workspace Manager provides WS privileges, access modes, and locks. More Workspace Facts The GoToWorkspace procedure places the user in a workspace and determines his or her data context. It is the only Workspace Manager procedure required in the application (or in a login script). All other workspace operations can be performed from SQL or Oracle Enterprise Manager When a user issues a command to GoToWorkspace (Parcel A) and updates a row for the first time, Workspace Manager automatically creates a new version of the updated row in the Parcel A workspace. Meanwhile, the original version of this row in LIVE remains unchanged and is available in all other workspaces. Subsequent changes to the row in Parcel A are made to the same version of the row unless the user creates a savepoint in Parcel A and makes change to the row, at which point a new version of the row is created. Merging the Open Space workspace makes latest versions created in it visible to users in the Parcel A workspace—but not to users in LIVE. Merging the Parcel A workspace makes latest versions created in it and anything merged from Open Space visible to users in the LIVE workspace. Refreshing the Parcel B workspace incorporates changes merged into LIVE from Parcel A. Oracle Spatial 10g: Advanced
487
Oracle Spatial 10g: Advanced 1-498
Savepoint Facts A savepoint groups a collection of changes within a workspace. Two types of savepoints: explicit and implicit An explicit savepoint is created and named by a user. An implicit savepoint is created automatically in the parent WS when a child WS is created. A savepoint is usually created to mark a unit of work. A savepoint causes a new version to be created. Subsequent changes are made to the latest version until another savepoint is created. Changes made in a WS can be rolled back to a savepoint. The GoToSavepoint procedure sets the session context so WS users see the version of the row before that savepoint. Savepoint Facts Savepoints logically group the current version of all rows associated with version-enabled tables in a workspace. With savepoints, users can roll back to a point in time, undoing edits made after a savepoint was created. Workspace Manager also enables users to set the current view to a savepoint. This enables users to see the database as it existed at the time a savepoint was created, without physically rolling back edits. Savepoints are usually created in response to a milestone in a business event, such as the completion of a design or the end of a billing period. Modifying a row after a savepoint is created causes a new row version to be implicitly created. Subsequent changes are applied to this new version until another savepoint is created. Oracle Spatial 10g: Advanced
488
When Is a New Row Version Created?
PARCELS table: Row 1 v0 Row 1 (v0) – Present when (or inserted after) PARCELS table is versioned Row 1 v1 Row 1 (v1) – First update in WS1 (since implicit SP1 was created) Row 1 v2 Row 1 (v2) – First update in WS1 after explicit SP2 is created Row 1 v3 Row 1 (v3) – First update in LIVE after WS1/SP1 created (creates a conflict) LIVE workspace WS1 workspace SP1 (implicit) When Is a New Row Version Created? A table called PARCELS is version-enabled with row 1 already present (or inserted after PARCELS is versioned). The initial version of Row 1 is version 0 (R1v0). Updates to row 1 in LIVE are applied to R1v0. A workspace called WS1 is created as a child of LIVE. This creates an implicit savepoint (SP1) in LIVE. An update to row 1 from WS1 creates R1v1. Subsequent updates to row 1 from WS1 are applied to R1v1. R1v1 is only visible from WS1 until WS1 is merged with LIVE. An explicit savepoint SP2 is created in WS1. The next change to row 1 causes R1v2 to be created. Subsequent updates to row 1 are applied to R1v2 until another savepoint is created. Row 1 is updated from LIVE. R1v3 is created. R1v3 is only visible from LIVE until WS1 is refreshed. Updating Row 1 in LIVE and WS1 creates a conflict that must be resolved before a Merge or Refresh operation can occur between the two workspaces. SP2 (explicit) Oracle Spatial 10g: Advanced
489
Workspace Manager Operations
Table: EnableVersioning, DisableVersioning, DDL, merge, refresh, rollback, topologies Workspace: Create, goto, refresh, merge, rollback, remove, multiparent, compress, alter, events Savepoints: Create, alter, goto, rollback History: Goto date Valid time: Valid from and until, set session valid time Privileges: Access, create, delete, rollback, merge Access modes: Read, single writer, WS operations, none Locks: Exclusive and shared Differences: Compares savepoints and workspaces Detect/resolve conflicts: Choose version to merge Bulk data movement: SQL*Loader, Import/Export, replication Workspace Manager Operations Workspace Manager includes a complete set of workspace semantics: Workspace data can be refreshed from the parent, merged back to the parent, and rolled back to a previous savepoint. The Workspace Manager event framework is built on the Oracle Advanced Queuing (AQ) capability. Messaging features provided by AQ, such as asynchronous notification, persistence, propagation, access control, history, and rule-based subscription, can be used for Workspace Manager events. Workspace Manager creates a multiconsumer queue where events are enqueued. Savepoints are persistent and mark a point in time to which operations in the workspace can be rolled back. Implicit savepoints are created by the system when a new child workspace is created. Explicit savepoints are created by the user. A savepoint causes a new version of a row to be created the next time the row is updated. Changes made to the row since an explicit savepoint can be rolled back. History keeps track of the time and date of all version changes. When the history option is enabled for a version-enabled table, each (or just the last) change to a row results in another copy of the row with the same version number and a unique time stamp. This allows users to “go to date” to see the entire database as it existed at a certain point in time. Oracle Spatial 10g: Advanced
490
Oracle Spatial 10g: Advanced 1-501
Code Sample --Version enable the PERSONNEL table with history and timestamp all changes DBMS_WM.EnableVersioning('PERSONNEL', Hist=>'VIEW_WO_OVERWRITE'); -- Create a workspace called PERSONNEL_UPDATES dbms_wm.createWorkspace('PERSONNEL_UPDATES'); -- Go to workspace PERSONNEL_UPDATES and update dbms_wm.gotoWorkspace('PERSONNEL_UPDATES'); update PERSONNEL.... Code Sample Version-enable the PERSONNEL table with history and time-stamp all changes (instead of just the latest change) made to a version. Create and go to a workspace called PERSONNEL_UPDATES to isolate a group of changes. Oracle Spatial 10g: Advanced
491
Oracle Spatial 10g: Advanced 1-502
Code Sample -- Create a savepoint called POTENTIAL_CHANGES in the PERSONNEL_UPDATES workspace & make more changes dbms_wm.CreateSavepoint('PERSONNEL_UPDATES', 'POTENTIAL_CHANGES'); update PERSONNEL.... -- Undo the last set of changes dbms_wm.RollbackToSP('PERSONNEL_UPDATES','POTENTIAL_CHANGES'); Code Sample (continued) After making a group of changes, create a savepoint called POTENTIAL_CHANGES in the PERSONNEL_UPDATES workspace so future changes can be rolled back, and then roll back the second set of changes. Oracle Spatial 10g: Advanced
492
Oracle Spatial 10g: Advanced 1-503
Code Sample -- Merge changes into LIVE (production) Workspace and remove the workspace PERSONNEL_UPDATES dbms_wm.gotoWorkspace('LIVE'); dbms_wm.MergeWorkspace('PERSONNEL_UPDATES', remove_workspace => true); -- Disable versioning on the PERSONNEL table dbms_wm.DisableVersioning('PERSONNEL'); Code Sample (continued) After the changes are completed, merge the changes into the LIVE (production) workspace and remove the PERSONNEL_UPDATES workspace. Then disable versioning on the table. Oracle Spatial 10g: Advanced
493
Workspace Manager Locks
Pessimistic mode eliminates row conflicts between a parent and child workspace by locking changed rows. Workspace Manager locks are used in conjunction with conventional Oracle database short transactions locks. Locking can be set for a workspace, session, or row. This example sets shared workspace locking on workspace WS1 and allows a session to override the locking mode: Workspace Manager Locks In addition to locks provided by conventional Oracle short transactions, Workspace Manager provides version locks. Workspace Manager locks eliminate row conflicts between a parent and child workspace. Locking is enabled at the workspace and/or a user session level (Session-level locking is discussed in a later slide.): SetWorkspaceLockModeOff is the default mode for workspace row-level locking. If OFF, it enables access to versioned rows in the specified workspace and to corresponding rows in the parent workspace. SetWorkspaceLockModeOn: When locking is enabled for a workspace, it locks all rows changed in the workspace. DBMS_WM.SETWORKSPACELOCKMODEON('WS1','S',TRUE); Oracle Spatial 10g: Advanced
494
Oracle Spatial 10g: Advanced 1-505
Workspace Lock Modes Shared (S): Any user in the workspace can modify a row changed in the workspace. Exclusive (E): Only the user that set the lock can modify the row in the workspace. Some exclusive locks prevent access but not conflicts. Version Exclusive (VE): Only the user that set the lock can modify the row in any workspace. Workspace Exclusive (WE): Only the user that set the lock can modify the row in the workspace in which the lock was set. Other users can modify the row in other workspaces. Workspace Lock Modes Workspace Manager provides two types of version locks: Exclusive locks are similar to short transaction locks in that after an exclusive lock has been placed on a record, no other user in the database can change the record except for the session that locked it. Shared locks ensure that only users in the workspace in which the row was locked are allowed to modify it. Version Exclusive and Workspace Exclusive locks control access to rows but do not prevent conflicts. Oracle Spatial 10g: Advanced
495
Resolving Workspace Conflicts
Optimistic mode increases concurrency by allowing conflicts. A conflict is created between a child and parent if a row is modified in both after the common base version. Unit of conflict detection is a row. If different columns are updated in parent and child workspaces, a conflict still exists (false conflict). Conflicts must be resolved before a Merge or Refresh. Conflicts automatically detected when a Merge or Refresh is attempted, or when SetConflictWorkspace is called. Workflow to resolve conflicts: BeginResolve, ResolveConflicts, CommitResolve, RollbackResolve Resolving Workspace Conflicts Rows that are changed in the child and parent workspaces or in two peer workspaces may lead to data conflicts. Conflicts are discovered during a merge or refresh operation or when SetConflictWorkspace is called. BeginResolve creates conflict views, one conflict view per table, to present the conflicts. The conflict view lists the primary key of the rows in conflict and also the column values of the rows in the two workspaces that form the conflict. When there are no conflicts between the parent and child workspaces, the data in the two workspaces can be merged. Conflicts must be resolved before a MergeWorkspace or RefreshWorkspace operation can be performed. Oracle Spatial 10g: Advanced
496
Oracle Spatial 10g: Advanced 1-507
Resolve Conflicts A savepoint is created in the child workspace. ResolveConflicts Keep parameter Parent: The row from the parent is copied into the child workspace. Child: No row is copied into the parent until the workspace or table is merged. Base: The base row is copied to the child workspace. No copy is made in the parent workspace until a merge operation. After resolution, both rows need to be modified in order for a conflict to reoccur. Except when the parent row is modified after resolution in favor of the child Resolve Conflicts A conflict resolution creates a savepoint in the child workspace so the changes can be rolled back. Conflicts are resolved using the ResolveConflicts procedure. During this procedure, the user chooses the row value from the base, child, or parent table. Oracle Spatial 10g: Advanced
497
Oracle Spatial 10g: Advanced 1-508
History Options Time-stamps row changes with transaction time A table can be version-enabled with one of the following history options: VIEW_WO_OVERWRITE: Each update is preserved. VIEW_W_OVERWRITE: Subsequent updates in the same version overwrite previous updates. _HIST view shows all versions in the _LT table. dbms_wm.GoToDate to view data at a given instant Rollback and Remove operations delete the history of changes made in the workspace. CompressWorkspace[Tree] can optionally preserve history (in this case, it only deletes savepoints). History Options With the history option, you can time-stamp changes made to all rows in a version-enabled table and save a copy of either all changes or only the most recent changes to each row. If you keep all changes (specifying the “without overwrite” history option) when version-enabling a table, you keep a persistent history of all changes made to all row versions, and enable users to go to any point in time to view the database as it existed from the perspective of that workspace. If you roll back changes to a workspace or remove a workspace, the history of changes made in that workspace are deleted. CompressWorkspace also deletes historical versions in the workspace or between two savepoints unless compress_view_wo_overwrite is false. Oracle Spatial 10g: Advanced
498
Valid Time (Effective Dating)
Uniquely specifies a valid date and time range for a row version Sets the valid time (VT) range for your session before a query, update, or delete Insert, update, or delete a row in one of two ways: Default to the session VT range. Specify a VT range (past, present, and/or future). Use Valid Time comparison operators to refine queries within the valid time of the session context. Specify the Valid Time option for a table when or after a table is version-enabled. Valid Time (Effective Dating) An application may require the ability to create multiple versions of project data and to specify a valid date and time range for each version of the data. These capabilities allow users, for instance, to analyze the impact and timing of various project scenarios on capacity, resource utilization, bottlenecks, and schedules. Workspace Manager provides these capabilities by versioning project data and allowing a valid time to be specified for each row version. When a table is version-enabled, the Valid Time option can be chosen. (Valid Time support can also be added to an existing version-enabled table.) If it is enabled, a user can specify a valid date and time range for a record when it is inserted, updated, or deleted. The valid time can encompass the past, the present, and/or the future. Before a query, update, or delete is performed, the user sets a valid time in his session context that acts as a filter on queries. A query returns only versions stamped with a valid time that falls within the valid time of the session context. Workspace Manager’s Valid Time comparison operators can also be used to further refine queries within the valid time of the session context. Oracle Spatial 10g: Advanced
499
Sequenced and Nonsequenced Updates
Sequenced: If a VT range is not specified in an update or delete operation, the session VT range is used to split the original row. For example: VT range of the original row = T1–T10 VT range of the session = T4–T6 Update: The original row is split into three rows with the following VT ranges: T1–T4, T4–T6, T6–T10 Delete: The original row is split into two rows with the following VT ranges: T1–T4, T6–T10. (If the session VT is not set, the entire row is deleted.) Nonsequenced: If a VT range is specified in an update: No additional row is created. Workspace Manager returns an error if the VT range overlaps that of an existing row. Sequenced and Nonsequenced Updates There are two types of valid time updates: sequenced and nonsequenced. A sequenced update operation occurs when you do not specify a change to the WM_VALID column in the UPDATE statement. In a sequenced update operation, the ValidTill value for the row is changed to the ValidFrom time stamp of the current session valid time range, and a new row is created in which the WM_VALID period reflects the current session valid time range. Sequenced updates ensure that no duplicate records are created by an UPDATE statement, because the WM_VALID column values are different. A nonsequenced update operation occurs when you specify a change to the WM_VALID column in the UPDATE statement. In a nonsequenced update operation, no additional row is created, and the WM_VALID column value of the updated row or rows reflects what you specified in the UPDATE statement. You must ensure that a nonsequenced update operation will not result in multiple rows with the same primary key value being valid in the period specified in the UPDATE statement; otherwise, the update fails because of a primary key constraint violation. Oracle Spatial 10g: Advanced
500
Valid Time Mode and Filter
Mode: Use to correct errors in the data. OFF: Disables sequenced and nonsequenced operations. Use to correct errors in a row without affecting the row’s VT range. ON: Enables sequenced and nonsequenced operations. Use to update or delete a row in a specific VT range. Filter: Use to return a single row for a session VT range. OFF: Can return multiple rows Session VT range = T1–T10 Two versions of a row: T1–T5, T5–T10 (query returns both) ON: Specifies a point in time within the session VT range A query returns only the version valid for that point in time. Valid Time Mode and Filter If SetWMValidUpdateModeOFF is set, it disables sequenced and nonsequenced update operations and sequenced delete operations. This enables all row data to be updated or deleted, regardless of the valid time period, and causes WM_VALID column values in the table not to be updated. A valid time filter is a time that is applied to queries against version-enabled tables that have valid time support. When a valid time filter is set for the current session, only rows that are valid for the specified time are returned. The purpose for setting a valid time filter is usually to work with only one row for a given primary key value. Oracle Spatial 10g: Advanced
501
Oracle Spatial 10g: Advanced 1-512
Valid Time Operators Use Valid Time operators as query filters. Relationship operators: WM_OVERLAPS: Two periods overlap WM_CONTAINS: One period contains another WM_MEETS: The end of one period is the start of another WM_EQUALS: The start/end of two periods are the same WM_LESSTHAN: The end of one period is earlier than the start of another WM_GREATERTHAN: One period starts later than the end of another Set operators: WM_INTERSECTION returns the time range common to two periods WM_LDIFF returns the difference between the two periods that is earlier in time WM_RDIFF returns the difference between the two periods that is later in time Valid Time Operators Workspace Manager provides relationship-checking operators and set operators that accept two time period parameters and that can be used to apply valid time filters in a query. The relationship-checking operators return the integer value 1 if the relationship between the two periods exists, and 0 if the relationship does not exist. The set operators return the period reflecting the relationship between the two periods, or a null value if the two periods do not have the specified relationship. Oracle Spatial 10g: Advanced
502
Oracle Spatial 10g: Advanced 1-513
Summary: Features Workspace hierarchies of arbitrary depth and width No changes to application SQL or queries Optimistic and pessimistic locking modes Continually Refreshed (CR) and non-CR workspaces Multiparent workspaces Persistent workspace locks Differencing and conflict detection/resolution Partial and full merge/refresh of workspace/table Garbage collection operations to keep the version-tree/version-data sizes optimal Event framework Oracle Spatial 10g: Advanced
503
Summary: Database Integration
Supports Oracle Spatial Supports all data types (including nested tables) DDL operations on version-enabled tables Constraints (Referential Integrity, Unique, Check) Triggers Import/Export (full and table) SQL*Loader bulk loading Replication VPDs Materialized views (full refresh) Manage via Enterprise Manager and metadata views Summary: Database Integration The export procedure exports data from a version-enabled table (all rows, or as limited by any combination of several parameters) to a staging table. The import procedure imports data from a staging table that was previously exported from a version-enabled table using the export procedure (all rows, or as limited by any combination of several parameters). SQL*Loader can be used to perform bulk loading into version-enabled tables. This requires some new Workspace Manager procedures. Some restrictions apply. You can perform both direct-path and conventional-path bulk loading of data into either the latest version of any workspace or into the root version (version number 0, which is in the LIVE workspace). The root version is the ancestor of all other versions, so data in the root version is visible from all other workspaces (unless non-LIVE workspaces have updated the data). Oracle Spatial 10g: Advanced
504
Workspace Manager Patch Sets
Workspace Manager is not part of the Oracle database DBMS patch set. Available on MetaLink: Patch sets are distributed for each supported Oracle database release. Current patch set versions and patch IDs (as of July 1, 2005): – Patch – Patch – Patch Oracle Spatial 10g: Advanced
505
Oracle Spatial 10g: Advanced 1-516
Summary Workspace Manager provides long transactions for: Long-duration projects What-if scenarios History It is tightly integrated with: Oracle Database 10g Oracle Spatial It is becoming the defacto standard for long transactions with the most comprehensive set of features and database integration in the industry. It saves money, time, and labor. Oracle Spatial 10g: Advanced
506
Oracle Spatial 10g: Advanced 1-517
Summary In this lesson, you should have learned how to describe Workspace Manager benefits. Summary This section introduced the concepts associated with the Oracle Spatial Analysis and Mining. It described neighborhood analysis, spatial binning, spatial clustering, and colocation analysis. Oracle Spatial 10g: Advanced
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.