Oracle Spatial(空间Oracle)


Oracle® Spatial Developer's Guide 11g Release 2 (11.2) E11830-06 March 2010 Provides usage and reference information for indexing and storing spatial data and for developing spatial applications using Oracle Spatial and Oracle Locator. Oracle Spatial Developer's Guide, 11g Release 2 (11.2) E11830-06 Copyright © 1999, 2010, Oracle and/or its affiliates. All rights reserved. Primary Author: Chuck Murray Contributors: Dan Abugov, Nicole Alexander, Bruce Blackwell, Raja Chatterjee, Dan Geringer, Mike Horhammer, Ying Hu, Baris Kazar, Ravi Kothuri, Siva Ravada, Jack Wang, Ji Yang This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this software or related documentation is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable: U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065. This software is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications which may create a risk of personal injury. If you use this software in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use of this software. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software in dangerous applications. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. This software and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services. iii Contents Preface ............................................................................................................................................................ xxvii Audience.................................................................................................................................................. xxvii Documentation Accessibility................................................................................................................ xxvii Related Documents ............................................................................................................................... xxviii Conventions ........................................................................................................................................... xxviii What’s New in Oracle Spatial?.......................................................................................................... xxix Release 11.2............................................................................................................................................... xxix Release 11.1............................................................................................................................................... xxxi Part I Conceptual and Usage Information 1 Spatial Concepts 1.1 What Is Oracle Spatial? .............................................................................................................. 1-2 1.2 Object-Relational Model ............................................................................................................ 1-2 1.3 Introduction to Spatial Data ...................................................................................................... 1-3 1.4 Geometry Types .......................................................................................................................... 1-3 1.5 Data Model................................................................................................................................... 1-4 1.5.1 Element.................................................................................................................................. 1-4 1.5.2 Geometry............................................................................................................................... 1-5 1.5.3 Layer ...................................................................................................................................... 1-5 1.5.4 Coordinate System............................................................................................................... 1-5 1.5.5 Tolerance............................................................................................................................... 1-6 1.5.5.1 Tolerance in the Geometry Metadata for a Layer.................................................... 1-7 1.5.5.2 Tolerance as an Input Parameter................................................................................ 1-8 1.6 Query Model................................................................................................................................ 1-8 1.7 Indexing of Spatial Data............................................................................................................. 1-9 1.7.1 R-Tree Indexing.................................................................................................................... 1-9 1.7.2 R-Tree Quality................................................................................................................... 1-10 1.8 Spatial Relationships and Filtering ....................................................................................... 1-11 1.9 Spatial Operators, Procedures, and Functions .................................................................... 1-13 1.10 Spatial Aggregate Functions .................................................................................................. 1-14 1.10.1 SDOAGGRTYPE Object Type......................................................................................... 1-14 1.11 Three-Dimensional Spatial Objects ....................................................................................... 1-15 1.11.1 Modeling Surfaces ............................................................................................................ 1-17 iv 1.11.2 Modeling Solids ................................................................................................................ 1-18 1.11.3 Three-Dimensional Optimized Rectangles ................................................................... 1-19 1.11.4 Using Texture Data........................................................................................................... 1-20 1.11.4.1 Schema Considerations with Texture Data ........................................................... 1-22 1.11.5 Validation Checks for Three-Dimensional Geometries .............................................. 1-23 1.12 Geocoding ................................................................................................................................. 1-24 1.13 Spatial Java Application Programming Interface ............................................................... 1-24 1.14 Predefined User Accounts Created by Spatial..................................................................... 1-25 1.15 Performance and Tuning Information.................................................................................. 1-26 1.16 OGC and ISO Compliance...................................................................................................... 1-26 1.17 Spatial Release (Version) Number......................................................................................... 1-26 1.18 Spatial Application Hardware Requirement Considerations ........................................... 1-27 1.19 Spatial Error Messages ............................................................................................................ 1-27 1.20 Spatial Examples ...................................................................................................................... 1-27 1.21 README File for Spatial and Related Features.................................................................. 1-28 2 Spatial Data Types and Metadata 2.1 Simple Example: Inserting, Indexing, and Querying Spatial Data...................................... 2-1 2.2 SDO_GEOMETRY Object Type ................................................................................................ 2-5 2.2.1 SDO_GTYPE......................................................................................................................... 2-5 2.2.2 SDO_SRID............................................................................................................................. 2-7 2.2.3 SDO_POINT ......................................................................................................................... 2-7 2.2.4 SDO_ELEM_INFO............................................................................................................... 2-7 2.2.5 SDO_ORDINATES ........................................................................................................... 2-11 2.2.6 Usage Considerations ...................................................................................................... 2-11 2.3 SDO_GEOMETRY Methods................................................................................................... 2-12 2.4 SDO_GEOMETRY Constructors............................................................................................ 2-13 2.5 TIN-Related Object Types....................................................................................................... 2-14 2.5.1 SDO_TIN Object Type...................................................................................................... 2-15 2.5.2 SDO_TIN_BLK_TYPE and SDO_TIN_BLK Object Types .......................................... 2-18 2.6 Point Cloud-Related Object Types ........................................................................................ 2-18 2.6.1 SDO_PC Object Type ....................................................................................................... 2-18 2.6.2 SDO_PC_BLK_TYPE and SDO_PC_BLK Object Type ............................................... 2-20 2.7 Geometry Examples................................................................................................................. 2-20 2.7.1 Rectangle............................................................................................................................ 2-20 2.7.2 Polygon with a Hole......................................................................................................... 2-21 2.7.3 Compound Line String .................................................................................................... 2-23 2.7.4 Compound Polygon ......................................................................................................... 2-24 2.7.5 Point.................................................................................................................................... 2-25 2.7.6 Oriented Point ................................................................................................................... 2-27 2.7.7 Type 0 (Zero) Element...................................................................................................... 2-29 2.7.8 Several Two-Dimensional Geometry Types ................................................................. 2-31 2.7.9 Three-Dimensional Geometry Types............................................................................. 2-35 2.8 Geometry Metadata Views..................................................................................................... 2-44 2.8.1 TABLE_NAME.................................................................................................................. 2-45 2.8.2 COLUMN_NAME............................................................................................................ 2-45 2.8.3 DIMINFO........................................................................................................................... 2-45 v 2.8.4 SRID .................................................................................................................................... 2-46 2.9 Spatial Index-Related Structures ........................................................................................... 2-46 2.9.1 Spatial Index Views.......................................................................................................... 2-46 2.9.1.1 xxx_SDO_INDEX_INFO Views............................................................................... 2-46 2.9.1.2 xxx_SDO_INDEX_METADATA Views ................................................................. 2-47 2.9.2 Spatial Index Table Definition ........................................................................................ 2-49 2.9.3 R-Tree Index Sequence Object ........................................................................................ 2-49 2.10 Unit of Measurement Support ............................................................................................... 2-49 2.10.1 Creating a User-Defined Unit of Measurement ........................................................... 2-50 3 SQL Multimedia Type Support 3.1 ST_GEOMETRY and SDO_GEOMETRY Interoperability.................................................... 3-1 3.2 Tolerance Value with SQL Multimedia Types ....................................................................... 3-7 3.3 Avoiding Name Conflicts .......................................................................................................... 3-7 3.4 Annotation Text Type and Views............................................................................................. 3-7 3.4.1 Using the ST_ANNOTATION_TEXT Constructor......................................................... 3-7 3.4.2 Annotation Text Metadata Views...................................................................................... 3-8 4 Loading Spatial Data 4.1 Bulk Loading .............................................................................................................................. 4-1 4.1.1 Bulk Loading SDO_GEOMETRY Objects ........................................................................ 4-1 4.1.2 Bulk Loading Point-Only Data in SDO_GEOMETRY Objects...................................... 4-3 4.2 Transactional Insert Operations Using SQL ........................................................................... 4-3 4.3 Recommendations for Loading and Validating Spatial Data............................................... 4-4 5 Indexing and Querying Spatial Data 5.1 Creating a Spatial Index............................................................................................................. 5-1 5.1.1 Constraining Data to a Geometry Type............................................................................ 5-2 5.1.2 Creating a Cross-Schema Index......................................................................................... 5-2 5.1.3 Using Partitioned Spatial Indexes ..................................................................................... 5-2 5.1.3.1 Creating a Local Partitioned Spatial Index ............................................................... 5-4 5.1.4 Exchanging Partitions Including Indexes ........................................................................ 5-5 5.1.5 Export and Import Considerations with Spatial Indexes and Data ............................. 5-5 5.1.6 Distributed Transactions and Spatial Index Consistency.............................................. 5-6 5.1.7 Rollback Segments and Sort Area Size ............................................................................. 5-6 5.2 Querying Spatial Data................................................................................................................ 5-7 5.2.1 Spatial Query........................................................................................................................ 5-7 5.2.1.1 Primary Filter Operator ............................................................................................... 5-8 5.2.1.2 Primary and Secondary Filter Operator.................................................................... 5-9 5.2.1.3 Within-Distance Operator ........................................................................................ 5-10 5.2.1.4 Nearest Neighbor Operator ..................................................................................... 5-11 5.2.1.5 Spatial Functions........................................................................................................ 5-11 5.2.2 Spatial Join ......................................................................................................................... 5-12 5.2.3 Data and Index Dimensionality, and Spatial Queries................................................. 5-12 vi 6 Coordinate Systems (Spatial Reference Systems) 6.1 Terms and Concepts ................................................................................................................... 6-1 6.1.1 Coordinate System (Spatial Reference System) .............................................................. 6-1 6.1.2 Cartesian Coordinates......................................................................................................... 6-2 6.1.3 Geodetic Coordinates (Geographic Coordinates)........................................................... 6-2 6.1.4 Projected Coordinates ......................................................................................................... 6-2 6.1.5 Local Coordinates ................................................................................................................ 6-2 6.1.6 Geodetic Datum ................................................................................................................... 6-2 6.1.7 Transformation..................................................................................................................... 6-2 6.2 Geodetic Coordinate Support ................................................................................................... 6-2 6.2.1 Geodesy and Two-Dimensional Geometry ..................................................................... 6-3 6.2.2 Choosing a Geodetic or Projected Coordinate System................................................... 6-3 6.2.3 Choosing Non-Ellipsoidal or Ellipsoidal Height ............................................................ 6-3 6.2.3.1 Non-Ellipsoidal Height................................................................................................ 6-4 6.2.3.2 Ellipsoidal Height......................................................................................................... 6-4 6.2.4 Geodetic MBRs..................................................................................................................... 6-5 6.2.5 Other Considerations and Requirements with Geodetic Data ..................................... 6-6 6.3 Local Coordinate Support.......................................................................................................... 6-7 6.4 EPSG Model and Spatial ............................................................................................................ 6-8 6.5 Three-Dimensional Coordinate Reference System Support................................................. 6-9 6.5.1 Geographic 3D Coordinate Reference Systems............................................................ 6-10 6.5.2 Compound Coordinate Reference Systems .................................................................. 6-10 6.5.3 Three-Dimensional Transformations............................................................................. 6-11 6.5.4 Cross-Dimensionality Transformations ........................................................................ 6-16 6.6 TFM_PLAN Object Type ........................................................................................................ 6-17 6.7 Coordinate Systems Data Structures..................................................................................... 6-17 6.7.1 SDO_COORD_AXES Table............................................................................................. 6-18 6.7.2 SDO_COORD_AXIS_NAMES Table ............................................................................. 6-18 6.7.3 SDO_COORD_OP_METHODS Table ........................................................................... 6-19 6.7.4 SDO_COORD_OP_PARAM_USE Table....................................................................... 6-19 6.7.5 SDO_COORD_OP_PARAM_VALS Table .................................................................... 6-20 6.7.6 SDO_COORD_OP_PARAMS Table............................................................................... 6-20 6.7.7 SDO_COORD_OP_PATHS Table .................................................................................. 6-21 6.7.8 SDO_COORD_OPS Table................................................................................................ 6-21 6.7.9 SDO_COORD_REF_SYS Table ....................................................................................... 6-23 6.7.10 SDO_COORD_REF_SYSTEM View............................................................................... 6-24 6.7.11 SDO_COORD_SYS Table ................................................................................................ 6-25 6.7.12 SDO_CRS_COMPOUND View ...................................................................................... 6-25 6.7.13 SDO_CRS_ENGINEERING View .................................................................................. 6-25 6.7.14 SDO_CRS_GEOCENTRIC View .................................................................................... 6-26 6.7.15 SDO_CRS_GEOGRAPHIC2D View............................................................................... 6-26 6.7.16 SDO_CRS_GEOGRAPHIC3D View............................................................................... 6-27 6.7.17 SDO_CRS_PROJECTED View ........................................................................................ 6-27 6.7.18 SDO_CRS_VERTICAL View........................................................................................... 6-28 6.7.19 SDO_DATUM_ENGINEERING View .......................................................................... 6-28 6.7.20 SDO_DATUM_GEODETIC View .................................................................................. 6-29 6.7.21 SDO_DATUM_VERTICAL View................................................................................... 6-30 vii 6.7.22 SDO_DATUMS Table....................................................................................................... 6-31 6.7.23 SDO_ELLIPSOIDS Table ................................................................................................. 6-32 6.7.24 SDO_PREFERRED_OPS_SYSTEM Table...................................................................... 6-32 6.7.25 SDO_PREFERRED_OPS_USER Table ........................................................................... 6-33 6.7.26 SDO_PRIME_MERIDIANS Table .................................................................................. 6-33 6.7.27 SDO_UNITS_OF_MEASURE Table............................................................................... 6-34 6.7.28 Relationships Among Coordinate System Tables and Views.................................... 6-35 6.7.29 Finding Information About EPSG-Based Coordinate Systems.................................. 6-36 6.7.29.1 Geodetic Coordinate Systems.................................................................................. 6-36 6.7.29.2 Projected Coordinate Systems ................................................................................. 6-37 6.8 Legacy Tables and Views........................................................................................................ 6-40 6.8.1 MDSYS.CS_SRS Table...................................................................................................... 6-40 6.8.1.1 Well-Known Text (WKT).......................................................................................... 6-41 6.8.1.2 US-American and European Notations for Datum Parameters ......................... 6-43 6.8.1.3 Procedures for Updating the Well-Known Text ................................................... 6-43 6.8.2 MDSYS.SDO_ANGLE_UNITS View ............................................................................. 6-44 6.8.3 MDSYS.SDO_AREA_UNITS View ................................................................................ 6-44 6.8.4 MDSYS.SDO_DATUMS_OLD_FORMAT and SDO_DATUMS_OLD_SNAPSHOT Tables 6-45 6.8.5 MDSYS.SDO_DIST_UNITS View................................................................................... 6-47 6.8.6 MDSYS.SDO_ELLIPSOIDS_OLD_FORMAT and SDO_ELLIPSOIDS_OLD_ SNAPSHOT Tables 6-47 6.8.7 MDSYS.SDO_PROJECTIONS_OLD_FORMAT and SDO_PROJECTIONS_OLD_ SNAPSHOT Tables 6-48 6.9 Creating a User-Defined Coordinate Reference System .................................................... 6-49 6.9.1 Creating a Geodetic CRS.................................................................................................. 6-50 6.9.2 Creating a Projected CRS................................................................................................. 6-51 6.9.3 Creating a Vertical CRS.................................................................................................... 6-60 6.9.4 Creating a Compound CRS............................................................................................. 6-61 6.9.5 Creating a Geographic 3D CRS....................................................................................... 6-62 6.9.6 Creating a Transformation Operation ........................................................................... 6-62 6.9.7 Using British Grid Transformation OSTN02/OSGM02 (EPSG Method 9633)........ 6-65 6.10 Notes and Restrictions with Coordinate Systems Support................................................ 6-67 6.10.1 Different Coordinate Systems for Geometries with Operators and Functions ....... 6-67 6.10.2 3D LRS Functions Not Supported with Geodetic Data............................................... 6-67 6.10.3 Functions Supported by Approximations with Geodetic Data ................................. 6-67 6.10.4 Unknown CRS and NaC Coordinate Reference Systems ........................................... 6-68 6.11 U.S. National Grid Support .................................................................................................... 6-68 6.12 Google Maps Considerations ................................................................................................. 6-68 6.13 Example of Coordinate System Transformation ................................................................. 6-69 7 Linear Referencing System 7.1 Terms and Concepts ................................................................................................................... 7-1 7.1.1 Geometric Segments (LRS Segments) .............................................................................. 7-1 7.1.2 Shape Points ......................................................................................................................... 7-2 7.1.3 Direction of a Geometric Segment .................................................................................... 7-2 7.1.4 Measure (Linear Measure).................................................................................................. 7-3 viii 7.1.5 Offset...................................................................................................................................... 7-3 7.1.6 Measure Populating ............................................................................................................ 7-3 7.1.7 Measure Range of a Geometric Segment.......................................................................... 7-5 7.1.8 Projection .............................................................................................................................. 7-5 7.1.9 LRS Point............................................................................................................................... 7-5 7.1.10 Linear Features..................................................................................................................... 7-5 7.1.11 Measures with Multiline Strings and Polygons with Holes.......................................... 7-5 7.2 LRS Data Model .......................................................................................................................... 7-6 7.3 Indexing of LRS Data.................................................................................................................. 7-7 7.4 3D Formats of LRS Functions.................................................................................................... 7-7 7.5 LRS Operations............................................................................................................................ 7-8 7.5.1 Defining a Geometric Segment ......................................................................................... 7-8 7.5.2 Redefining a Geometric Segment...................................................................................... 7-8 7.5.3 Clipping a Geometric Segment.......................................................................................... 7-9 7.5.4 Splitting a Geometric Segment .......................................................................................... 7-9 7.5.5 Concatenating Geometric Segments .............................................................................. 7-10 7.5.6 Scaling a Geometric Segment ......................................................................................... 7-11 7.5.7 Offsetting a Geometric Segment..................................................................................... 7-12 7.5.8 Locating a Point on a Geometric Segment .................................................................... 7-12 7.5.9 Projecting a Point onto a Geometric Segment .............................................................. 7-13 7.5.10 Converting LRS Geometries............................................................................................ 7-14 7.6 Tolerance Values with LRS Functions .................................................................................. 7-15 7.7 Example of LRS Functions...................................................................................................... 7-15 8 Spatial Analysis and Mining 8.1 Spatial Information and Data Mining Applications .............................................................. 8-1 8.2 Spatial Binning for Detection of Regional Patterns................................................................ 8-3 8.3 Materializing Spatial Correlation ............................................................................................. 8-3 8.4 Colocation Mining ...................................................................................................................... 8-4 8.5 Spatial Clustering........................................................................................................................ 8-4 8.6 Location Prospecting .................................................................................................................. 8-5 9 Extending Spatial Indexing Capabilities 9.1 SDO_GEOMETRY Objects in User-Defined Type Definitions ............................................ 9-1 9.2 SDO_GEOMETRY Objects in Function-Based Indexes......................................................... 9-3 9.2.1 Example: Function with Standard Types......................................................................... 9-3 9.2.2 Example: Function with a User-Defined Object Type.................................................... 9-4 Part II Spatial Web Services 10 Introduction to Spatial Web Services 10.1 Types of Spatial Web Services................................................................................................ 10-1 10.2 Types of Users of Spatial Web Services ................................................................................ 10-2 10.3 Setting Up the Client for Spatial Web Services.................................................................... 10-2 10.4 Demo Files for Sample Java Client ........................................................................................ 10-6 ix 11 Geocoding Address Data 11.1 Concepts for Geocoding.......................................................................................................... 11-1 11.1.1 Address Representation................................................................................................... 11-1 11.1.2 Match Modes ..................................................................................................................... 11-2 11.1.3 Match Codes...................................................................................................................... 11-3 11.1.4 Error Messages for Output Geocoded Addresses ....................................................... 11-4 11.1.5 Match Vector for Output Geocoded Addresses........................................................... 11-4 11.2 Data Types for Geocoding...................................................................................................... 11-5 11.2.1 SDO_GEO_ADDR Type .................................................................................................. 11-5 11.2.2 SDO_ADDR_ARRAY Type............................................................................................. 11-8 11.2.3 SDO_KEYWORDARRAY Type...................................................................................... 11-8 11.3 Using the Geocoding Capabilities ......................................................................................... 11-8 11.4 Geocoding from a Place Name............................................................................................... 11-9 11.5 Data Structures for Geocoding............................................................................................. 11-10 11.5.1 GC_ADDRESS_POINT_ Table and Index.................................................... 11-11 11.5.2 GC_AREA_ Table ............................................................................................ 11-12 11.5.3 GC_COUNTRY_PROFILE Table.................................................................................. 11-14 11.5.4 GC_INTERSECTION_ Table.......................................................................... 11-15 11.5.5 GC_PARSER_PROFILES Table .................................................................................... 11-16 11.5.6 GC_PARSER_PROFILEAFS Table ............................................................................... 11-19 11.5.6.1 ADDRESS_FORMAT_STRING Description ....................................................... 11-20 11.5.7 GC_POI_ Table................................................................................................. 11-22 11.5.8 GC_POSTAL_CODE_ Table........................................................................... 11-23 11.5.9 GC_ROAD_ Table............................................................................................ 11-24 11.5.10 GC_ROAD_SEGMENT_ Table ...................................................................... 11-26 11.5.11 Indexes on Tables for Geocoding ................................................................................. 11-28 11.6 Installing the Profile Tables.................................................................................................. 11-29 11.7 Using the Geocoding Service (XML API)........................................................................... 11-30 11.7.1 Deploying and Configuring the J2EE Geocoder ........................................................ 11-31 11.7.1.1 Configuring the geocodercfg.xml File.................................................................. 11-32 11.7.2 Geocoding Request XML Schema Definition and Example ..................................... 11-33 11.7.3 Geocoding Response XML Schema Definition and Example .................................. 11-36 12 Business Directory (Yellow Pages) Support 12.1 Business Directory Concepts.................................................................................................. 12-1 12.2 Using the Business Directory Capabilities ........................................................................... 12-1 12.3 Data Structures for Business Directory Support ................................................................. 12-2 12.3.1 OPENLS_DIR_BUSINESSES Table................................................................................ 12-2 12.3.2 OPENLS_DIR_BUSINESS_CHAINS Table................................................................... 12-3 12.3.3 OPENLS_DIR_CATEGORIES Table.............................................................................. 12-3 12.3.4 OPENLS_DIR_CATEGORIZATIONS Table ................................................................ 12-4 12.3.5 OPENLS_DIR_CATEGORY_TYPES Table ................................................................... 12-4 12.3.6 OPENLS_DIR_SYNONYMS Table ................................................................................ 12-5 13 Routing Engine 13.1 Deploying and Configuring the Routing Engine................................................................ 13-2 x 13.1.1 Configuring the web.xml File ......................................................................................... 13-4 13.2 Routing Engine XML API....................................................................................................... 13-5 13.2.1 Route Request and Response Examples........................................................................ 13-6 13.2.2 Route Request DTD........................................................................................................ 13-12 13.2.2.1 route_request Element............................................................................................ 13-13 13.2.2.2 route_request Attributes......................................................................................... 13-13 13.2.2.3 input_location Element........................................................................................... 13-15 13.2.2.4 pre_geocoded_location Element ........................................................................... 13-15 13.2.3 Route Response DTD ..................................................................................................... 13-15 13.2.4 Batch Route Request and Response Examples........................................................... 13-16 13.2.5 Batch Route Request DTD ............................................................................................. 13-19 13.2.5.1 batch_route_request Element ................................................................................ 13-19 13.2.5.2 batch_route_request Attributes............................................................................. 13-20 13.2.6 Batch Route Response DTD .......................................................................................... 13-20 13.3 Data Structures Used by the Routing Engine .................................................................... 13-21 13.3.1 EDGE Table ..................................................................................................................... 13-21 13.3.2 NODE Table..................................................................................................................... 13-22 13.3.3 PARTITION Table .......................................................................................................... 13-22 13.3.4 SIGN_POST Table........................................................................................................... 13-22 14 OpenLS Support 14.1 Supported OpenLS Services................................................................................................... 14-1 14.2 OpenLS Application Programming Interfaces .................................................................... 14-2 14.3 OpenLS Service Support and Examples ............................................................................... 14-2 14.3.1 OpenLS Geocoding........................................................................................................... 14-2 14.3.2 OpenLS Mapping.............................................................................................................. 14-4 14.3.3 OpenLS Routing................................................................................................................ 14-6 14.3.4 OpenLS Directory Service (YP)....................................................................................... 14-8 15 Web Feature Service (WFS) Support 15.1 WFS Engine............................................................................................................................... 15-1 15.2 Managing Feature Types ........................................................................................................ 15-2 15.2.1 Capabilities Documents................................................................................................... 15-3 15.3 Request and Response XML Examples................................................................................. 15-4 15.4 Java API for WFS Administration ....................................................................................... 15-13 15.4.1 createXMLTableIndex method ..................................................................................... 15-13 15.4.2 dropFeatureType method.............................................................................................. 15-13 15.4.3 dropXMLTableIndex method ....................................................................................... 15-14 15.4.4 getIsXMLTableIndexCreated method ......................................................................... 15-14 15.4.5 grantFeatureTypeToUser method................................................................................ 15-14 15.4.6 grantMDAccessToUser method ................................................................................... 15-15 15.4.7 publishFeatureType method......................................................................................... 15-15 15.4.7.1 Related Classes for publishFeatureType.............................................................. 15-19 15.4.8 revokeFeatureTypeFromUser method ........................................................................ 15-23 15.4.9 revokeMDAccessFromUser method............................................................................ 15-23 15.4.10 setXMLTableIndexInfo method.................................................................................... 15-23 15.5 Using WFS with Oracle Workspace Manager ................................................................... 15-24 xi 16 Catalog Services for the Web (CSW) Support 16.1 CSW Engine and Architecture ............................................................................................... 16-1 16.2 CSW APIs and Configuration ................................................................................................ 16-2 16.2.1 Capabilities Documents................................................................................................... 16-3 16.2.2 Spatial Path Extractor Function (extractSDO) .............................................................. 16-3 16.2.2.1 Registering and Unregistering the extractSDO Function.................................... 16-5 16.3 Request and Response XML Examples................................................................................. 16-5 16.4 Java API for CSW Administration....................................................................................... 16-15 16.4.1 createXMLTableIndex method ..................................................................................... 16-15 16.4.2 deleteDomainInfo method ............................................................................................ 16-15 16.4.3 deleteRecordViewMap method.................................................................................... 16-16 16.4.4 disableVersioning method ............................................................................................ 16-16 16.4.5 dropRecordType method .............................................................................................. 16-16 16.4.6 dropXMLTableIndex method ....................................................................................... 16-17 16.4.7 enableVersioning method.............................................................................................. 16-17 16.4.8 getIsXMLTableIndexCreated method ......................................................................... 16-17 16.4.9 getRecordTypeId method.............................................................................................. 16-17 16.4.10 grantMDAccessToUser method ................................................................................... 16-18 16.4.11 grantRecordTypeToUser method................................................................................. 16-18 16.4.12 publishRecordType method.......................................................................................... 16-18 16.4.12.1 Related Classes for publishRecordType............................................................... 16-22 16.4.13 registerTypePluginMap method .................................................................................. 16-26 16.4.14 revokeMDAccessFromUser method............................................................................ 16-26 16.4.15 revokeRecordTypeFromUser method ......................................................................... 16-26 16.4.16 setCapabilitiesInfo method ........................................................................................... 16-27 16.4.17 setDomainInfo method .................................................................................................. 16-27 16.4.18 setRecordViewMap method.......................................................................................... 16-27 16.4.19 setXMLTableIndexInfo method.................................................................................... 16-28 17 Security Considerations for Spatial Web Services 17.1 User Management.................................................................................................................... 17-1 17.1.1 Identity Propagation to the Database ............................................................................ 17-2 17.1.2 Caching and User Administration ................................................................................. 17-2 17.2 Access Control and Versioning.............................................................................................. 17-3 17.2.1 Virtual Private Databases ................................................................................................ 17-3 17.2.2 Workspace Manager......................................................................................................... 17-3 17.3 Deploying and Configuring the .ear File.............................................................................. 17-4 17.3.1 Adding Spatial Service Handlers ................................................................................... 17-5 17.4 Interfaces for Spatial Web Services........................................................................................ 17-6 17.4.1 SOAP/WSS Interface ....................................................................................................... 17-6 17.4.2 XML (Non-SOAP) Interface ............................................................................................ 17-6 17.4.3 PL/SQL Interface (OpenLS Only).................................................................................. 17-7 17.4.4 Level of Security, by Interface......................................................................................... 17-7 Part III Reference Information xii 18 SQL Statements for Indexing Spatial Data ALTER INDEX ......................................................................................................................... 18-2 ALTER INDEX REBUILD....................................................................................................... 18-4 ALTER INDEX RENAME TO ................................................................................................ 18-7 CREATE INDEX....................................................................................................................... 18-8 DROP INDEX ......................................................................................................................... 18-12 19 Spatial Operators SDO_ANYINTERACT ............................................................................................................ 19-3 SDO_CONTAINS .................................................................................................................... 19-5 SDO_COVEREDBY ................................................................................................................. 19-7 SDO_COVERS .......................................................................................................................... 19-9 SDO_EQUAL.......................................................................................................................... 19-11 SDO_FILTER........................................................................................................................... 19-13 SDO_INSIDE .......................................................................................................................... 19-16 SDO_JOIN............................................................................................................................... 19-18 SDO_NN ................................................................................................................................. 19-23 SDO_NN_DISTANCE........................................................................................................... 19-28 SDO_ON.................................................................................................................................. 19-30 SDO_OVERLAPBDYDISJOINT........................................................................................... 19-32 SDO_OVERLAPBDYINTERSECT....................................................................................... 19-34 SDO_OVERLAPS................................................................................................................... 19-36 SDO_RELATE......................................................................................................................... 19-38 SDO_TOUCH ......................................................................................................................... 19-42 SDO_WITHIN_DISTANCE.................................................................................................. 19-44 20 Spatial Aggregate Functions SDO_AGGR_CENTROID....................................................................................................... 20-2 SDO_AGGR_CONCAT_LINES............................................................................................. 20-3 SDO_AGGR_CONVEXHULL................................................................................................ 20-5 SDO_AGGR_LRS_CONCAT ................................................................................................. 20-6 SDO_AGGR_MBR ................................................................................................................... 20-8 SDO_AGGR_SET_UNION..................................................................................................... 20-9 SDO_AGGR_UNION............................................................................................................ 20-11 21 SDO_CS Package (Coordinate System Transformation) SDO_CS.ADD_PREFERENCE_FOR_OP ............................................................................. 21-4 SDO_CS.CONVERT_NADCON_TO_XML ......................................................................... 21-6 SDO_CS.CONVERT_NTV2_TO_XML ................................................................................. 21-8 SDO_CS.CONVERT_XML_TO_NADCON ....................................................................... 21-10 SDO_CS.CONVERT_XML_TO_NTV2 ............................................................................... 21-12 xiii SDO_CS.CREATE_CONCATENATED_OP ...................................................................... 21-14 SDO_CS.CREATE_OBVIOUS_EPSG_RULES ................................................................... 21-15 SDO_CS.CREATE_PREF_CONCATENATED_OP .......................................................... 21-16 SDO_CS.DELETE_ALL_EPSG_RULES .............................................................................. 21-18 SDO_CS.DELETE_OP ........................................................................................................... 21-19 SDO_CS.DETERMINE_CHAIN .......................................................................................... 21-20 SDO_CS.DETERMINE_DEFAULT_CHAIN ..................................................................... 21-22 SDO_CS.FIND_GEOG_CRS................................................................................................. 21-23 SDO_CS.FIND_PROJ_CRS ................................................................................................... 21-25 SDO_CS.FIND_SRID............................................................................................................. 21-27 SDO_CS.FROM_OGC_SIMPLEFEATURE_SRS ............................................................... 21-31 SDO_CS.FROM_USNG......................................................................................................... 21-32 SDO_CS.GET_EPSG_DATA_VERSION............................................................................. 21-33 SDO_CS.MAKE_2D............................................................................................................... 21-34 SDO_CS.MAKE_3D............................................................................................................... 21-35 SDO_CS.MAP_EPSG_SRID_TO_ORACLE ....................................................................... 21-36 SDO_CS.MAP_ORACLE_SRID_TO_EPSG ....................................................................... 21-37 SDO_CS.REVOKE_PREFERENCE_FOR_OP .................................................................... 21-38 SDO_CS.TO_OGC_SIMPLEFEATURE_SRS...................................................................... 21-39 SDO_CS.TO_USNG ............................................................................................................... 21-40 SDO_CS.TRANSFORM......................................................................................................... 21-42 SDO_CS.TRANSFORM_LAYER ......................................................................................... 21-44 SDO_CS.UPDATE_WKTS_FOR_ALL_EPSG_CRS .......................................................... 21-46 SDO_CS.UPDATE_WKTS_FOR_EPSG_CRS .................................................................... 21-47 SDO_CS.UPDATE_WKTS_FOR_EPSG_DATUM ............................................................ 21-48 SDO_CS.UPDATE_WKTS_FOR_EPSG_ELLIPS............................................................... 21-49 SDO_CS.UPDATE_WKTS_FOR_EPSG_OP ...................................................................... 21-50 SDO_CS.UPDATE_WKTS_FOR_EPSG_PARAM............................................................. 21-51 SDO_CS.UPDATE_WKTS_FOR_EPSG_PM...................................................................... 21-52 SDO_CS.VALIDATE_WKT.................................................................................................. 21-53 22 SDO_CSW_PROCESS Package (CSW Processing) SDO_CSW_PROCESS.DeleteCapabilitiesInfo..................................................................... 22-2 SDO_CSW_PROCESS.DeleteDomainInfo............................................................................ 22-3 SDO_CSW_PROCESS.DeletePluginMap ............................................................................. 22-4 SDO_CSW_PROCESS.DeleteRecordViewMap ................................................................... 22-5 SDO_CSW_PROCESS.GetRecordTypeId............................................................................. 22-6 SDO_CSW_PROCESS.InsertCapabilitiesInfo ...................................................................... 22-7 SDO_CSW_PROCESS.InsertDomainInfo............................................................................. 22-8 SDO_CSW_PROCESS.InsertPluginMap .............................................................................. 22-9 SDO_CSW_PROCESS.InsertRecordViewMap .................................................................. 22-10 xiv SDO_CSW_PROCESS.InsertRtDataUpdated .................................................................... 22-12 SDO_CSW_PROCESS.InsertRtMDUpdated...................................................................... 22-13 23 SDO_GCDR Package (Geocoding) SDO_GCDR.CREATE_PROFILE_TABLES.......................................................................... 23-2 SDO_GCDR.GEOCODE ......................................................................................................... 23-3 SDO_GCDR.GEOCODE_ADDR ........................................................................................... 23-4 SDO_GCDR.GEOCODE_ADDR_ALL ................................................................................. 23-6 SDO_GCDR.GEOCODE_ALL ............................................................................................... 23-8 SDO_GCDR.GEOCODE_AS_GEOMETRY ....................................................................... 23-10 SDO_GCDR.REVERSE_GEOCODE.................................................................................... 23-11 24 SDO_GEOM Package (Geometry) SDO_GEOM.RELATE ............................................................................................................. 24-4 SDO_GEOM.SDO_ALPHA_SHAPE..................................................................................... 24-7 SDO_GEOM.SDO_ARC_DENSIFY....................................................................................... 24-9 SDO_GEOM.SDO_AREA..................................................................................................... 24-11 SDO_GEOM.SDO_BUFFER ................................................................................................. 24-13 SDO_GEOM.SDO_CENTROID ........................................................................................... 24-16 SDO_GEOM.SDO_CLOSEST_POINTS .............................................................................. 24-18 SDO_GEOM.SDO_CONCAVEHULL ................................................................................ 24-20 SDO_GEOM.SDO_CONCAVEHULL_BOUNDARY....................................................... 24-22 SDO_GEOM.SDO_CONVEXHULL.................................................................................... 24-24 SDO_GEOM.SDO_DIFFERENCE ....................................................................................... 24-26 SDO_GEOM.SDO_DISTANCE............................................................................................ 24-28 SDO_GEOM.SDO_INTERSECTION .................................................................................. 24-30 SDO_GEOM.SDO_LENGTH ............................................................................................... 24-32 SDO_GEOM.SDO_MAX_MBR_ORDINATE .................................................................... 24-34 SDO_GEOM.SDO_MBR ....................................................................................................... 24-36 SDO_GEOM.SDO_MIN_MBR_ORDINATE ..................................................................... 24-38 SDO_GEOM.SDO_POINTONSURFACE........................................................................... 24-40 SDO_GEOM.SDO_TRIANGULATE................................................................................... 24-42 SDO_GEOM.SDO_UNION .................................................................................................. 24-43 SDO_GEOM.SDO_VOLUME............................................................................................... 24-45 SDO_GEOM.SDO_XOR........................................................................................................ 24-47 SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT........................................... 24-49 SDO_GEOM.VALIDATE_LAYER_WITH_CONTEXT .................................................... 24-53 SDO_GEOM.WITHIN_DISTANCE .................................................................................... 24-56 25 SDO_LRS Package (Linear Referencing System) SDO_LRS.CLIP_GEOM_SEGMENT..................................................................................... 25-5 SDO_LRS.CONCATENATE_GEOM_SEGMENTS ............................................................ 25-7 xv SDO_LRS.CONNECTED_GEOM_SEGMENTS................................................................ 25-10 SDO_LRS.CONVERT_TO_LRS_DIM_ARRAY................................................................. 25-12 SDO_LRS.CONVERT_TO_LRS_GEOM............................................................................. 25-14 SDO_LRS.CONVERT_TO_LRS_LAYER............................................................................ 25-16 SDO_LRS.CONVERT_TO_STD_DIM_ARRAY ................................................................ 25-18 SDO_LRS.CONVERT_TO_STD_GEOM ............................................................................ 25-19 SDO_LRS.CONVERT_TO_STD_LAYER............................................................................ 25-20 SDO_LRS.DEFINE_GEOM_SEGMENT ............................................................................. 25-22 SDO_LRS.DYNAMIC_SEGMENT ...................................................................................... 25-25 SDO_LRS.FIND_LRS_DIM_POS......................................................................................... 25-27 SDO_LRS.FIND_MEASURE ................................................................................................ 25-28 SDO_LRS.FIND_OFFSET ..................................................................................................... 25-30 SDO_LRS.GEOM_SEGMENT_END_MEASURE ............................................................. 25-32 SDO_LRS.GEOM_SEGMENT_END_PT ............................................................................ 25-33 SDO_LRS.GEOM_SEGMENT_LENGTH........................................................................... 25-34 SDO_LRS.GEOM_SEGMENT_START_MEASURE ......................................................... 25-35 SDO_LRS.GEOM_SEGMENT_START_PT ........................................................................ 25-36 SDO_LRS.GET_MEASURE .................................................................................................. 25-37 SDO_LRS.GET_NEXT_SHAPE_PT..................................................................................... 25-38 SDO_LRS.GET_NEXT_SHAPE_PT_MEASURE ............................................................... 25-40 SDO_LRS.GET_PREV_SHAPE_PT ..................................................................................... 25-42 SDO_LRS.GET_PREV_SHAPE_PT_MEASURE................................................................ 25-44 SDO_LRS.IS_GEOM_SEGMENT_DEFINED .................................................................... 25-46 SDO_LRS.IS_MEASURE_DECREASING .......................................................................... 25-47 SDO_LRS.IS_MEASURE_INCREASING ........................................................................... 25-48 SDO_LRS.IS_SHAPE_PT_MEASURE................................................................................. 25-49 SDO_LRS.LOCATE_PT......................................................................................................... 25-51 SDO_LRS.LRS_INTERSECTION......................................................................................... 25-53 SDO_LRS.MEASURE_RANGE............................................................................................ 25-55 SDO_LRS.MEASURE_TO_PERCENTAGE ....................................................................... 25-56 SDO_LRS.OFFSET_GEOM_SEGMENT ............................................................................. 25-58 SDO_LRS.PERCENTAGE_TO_MEASURE ....................................................................... 25-61 SDO_LRS.PROJECT_PT........................................................................................................ 25-63 SDO_LRS.REDEFINE_GEOM_SEGMENT........................................................................ 25-65 SDO_LRS.RESET_MEASURE .............................................................................................. 25-67 SDO_LRS.REVERSE_GEOMETRY...................................................................................... 25-69 SDO_LRS.REVERSE_MEASURE......................................................................................... 25-71 SDO_LRS.SCALE_GEOM_SEGMENT............................................................................... 25-73 SDO_LRS.SET_PT_MEASURE ............................................................................................ 25-75 SDO_LRS.SPLIT_GEOM_SEGMENT ................................................................................. 25-78 SDO_LRS.TRANSLATE_MEASURE .................................................................................. 25-80 xvi SDO_LRS.VALID_GEOM_SEGMENT ............................................................................... 25-82 SDO_LRS.VALID_LRS_PT................................................................................................... 25-83 SDO_LRS.VALID_MEASURE ............................................................................................. 25-84 SDO_LRS.VALIDATE_LRS_GEOMETRY ......................................................................... 25-86 26 SDO_MIGRATE Package (Upgrading) SDO_MIGRATE.TO_CURRENT ........................................................................................... 26-2 27 SDO_OLS Package (OpenLS) SDO_OLS.MakeOpenLSClobRequest................................................................................... 27-2 SDO_OLS.MakeOpenLSRequest........................................................................................... 27-4 28 SDO_PC_PKG Package (Point Clouds) SDO_PC_PKG.CLIP_PC ......................................................................................................... 28-2 SDO_PC_PKG.CREATE_PC .................................................................................................. 28-4 SDO_PC_PKG.DROP_DEPENDENCIES............................................................................. 28-6 SDO_PC_PKG.GET_PT_IDS .................................................................................................. 28-7 SDO_PC_PKG.INIT ................................................................................................................. 28-8 SDO_PC_PKG.TO_GEOMETRY ......................................................................................... 28-11 29 SDO_SAM Package (Spatial Analysis and Mining) SDO_SAM.AGGREGATES_FOR_GEOMETRY.................................................................. 29-3 SDO_SAM.AGGREGATES_FOR_LAYER ........................................................................... 29-5 SDO_SAM.BIN_GEOMETRY ................................................................................................ 29-7 SDO_SAM.BIN_LAYER.......................................................................................................... 29-9 SDO_SAM.COLOCATED_REFERENCE_FEATURES..................................................... 29-11 SDO_SAM.SIMPLIFY_GEOMETRY ................................................................................... 29-13 SDO_SAM.SIMPLIFY_LAYER ............................................................................................ 29-15 SDO_SAM.SPATIAL_CLUSTERS....................................................................................... 29-17 SDO_SAM.TILED_AGGREGATES..................................................................................... 29-18 SDO_SAM.TILED_BINS ....................................................................................................... 29-21 30 SDO_TIN_PKG Package (TINs) SDO_TIN_PKG.CLIP_TIN ..................................................................................................... 30-2 SDO_TIN_PKG.CREATE_TIN............................................................................................... 30-4 SDO_TIN_PKG.DROP_DEPENDENCIES........................................................................... 30-6 SDO_TIN_PKG.INIT ............................................................................................................... 30-7 SDO_TIN_PKG.TO_GEOMETRY ....................................................................................... 30-10 31 SDO_TUNE Package (Tuning) SDO_TUNE.AVERAGE_MBR ............................................................................................... 31-2 SDO_TUNE.ESTIMATE_RTREE_INDEX_SIZE.................................................................. 31-4 xvii SDO_TUNE.EXTENT_OF....................................................................................................... 31-7 SDO_TUNE.MIX_INFO.......................................................................................................... 31-8 SDO_TUNE.QUALITY_DEGRADATION......................................................................... 31-10 32 SDO_UTIL Package (Utility) SDO_UTIL.AFFINETRANSFORMS...................................................................................... 32-3 SDO_UTIL.APPEND............................................................................................................... 32-9 SDO_UTIL.BEARING_TILT_FOR_POINTS...................................................................... 32-10 SDO_UTIL.CIRCLE_POLYGON......................................................................................... 32-12 SDO_UTIL.CONCAT_LINES .............................................................................................. 32-14 SDO_UTIL.CONVERT_UNIT.............................................................................................. 32-16 SDO_UTIL.DROP_WORK_TABLES................................................................................... 32-17 SDO_UTIL.ELLIPSE_POLYGON........................................................................................ 32-18 SDO_UTIL.EXTRACT ........................................................................................................... 32-20 SDO_UTIL.EXTRACT3D ...................................................................................................... 32-23 SDO_UTIL.EXTRUDE........................................................................................................... 32-25 SDO_UTIL.FROM_GML311GEOMETRY .......................................................................... 32-28 SDO_UTIL.FROM_GMLGEOMETRY ................................................................................ 32-30 SDO_UTIL.FROM_KMLGEOMETRY ................................................................................ 32-32 SDO_UTIL.FROM_WKBGEOMETRY................................................................................ 32-34 SDO_UTIL.FROM_WKTGEOMETRY................................................................................ 32-36 SDO_UTIL.GETNUMELEM ................................................................................................ 32-38 SDO_UTIL.GETNUMVERTICES ........................................................................................ 32-39 SDO_UTIL.GETVERTICES................................................................................................... 32-40 SDO_UTIL.INITIALIZE_INDEXES_FOR_TTS ................................................................. 32-42 SDO_UTIL.INTERIOR_POINT............................................................................................ 32-44 SDO_UTIL.POINT_AT_BEARING ..................................................................................... 32-45 SDO_UTIL.POLYGONTOLINE .......................................................................................... 32-47 SDO_UTIL.PREPARE_FOR_TTS......................................................................................... 32-48 SDO_UTIL.RECTIFY_GEOMETRY .................................................................................... 32-49 SDO_UTIL.REMOVE_DUPLICATE_VERTICES.............................................................. 32-51 SDO_UTIL.REVERSE_LINESTRING.................................................................................. 32-53 SDO_UTIL.SIMPLIFY ........................................................................................................... 32-54 SDO_UTIL.TO_GML311GEOMETRY ................................................................................ 32-57 SDO_UTIL.TO_GMLGEOMETRY ...................................................................................... 32-62 SDO_UTIL.TO_KMLGEOMETRY ...................................................................................... 32-68 SDO_UTIL.TO_WKBGEOMETRY ...................................................................................... 32-70 SDO_UTIL.TO_WKTGEOMETRY ...................................................................................... 32-72 SDO_UTIL.VALIDATE_WKBGEOMETRY....................................................................... 32-74 SDO_UTIL.VALIDATE_WKTGEOMETRY....................................................................... 32-76 xviii 33 SDO_WFS_LOCK Package (WFS) SDO_WFS_LOCK.EnableDBTxns ......................................................................................... 33-2 SDO_WFS_LOCK.RegisterFeatureTable.............................................................................. 33-3 SDO_WFS_LOCK.UnRegisterFeatureTable ........................................................................ 33-4 34 SDO_WFS_PROCESS Package (WFS Processing) SDO_WFS_PROCESS.DropFeatureType ............................................................................. 34-3 SDO_WFS_PROCESS.DropFeatureTypes............................................................................ 34-4 SDO_WFS_PROCESS.GenCollectionProcs .......................................................................... 34-5 SDO_WFS_PROCESS.GetFeatureTypeId............................................................................. 34-6 SDO_WFS_PROCESS.GrantFeatureTypeToUser................................................................ 34-7 SDO_WFS_PROCESS.GrantMDAccessToUser ................................................................... 34-8 SDO_WFS_PROCESS.InsertCapabilitiesInfo....................................................................... 34-9 SDO_WFS_PROCESS.InsertFtDataUpdated ..................................................................... 34-10 SDO_WFS_PROCESS.InsertFtMDUpdated....................................................................... 34-11 SDO_WFS_PROCESS.PopulateFeatureTypeXMLInfo..................................................... 34-12 SDO_WFS_PROCESS.PublishFeatureType ....................................................................... 34-13 SDO_WFS_PROCESS.RegisterMTableView...................................................................... 34-17 SDO_WFS_PROCESS.RevokeFeatureTypeFromUser...................................................... 34-20 SDO_WFS_PROCESS.RevokeMDAccessFromUser ......................................................... 34-21 SDO_WFS_PROCESS.UnRegisterMTableView ................................................................ 34-22 Part IV Supplementary Information A Installation, Compatibility, and Upgrade A.1 Ensuring That GeoRaster Works Properly After an Installation or Upgrade................... A-1 A.2 Index Maintenance Before and After an Upgrade (WFS and CSW) .................................. A-1 A.3 Increasing the Size of Ordinate Arrays to Support Very Large Geometries..................... A-2 B Oracle Locator B.1 Installing and Deinstalling Locator or Spatial Manually..................................................... B-4 C Complex Spatial Queries: Examples C.1 Tables Used in the Examples.................................................................................................... C-1 C.2 SDO_WITHIN_DISTANCE Examples ................................................................................... C-2 C.3 SDO_NN Examples ................................................................................................................... C-3 C.4 SDO_AGGR_UNION Example ............................................................................................... C-5 D Loading ESRI Shapefiles into Spatial D.1 Usage of the Shapefile Converter ............................................................................................ D-1 D.2 Examples of the Shapefile Converter...................................................................................... D-2 xix Glossary Index xx List of Examples 1–1 Inserting Texture Coordinate Definitions ............................................................................ 1-22 1–2 Creating Tables for Texture Coordinates, Textures, and Surfaces ................................... 1-23 2–1 Simple Example: Inserting, Indexing, and Querying Spatial Data...................................... 2-2 2–2 SDO_GEOMETRY Methods................................................................................................... 2-12 2–3 SDO_GEOMETRY Constructors to Create Geometries ..................................................... 2-14 2–4 SDO_TIN Attribute in a Query.............................................................................................. 2-18 2–5 SDO_PC Attribute in a Query................................................................................................ 2-20 2–6 SQL Statement to Insert a Rectangle ..................................................................................... 2-21 2–7 SQL Statement to Insert a Polygon with a Hole.................................................................. 2-22 2–8 SQL Statement to Insert a Compound Line String.............................................................. 2-24 2–9 SQL Statement to Insert a Compound Polygon .................................................................. 2-25 2–10 SQL Statement to Insert a Point-Only Geometry ................................................................ 2-26 2–11 Query for Point-Only Geometry Based on a Coordinate Value ....................................... 2-26 2–12 SQL Statement to Insert an Oriented Point Geometry ....................................................... 2-28 2–13 SQL Statement to Insert an Oriented Multipoint Geometry ............................................. 2-29 2–14 SQL Statement to Insert a Geometry with a Type 0 Element............................................ 2-30 2–15 SQL Statements to Insert Various Two-Dimensional Geometries.................................... 2-31 2–16 SQL Statements to Insert Three-Dimensional Geometries ................................................ 2-35 2–17 Updating Metadata and Creating Indexes for 3-Dimensional Geometries..................... 2-43 2–18 Creating and Using a User-Defined Unit of Measurement ............................................... 2-51 3–1 Using the ST_GEOMETRY Type for a Spatial Column......................................................... 3-2 3–2 Creating, Indexing, Storing, and Querying ST_GEOMETRY Data ..................................... 3-2 3–3 Using the ST_ANNOTATION_TEXT Constructor................................................................ 3-8 4–1 Control File for a Bulk Load of Cola Market Geometries ..................................................... 4-1 4–2 Control File for a Bulk Load of Polygons ................................................................................ 4-2 4–3 Control File for a Bulk Load of Point-Only Data.................................................................... 4-3 4–4 Procedure to Perform a Transactional Insert Operation ....................................................... 4-4 4–5 PL/SQL Block Invoking a Procedure to Insert a Geometry ................................................. 4-4 5–1 Primary Filter with a Temporary Query Window................................................................. 5-8 5–2 Primary Filter with a Transient Instance of the Query Window ......................................... 5-9 5–3 Primary Filter with a Stored Query Window ......................................................................... 5-9 5–4 Secondary Filter Using a Temporary Query Window .......................................................... 5-9 5–5 Secondary Filter Using a Stored Query Window................................................................ 5-10 6–1 Using a Geodetic MBR ............................................................................................................... 6-5 6–2 Three-Dimensional Datum Transformation ........................................................................ 6-11 6–3 Transformation Between Geoidal And Ellipsoidal Height................................................ 6-13 6–4 Cross-Dimensionality Transformation ................................................................................. 6-16 6–5 Creating a User-Defined Geodetic Coordinate Reference System ................................... 6-50 6–6 Inserting a Row into the SDO_COORD_SYS Table............................................................ 6-51 6–7 Creating a User-Defined Projected Coordinate Reference System................................... 6-52 6–8 Inserting a Row into the SDO_COORD_OPS Table ........................................................... 6-53 6–9 Inserting a Row into the SDO_COORD_OP_PARAM_VALS Table................................ 6-53 6–10 Creating a User-Defined Projected CRS: Extended Example............................................ 6-55 6–11 Creating a Vertical Coordinate Reference System .............................................................. 6-60 6–12 Creating a Compound Coordinate Reference System........................................................ 6-61 6–13 Creating a Geographic 3D Coordinate Reference System ................................................. 6-62 6–14 Creating a Transformation Operation .................................................................................. 6-63 6–15 Loading Offset Matrixes ......................................................................................................... 6-64 6–16 Using British Grid Transformation OSTN02/OSGM02 (EPSG Method 9633) ............... 6-66 6–17 Simplified Example of Coordinate System Transformation.............................................. 6-70 6–18 Output of SELECT Statements in Coordinate System Transformation Example .......... 6-72 7–1 Including LRS Measure Dimension in Spatial Metadata...................................................... 7-6 7–2 Simplified Example: Highway............................................................................................... 7-17 7–3 Simplified Example: Output of SELECT Statements.......................................................... 7-20 xxi 10–1 WSConfig.xml File ................................................................................................................... 10-3 11–1 Geocoding, Returning Address Object and Specific Attributes........................................ 11-7 11–2 Geocoding from a Place Name and Country....................................................................... 11-9 11–3 Geocoding from a Place Name, Country, and Other Fields............................................ 11-10 11–4 XML Definition for the US Address Format...................................................................... 11-19 11–5 Required Indexes on Tables for Geocoding ....................................................................... 11-28 11–6 Element Definitions.......................................................................................... 11-32 11–7 Geocoding Request (XML API)............................................................................................ 11-35 11–8 Geocoding Response (XML API)......................................................................................... 11-37 13–1 Route Request with Specified Addresses............................................................................. 13-7 13–2 Route Response with Specified Addresses .......................................................................... 13-7 13–3 Route Request with Specified Longitude/Latitude Points................................................ 13-9 13–4 Route Response with Specified Longitude/Latitude Points............................................. 13-9 13–5 Route Request with Previously Geocoded Locations....................................................... 13-10 13–6 Route Response with Previously Geocoded Locations .................................................... 13-11 13–7 Batch Route Request with Specified Addresses ................................................................ 13-16 13–8 Batch Route Response with Specified Addresses ............................................................. 13-17 13–9 Batch Route Request with Previously Geocoded Locations............................................ 13-18 13–10 Batch Route Response with Previously Geocoded Locations ......................................... 13-18 14–1 OpenLS Geocoding Request................................................................................................... 14-2 14–2 OpenLS Geocoding Response ................................................................................................ 14-3 14–3 OpenLS Mapping Request...................................................................................................... 14-4 14–4 OpenLS Mapping Response................................................................................................... 14-5 14–5 OpenLS Routing Request........................................................................................................ 14-6 14–6 OpenLS Routing Response ..................................................................................................... 14-7 14–7 OpenLS Directory Service (YP) Request............................................................................... 14-8 14–8 OpenLS Directory Service (YP) Response ............................................................................ 14-9 15–1 GetCapabilities Request.......................................................................................................... 15-4 15–2 GetCapabilities Response ....................................................................................................... 15-4 15–3 DescribeFeatureType Request................................................................................................ 15-7 15–4 DescribeFeatureType Response............................................................................................. 15-7 15–5 GetFeature Request.................................................................................................................. 15-8 15–6 GetFeature Response ............................................................................................................... 15-8 15–7 GetFeatureWithLock Request ................................................................................................ 15-9 15–8 GetFeatureWithLock Response............................................................................................ 15-10 15–9 LockFeature Request ............................................................................................................. 15-10 15–10 LockFeature Response........................................................................................................... 15-10 15–11 Insert Request ......................................................................................................................... 15-11 15–12 Insert Response ...................................................................................................................... 15-11 15–13 Update Request ...................................................................................................................... 15-11 15–14 Update Response ................................................................................................................... 15-12 15–15 Delete Request........................................................................................................................ 15-12 15–16 Delete Response ..................................................................................................................... 15-13 16–1 GetCapabilities Request.......................................................................................................... 16-5 16–2 GetCapabilities Response ....................................................................................................... 16-6 16–3 DescribeRecord Request ......................................................................................................... 16-9 16–4 DescribeRecord Response....................................................................................................... 16-9 16–5 GetRecords Request............................................................................................................... 16-11 16–6 GetRecords Response ............................................................................................................ 16-12 16–7 GetDomain Request............................................................................................................... 16-12 16–8 GetDomain Response ............................................................................................................ 16-12 16–9 GetRecordById Request........................................................................................................ 16-13 16–10 GetRecordById Response ..................................................................................................... 16-13 16–11 Insert Request ......................................................................................................................... 16-13 16–12 Insert Response ...................................................................................................................... 16-14 xxii 16–13 Update Request ...................................................................................................................... 16-14 16–14 Update Response ................................................................................................................... 16-14 16–15 Delete Request........................................................................................................................ 16-14 16–16 Delete Response ..................................................................................................................... 16-15 C–1 Finding All Cities Within a Distance of a Highway ............................................................. C-2 C–2 Finding All Highways Within a Distance of a City .............................................................. C-2 C–3 Finding the Cities Nearest to a Highway ............................................................................... C-3 C–4 Finding the Cities Above a Specified Population Nearest to a Highway.......................... C-4 C–5 Aggregate Union with Groupings for Many Rows .............................................................. C-5 xxiii List of Figures 1–1 Geometric Types ......................................................................................................................... 1-4 1–2 Query Model................................................................................................................................ 1-8 1–3 MBR Enclosing a Geometry....................................................................................................... 1-9 1–4 R-Tree Hierarchical Index on MBRs...................................................................................... 1-10 1–5 The Nine-Intersection Model ................................................................................................. 1-11 1–6 Topological Relationships....................................................................................................... 1-12 1–7 Distance Buffers for Points, Lines, and Polygons................................................................ 1-13 1–8 Tolerance in an Aggregate Union Operation....................................................................... 1-15 1–9 Frustum as Query Window for Spatial Objects................................................................... 1-19 1–10 Faces and Textures................................................................................................................... 1-21 1–11 Texture Mapped to a Face ...................................................................................................... 1-21 2–1 Areas of Interest for the Simple Example................................................................................ 2-2 2–2 Storage of TIN Data ................................................................................................................. 2-16 2–3 Rectangle ................................................................................................................................... 2-20 2–4 Polygon with a Hole................................................................................................................ 2-21 2–5 Compound Line String............................................................................................................ 2-23 2–6 Compound Polygon ................................................................................................................ 2-24 2–7 Point-Only Geometry .............................................................................................................. 2-26 2–8 Oriented Point Geometry........................................................................................................ 2-28 2–9 Geometry with Type 0 (Zero) Element................................................................................. 2-30 5–1 Geometries with MBRs .............................................................................................................. 5-7 5–2 Layer with a Query Window .................................................................................................... 5-8 7–1 Geometric Segment..................................................................................................................... 7-2 7–2 Describing a Point Along a Segment with a Measure and an Offset .................................. 7-3 7–3 Measures, Distances, and Their Mapping Relationship........................................................ 7-4 7–4 Measure Populating of a Geometric Segment ........................................................................ 7-4 7–5 Measure Populating with Disproportional Assigned Measures ......................................... 7-4 7–6 Linear Feature, Geometric Segments, and LRS Points .......................................................... 7-5 7–7 Creating a Geometric Segment ................................................................................................. 7-6 7–8 Defining a Geometric Segment ................................................................................................. 7-8 7–9 Redefining a Geometric Segment ............................................................................................. 7-9 7–10 Clipping, Splitting, and Concatenating Geometric Segments.............................................. 7-9 7–11 Measure Assignment in Geometric Segment Operations.................................................. 7-10 7–12 Segment Direction with Concatenation................................................................................ 7-11 7–13 Scaling a Geometric Segment................................................................................................. 7-11 7–14 Offsetting a Geometric Segment............................................................................................ 7-12 7–15 Locating a Point Along a Segment with a Measure and an Offset ................................... 7-12 7–16 Ambiguity in Location Referencing with Offsets................................................................ 7-13 7–17 Multiple Projection Points ...................................................................................................... 7-13 7–18 Conversion from Standard to LRS Line String.................................................................... 7-14 7–19 Segment for Clip Operation Affected by Tolerance............................................................ 7-15 7–20 Simplified LRS Example: Highway....................................................................................... 7-16 8–1 Spatial Mining and Oracle Data Mining.................................................................................. 8-2 11–1 Basic Flow of Action with the Spatial Geocoding Service ............................................... 11-30 13–1 Basic Flow of Action with the Spatial Routing Engine....................................................... 13-1 15–1 Web Feature Service Architecture ......................................................................................... 15-2 16–1 CSW Architecture .................................................................................................................... 16-2 24–1 Arc Tolerance.......................................................................................................................... 24-10 24–2 SDO_GEOM.SDO_DIFFERENCE ....................................................................................... 24-27 24–3 SDO_GEOM.SDO_INTERSECTION .................................................................................. 24-31 24–4 SDO_GEOM.SDO_UNION .................................................................................................. 24-44 24–5 SDO_GEOM.SDO_XOR........................................................................................................ 24-48 25–1 Translating a Geometric Segment ....................................................................................... 25-80 32–1 Simplification of a Geometry ............................................................................................... 32-56 xxiv List of Tables 1–1 SDO_GEOMETRY Attributes for Three-Dimensional Geometries................................. 1-15 1–2 Predefined User Accounts Created by Spatial.................................................................... 1-25 2–1 Valid SDO_GTYPE Values ....................................................................................................... 2-6 2–2 Values and Semantics in SDO_ELEM_INFO......................................................................... 2-9 2–3 SDO_GEOMETRY Methods.................................................................................................. 2-12 2–4 SDO_TIN Type Attributes..................................................................................................... 2-15 2–5 Columns in the TIN Block Table........................................................................................... 2-16 2–6 SDO_PC Type Attributes....................................................................................................... 2-18 2–7 Columns in the Point Cloud Block Table ............................................................................ 2-19 2–8 Columns in the xxx_SDO_INDEX_INFO Views................................................................ 2-46 2–9 Columns in the xxx_SDO_INDEX_METADATA Views .................................................. 2-47 2–10 Columns in an R-Tree Spatial Index Data Table ................................................................ 2-49 2–11 SDO_UNITS_OF_MEASURE Table Entries for User-Defined Unit................................ 2-50 3–1 Columns in the Annotation Text Metadata Views................................................................ 3-9 5–1 Data and Index Dimensionality, and Query Support........................................................ 5-13 6–1 SDO_COORD_AXES Table ................................................................................................... 6-18 6–2 SDO_COORD_AXIS_NAMES Table.................................................................................... 6-18 6–3 SDO_COORD_OP_METHODS Table.................................................................................. 6-19 6–4 SDO_COORD_OP_PARAM_USE Table ............................................................................. 6-19 6–5 SDO_COORD_OP_PARAM_VALS Table .......................................................................... 6-20 6–6 SDO_COORD_OP_PARAMS Table..................................................................................... 6-21 6–7 SDO_COORD_OP_PATHS Table......................................................................................... 6-21 6–8 SDO_COORD_OPS Table...................................................................................................... 6-21 6–9 SDO_COORD_REF_SYS Table ............................................................................................. 6-23 6–10 SDO_COORD_SYS Table....................................................................................................... 6-25 6–11 SDO_CRS_COMPOUND View ............................................................................................ 6-25 6–12 SDO_CRS_ENGINEERING View ........................................................................................ 6-26 6–13 SDO_CRS_GEOCENTRIC View........................................................................................... 6-26 6–14 SDO_CRS_GEOGRAPHIC2D View..................................................................................... 6-27 6–15 SDO_CRS_GEOGRAPHIC3D View..................................................................................... 6-27 6–16 SDO_CRS_PROJECTED View .............................................................................................. 6-28 6–17 SDO_CRS_VERTICAL View................................................................................................. 6-28 6–18 SDO_DATUM_ENGINEERING View ................................................................................ 6-29 6–19 SDO_DATUM_GEODETIC View ........................................................................................ 6-29 6–20 SDO_DATUM_VERTICAL View ......................................................................................... 6-30 6–21 SDO_DATUMS Table............................................................................................................. 6-31 6–22 SDO_ELLIPSOIDS Table........................................................................................................ 6-32 6–23 SDO_PREFERRED_OPS_SYSTEM Table ............................................................................ 6-33 6–24 SDO_PREFERRED_OPS_USER Table ................................................................................. 6-33 6–25 SDO_PRIME_MERIDIANS Table ........................................................................................ 6-34 6–26 SDO_UNITS_OF_MEASURE Table..................................................................................... 6-34 6–27 EPSG Table Names and Oracle Spatial Names .................................................................. 6-35 6–28 MDSYS.CS_SRS Table ............................................................................................................ 6-40 6–29 MDSYS.SDO_ANGLE_UNITS View ................................................................................... 6-44 6–30 SDO_AREA_UNITS View ..................................................................................................... 6-44 6–31 MDSYS.SDO_DATUMS_OLD_FORMAT and SDO_DATUMS_OLD_SNAPSHOT Tables.. 6-45 6–32 MDSYS.SDO_DIST_UNITS View......................................................................................... 6-47 6–33 MDSYS.SDO_ELLIPSOIDS_OLD_FORMAT and SDO_ELLIPSOIDS_OLD_SNAPSHOT Tables 6-47 6–34 MDSYS.SDO_PROJECTIONS_OLD_FORMAT and SDO_PROJECTIONS_OLD_ SNAPSHOT Tables 6-49 7–1 Highway Features and LRS Counterparts .......................................................................... 7-16 xxv 11–1 Attributes for Formal Address Representation .................................................................. 11-1 11–2 Match Modes for Geocoding Operations ............................................................................ 11-2 11–3 Match Codes for Geocoding Operations ............................................................................. 11-3 11–4 Geocoded Address Error Message Interpretation ............................................................. 11-4 11–5 Geocoded Address Match Vector Interpretation ............................................................... 11-5 11–6 SDO_GEO_ADDR Type Attributes...................................................................................... 11-6 11–7 GC_ADDRESS_POINT_ Table............................................................................. 11-11 11–8 GC_AREA_ Table................................................................................................... 11-12 11–9 GC_COUNTRY_PROFILE Table........................................................................................ 11-14 11–10 GC_INTERSECTION_ Table ................................................................................ 11-16 11–11 GC_PARSER_PROFILES Table........................................................................................... 11-16 11–12 GC_PARSER_PROFILEAFS Table ..................................................................................... 11-19 11–13 GC_POI_ Table ....................................................................................................... 11-22 11–14 GC_POSTAL_CODE_ Table................................................................................. 11-23 11–15 GC_ROAD_ Table.................................................................................................. 11-24 11–16 GC_ROAD_SEGMENT_ Table ............................................................................ 11-27 12–1 OPENLS_DIR_BUSINESSES Table ...................................................................................... 12-2 12–2 OPENLS_DIR_BUSINESS_CHAINS Table......................................................................... 12-3 12–3 OPENLS_DIR_CATEGORIES Table .................................................................................... 12-3 12–4 OPENLS_DIR_CATEGORIZATIONS Table....................................................................... 12-4 12–5 OPENLS_DIR_CATEGORY_TYPES Table ......................................................................... 12-4 12–6 OPENLS_DIR_SYNONYMS Table....................................................................................... 12-5 13–1 EDGE Table............................................................................................................................ 13-21 13–2 NODE Table........................................................................................................................... 13-22 13–3 PARTITION Table ................................................................................................................ 13-22 13–4 SIGN_POST Table................................................................................................................. 13-23 14–1 Spatial OpenLS Services Dependencies............................................................................... 14-1 18–1 Spatial Index Creation and Usage Statements.................................................................... 18-1 19–1 Main Spatial Operators .......................................................................................................... 19-1 19–2 Convenience Operators for SDO_RELATE Operations.................................................... 19-1 19–3 params Keywords for the SDO_JOIN Operator............................................................... 19-19 19–4 Keywords for the SDO_NN Param Parameter................................................................. 19-23 20–1 Spatial Aggregate Functions ................................................................................................. 20-1 21–1 Subprograms for Coordinate System Transformation ...................................................... 21-1 21–2 Table to Hold Transformed Layer...................................................................................... 21-45 22–1 Subprograms for CSW Processing Operations................................................................... 22-1 23–1 Subprograms for Geocoding Address Data........................................................................ 23-1 24–1 Geometry Subprograms......................................................................................................... 24-1 25–1 Subprograms for Creating and Editing Geometric Segments.......................................... 25-1 25–2 Subprograms for Querying and Validating Geometric Segments................................... 25-2 25–3 Subprograms for Converting Geometric Segments........................................................... 25-3 27–1 Subprograms for OpenLS Support....................................................................................... 27-1 28–1 Point Cloud Subprograms ..................................................................................................... 28-1 29–1 Subprograms for Spatial Analysis and Mining .................................................................. 29-1 30–1 TIN Subprograms ................................................................................................................... 30-1 31–1 Tuning Subprograms.............................................................................................................. 31-1 32–1 Spatial Utility Subprograms.................................................................................................. 32-1 33–1 Subprograms for WFS Support............................................................................................. 33-1 34–1 Subprograms for WFS Processing Operations ................................................................... 34-1 B–1 Spatial-Related Features Supported for Locator .................................................................. B-2 B–2 Spatial Features Not Supported for Locator ......................................................................... B-3 B–3 Feature Availability with Standard or Enterprise Edition.................................................. B-4 xxvi xxvii Preface Oracle Spatial Developer's Guide provides usage and reference information for indexing and storing spatial data and for developing spatial applications using Oracle Spatial and Oracle Locator. Oracle Spatial requires the Enterprise Edition of Oracle Database 11g. It is a foundation for the deployment of enterprise-wide spatial information systems, and Web-based and wireless location-based applications requiring complex spatial data management. Oracle Locator is a feature of the Standard and Enterprise Editions of Oracle Database 11g. It offers a subset of Oracle Spatial capabilities (see Appendix B for a list of Locator features) typically required to support Internet and wireless service applications and partner-based geographic information system (GIS) solutions. The Standard and Enterprise Editions of Oracle Database 11g have the same basic features. However, several advanced features, such as extended data types, are available only with the Enterprise Edition, and some of these features are optional. For example, to use Oracle Database 11g table partitioning, you must have the Enterprise Edition and the Partitioning Option. For information about the differences between Oracle Database 11g Standard Edition and Oracle Database 11g Enterprise Edition and the features and options that are available to you, see Oracle Database New Features Guide. Audience This guide is intended for anyone who needs to store spatial data in an Oracle database. Documentation Accessibility Our goal is to make Oracle products, services, and supporting documentation accessible to all users, including users that are disabled. To that end, our documentation includes features that make information available to users of assistive technology. This documentation is available in HTML format, and contains markup to facilitate access by the disabled community. Accessibility standards will continue to evolve over time, and Oracle is actively engaged with other market-leading technology vendors to address technical obstacles so that our documentation can be accessible to all of our customers. For more information, visit the Oracle Accessibility Program Web site at http://www.oracle.com/accessibility/. Accessibility of Code Examples in Documentation Screen readers may not always correctly read the code examples in this document. The conventions for writing code require that closing braces should appear on an xxviii otherwise empty line; however, some screen readers may not always read a line of text that consists solely of a bracket or brace. Accessibility of Links to External Web Sites in Documentation This documentation may contain links to Web sites of other companies or organizations that Oracle does not own or control. Oracle neither evaluates nor makes any representations regarding the accessibility of these Web sites. Access to Oracle Support Oracle customers have access to electronic support through My Oracle Support. For information, visit http://www.oracle.com/support/contact.html or visit http://www.oracle.com/accessibility/support.html if you are hearing impaired. Related Documents For more information, see the following documents: ■ Oracle Spatial GeoRaster Developer's Guide ■ Oracle Spatial Topology and Network Data Models Developer's Guide ■ Oracle Database SQL Language Reference ■ Oracle Database Administrator's Guide ■ Oracle Database Advanced Application Developer's Guide ■ Oracle Database Error Messages - Spatial messages are in the range of 13000 to 13499. ■ Oracle Database Performance Tuning Guide ■ Oracle Database Utilities ■ Oracle Database Advanced Replication ■ Oracle Database Data Cartridge Developer's Guide Conventions The following text conventions are used in this document: Convention Meaning boldface Boldface type indicates graphical user interface elements associated with an action, or terms defined in text or the glossary. italic Italic type indicates book titles, emphasis, or placeholder variables for which you supply particular values. monospace Monospace type indicates commands within a paragraph, URLs, code in examples, text that appears on the screen, or text that you enter. xxix What’s New in Oracle Spatial? This section describes new and changed Oracle Spatial features for Oracle Database Release 11. Release 11.2 The following are new and changed features for Oracle Spatial 11g Release 2 (11.2). Index Maintenance Required Before and After Upgrade for WFS and CSW Data If you are using Spatial Web Feature Service (WFS) or Catalog Services for the Web (CSW) support, and if you have data from a previous release that was indexed using one or more SYS.XMLTABLEINDEX indexes, you must drop the associated indexes before the upgrade and re-create the indexes after the upgrade. For more information, see Section A.2. New Spatial Aggregate Function The following new spatial aggregate function has been added (spatial aggregate functions are documented in Chapter 20): ■ SDO_AGGR_SET_UNION New SDO_GEOM Subprograms The following new subprograms have been added to the SDO_GEOM package, which is documented in Chapter 24: ■ SDO_GEOM.SDO_ALPHA_SHAPE ■ SDO_GEOM.SDO_CONCAVEHULL ■ SDO_GEOM.SDO_CONCAVEHULL_BOUNDARY ■ SDO_GEOM.SDO_TRIANGULATE New SDO_UTIL Subprograms The following new subprograms have been added to the SDO_UTIL package, which is documented in Chapter 32: ■ SDO_UTIL.INTERIOR_POINT ■ SDO_UTIL.FROM_KMLGEOMETRY ■ SDO_UTIL.TO_KMLGEOMETRY xxx New SDO_WFS_LOCK Subprogram The following new subprogram has been added to the SDO_WFS_LOCK package, which is documented in Chapter 33: ■ SDO_WFS_LOCK.EnableDBTxns SDO_NN_DISTANCE Performance Improvement with FIRST_ROWS Hint The implementation of the SDO_NN_DISTANCE ancillary operator has been changed to provide improved performance when you specify the FIRST_ROWS optimizer hint. For an example of using the FIRST_ROWS hint, see the SDO_NN_DISTANCE reference section in Chapter 19. Support for Google Maps with Spatial Applications Support for Google Maps with Oracle Spatial applications has been enhanced. You can now specify a use case name of USE_SPHERICAL with the SDO_CS.TRANSFORM function or the SDO_CS.TRANSFORM_LAYER procedure, to have Spatial use spherical math (used by Google Maps) instead of ellipsoidal math in its projections. For more information, see Section 6.12, "Google Maps Considerations". Support for Workspace Manager with WFS You can perform database transactions and Oracle Workspace Manager workspace maintenance operations in the same session with WFS transactions (WFS-T). In the previous release, only WFS queries from one or more workspaces were supported. For information about using WFS with Workspace Manager, see Section 15.5. Cross-Endian Operations Supported for Transportable Tablespaces Containing Spatial Indexes For the SDO_UTIL.INITIALIZE_INDEXES_FOR_TTS procedure (documented in Chapter 32), transportable tablespaces containing spatial indexes are now supported across endian format platforms (big-endian to little-endian, or little-endian to big-endian). They were not supported in the previous release. Support for Very Large Geometries (More Than 1,048,576 Ordinates) A new script is available if you need to support geometries with more than 1,048,576 ordinates; however, using that script involves significant extra work, some database downtime, and some considerations and restrictions. For information, see Section A.3. SDO_UTIL.PREPARE_FOR_TTS Deprecated Effective with Oracle Database Release 11.2, the SDO_UTIL.PREPARE_FOR_TTS procedure is deprecated. You do not need to call that procedure before performing a transportable tablespace export operation. GC_ADDRESS_POINT Table The GC_ADDRESS_POINT_ table (for example, GC_ADDRESS_POINT_US) stores the actual longitude, latitude coordinates for addresses. It therefore enables the Spatial Geocoder to provide more accurate location results when it is used. The GC_ ADDRESS_POINT table is not required for geocoding; however, if this table exists, it is automatically used by the Geocoder for improved results. This table and its associated index are described in Section 11.5.1. xxxi Release 11.1 The following are new and changed features for Oracle Spatial 11g Release 1 (11.1). 3-D Geometry Support Oracle Spatial supports the creation and storage of three-dimensional geometry objects, as explained in Section 1.11. Enhanced Web Services Support: Business Directory, Web Feature Service, Catalog Services, and OpenLS Expanded support is provided for spatial Web services. A Web service enables developers of Oracle Spatial applications to provide feature data and metadata to their application users over the Web. Chapter 10 introduces the support for Web services and includes some overall requirements and considerations. The following chapters document new features that are supported through Web services: ■ Chapter 12, "Business Directory (Yellow Pages) Support" ■ Chapter 14, "OpenLS Support" ■ Chapter 15, "Web Feature Service (WFS) Support" ■ Chapter 16, "Catalog Services for the Web (CSW) Support" Routing Engine Enhancements The routing engine includes the following enhancements: ■ Per-maneuver times and geometries ■ Long ID support ■ Edge ID support at both the route level and segment level ■ Better generation of driving directions The routing engine is described in Chapter 13. SQL Multimedia Types Support for the SQL Multimedia spatial types (ST_xxx) has been enhanced. These types are specified in ISO 13249-3, Information technology - Database languages - SQL Multimedia and Application Packages - Part 3: Spatial. The Oracle Spatial support for these types is described in Chapter 3. Annotation Text Oracle Spatial now supports annotation text as specified in the OpenGIS Implementation Specification for Geographic information - Simple feature access - Part 1: Common architecture. This support is described in Section 3.4. DEFAULT Geocoding Match Mode Equivalent to RELAX_POSTAL_CODE The DEFAULT match mode for geocoding operations is now equivalent to the RELAX_POSTAL_CODE mode. In the previous release, it was equivalent to the RELAX_BASE_NAME mode. The match modes for geocoding operations are explained Section 11.1.2. New MatchVector Attribute for SDO_GEOR_ADDR MatchVector has been added as the last attribute for the SDO_GEO_ADDR object type. This attribute is a string that indicates how each address attribute has been xxxii matched against the data used for geocoding. The MatchVector attribute is listed in Table 11–6 and is explained more fully in Section 11.1.5. SDO_GEOM.CLOSEST_POINTS Procedure The new SDO_GEOM.SDO_CLOSEST_POINTS procedure (described in Chapter 24) computes the minimum distance between two geometries and the points (one on each geometry) that are the minimum distance apart. SDO_UTIL.BEARING_TILT_FOR_POINTS Procedure The new SDO_UTIL.BEARING_TILT_FOR_POINTS procedure (described in Chapter 32) computes the bearing and tilt from a start point to an end point. Filtering by Distance with the SDO_NN Operator You can use the distance keyword in the param parameter to the SDO_NN operator (described in Chapter 19) to limit the distance in the search for nearest neighbors (for example, 'distance=10 unit=mile'). Part I Part I Conceptual and Usage Information This document has the following parts: ■ Part I provides conceptual and usage information about Oracle Spatial. ■ Part II provides conceptual and usage information about Oracle Spatial Web services. ■ Part III provides reference information about Oracle Spatial operators, functions, and procedures. ■ Part IV provides supplementary information (appendixes and a glossary). Part I is organized for efficient learning about Oracle Spatial. It covers basic concepts and techniques first, and proceeds to more advanced material, such as coordinate systems, the linear referencing system, geocoding, and extending spatial indexing. Part I contains the following chapters: ■ Chapter 1, "Spatial Concepts" ■ Chapter 2, "Spatial Data Types and Metadata" ■ Chapter 3, "SQL Multimedia Type Support" ■ Chapter 4, "Loading Spatial Data" ■ Chapter 5, "Indexing and Querying Spatial Data" ■ Chapter 6, "Coordinate Systems (Spatial Reference Systems)" ■ Chapter 7, "Linear Referencing System" ■ Chapter 8, "Spatial Analysis and Mining" ■ Chapter 9, "Extending Spatial Indexing Capabilities" 1 Spatial Concepts 1-1 1 Spatial Concepts Oracle Spatial is an integrated set of functions and procedures that enables spatial data to be stored, accessed, and analyzed quickly and efficiently in an Oracle database. Spatial data represents the essential location characteristics of real or conceptual objects as those objects relate to the real or conceptual space in which they exist. This chapter contains the following major sections: ■ Section 1.1, "What Is Oracle Spatial?" ■ Section 1.2, "Object-Relational Model" ■ Section 1.3, "Introduction to Spatial Data" ■ Section 1.4, "Geometry Types" ■ Section 1.5, "Data Model" ■ Section 1.6, "Query Model" ■ Section 1.7, "Indexing of Spatial Data" ■ Section 1.8, "Spatial Relationships and Filtering" ■ Section 1.9, "Spatial Operators, Procedures, and Functions" ■ Section 1.10, "Spatial Aggregate Functions" ■ Section 1.11, "Three-Dimensional Spatial Objects" ■ Section 1.12, "Geocoding" ■ Section 1.13, "Spatial Java Application Programming Interface" ■ Section 1.14, "Predefined User Accounts Created by Spatial" ■ Section 1.15, "Performance and Tuning Information" ■ Section 1.16, "OGC and ISO Compliance" ■ Section 1.17, "Spatial Release (Version) Number" ■ Section 1.18, "Spatial Application Hardware Requirement Considerations" ■ Section 1.19, "Spatial Error Messages" ■ Section 1.20, "Spatial Examples" ■ Section 1.21, "README File for Spatial and Related Features" What Is Oracle Spatial? 1-2 Oracle Spatial Developer's Guide 1.1 What Is Oracle Spatial? Oracle Spatial, often referred to as Spatial, provides a SQL schema and functions that facilitate the storage, retrieval, update, and query of collections of spatial features in an Oracle database. Spatial consists of the following: ■ A schema (MDSYS) that prescribes the storage, syntax, and semantics of supported geometric data types ■ A spatial indexing mechanism ■ Operators, functions, and procedures for performing area-of-interest queries, spatial join queries, and other spatial analysis operations ■ Functions and procedures for utility and tuning operations ■ Topology data model for working with data about nodes, edges, and faces in a topology (described in Oracle Spatial Topology and Network Data Models Developer's Guide). ■ Network data model for representing capabilities or objects that are modeled as nodes and links in a network (described in Oracle Spatial Topology and Network Data Models Developer's Guide). ■ GeoRaster, a feature that lets you store, index, query, analyze, and deliver GeoRaster data, that is, raster image and gridded data and its associated metadata (described in Oracle Spatial GeoRaster Developer's Guide). The spatial component of a spatial feature is the geometric representation of its shape in some coordinate space. This is referred to as its geometry. 1.2 Object-Relational Model Spatial supports the object-relational model for representing geometries. This model stores an entire geometry in the Oracle native spatial data type for vector data, SDO_ GEOMETRY. An Oracle table can contain one or more SDO_GEOMETRY columns. The object-relational model corresponds to a "SQL with Geometry Types" implementation of spatial feature tables in the Open GIS ODBC/SQL specification for geospatial features. The benefits provided by the object-relational model include: ■ Support for many geometry types, including arcs, circles, compound polygons, compound line strings, and optimized rectangles ■ Ease of use in creating and maintaining indexes and in performing spatial queries ■ Index maintenance by the Oracle database ■ Geometries modeled in a single column ■ Optimal performance Caution: Do not modify any packages, tables, or other objects under the MDSYS schema. (The only exception is if you need to create a user-defined coordinate reference system, as explained in Section 6.9.) Geometry Types Spatial Concepts 1-3 1.3 Introduction to Spatial Data Oracle Spatial is designed to make spatial data management easier and more natural to users of location-enabled applications and geographic information system (GIS) applications. Once spatial data is stored in an Oracle database, it can be easily manipulated, retrieved, and related to all other data stored in the database. A common example of spatial data can be seen in a road map. A road map is a two-dimensional object that contains points, lines, and polygons that can represent cities, roads, and political boundaries such as states or provinces. A road map is a visualization of geographic information. The location of cities, roads, and political boundaries that exist on the surface of the Earth are projected onto a two-dimensional display or piece of paper, preserving the relative positions and relative distances of the rendered objects. The data that indicates the Earth location (such as longitude and latitude) of these rendered objects is the spatial data. When the map is rendered, this spatial data is used to project the locations of the objects on a two-dimensional piece of paper. A GIS is often used to store, retrieve, and render this Earth-relative spatial data. Types of spatial data (other than GIS data) that can be stored using Spatial include data from computer-aided design (CAD) and computer-aided manufacturing (CAM) systems. Instead of operating on objects on a geographic scale, CAD/CAM systems work on a smaller scale, such as for an automobile engine or printed circuit boards. The differences among these systems are in the size and precision of the data, not the data’s complexity. The systems might all involve the same number of data points. On a geographic scale, the location of a bridge can vary by a few tenths of an inch without causing any noticeable problems to the road builders, whereas if the diameter of an engine’s pistons is off by a few tenths of an inch, the engine will not run. In addition, the complexity of data is independent of the absolute scale of the area being represented. For example, a printed circuit board is likely to have many thousands of objects etched on its surface, containing in its small area information that may be more complex than the details shown on a road builder’s blueprints. These applications all store, retrieve, update, or query some collection of features that have both nonspatial and spatial attributes. Examples of nonspatial attributes are name, soil_type, landuse_classification, and part_number. The spatial attribute is a coordinate geometry, or vector-based representation of the shape of the feature. 1.4 Geometry Types A geometry is an ordered sequence of vertices that are connected by straight line segments or circular arcs. The semantics of the geometry are determined by its type. Spatial supports several primitive types, and geometries composed of collections of these types, including two-dimensional: ■ Points and point clusters ■ Line strings ■ n-point polygons ■ Arc line strings (All arcs are generated as circular arcs.) ■ Arc polygons ■ Compound polygons ■ Compound line strings Data Model 1-4 Oracle Spatial Developer's Guide ■ Circles ■ Optimized rectangles Two-dimensional points are elements composed of two ordinates, X and Y, often corresponding to longitude and latitude. Line strings are composed of one or more pairs of points that define line segments. Polygons are composed of connected line strings that form a closed ring, and the area of the polygon is implied. For example, a point might represent a building location, a line string might represent a road or flight path, and a polygon might represent a state, city, zoning district, or city block. Self-crossing polygons are not supported, although self-crossing line strings are supported. If a line string crosses itself, it does not become a polygon. A self-crossing line string does not have any implied area. Figure 1–1 illustrates the geometric types. Figure 1–1 Geometric Types Spatial also supports the storage and indexing of three-dimensional and four-dimensional geometric types, where three or four coordinates are used to define each vertex of the object being defined. For information about support for three-dimensional geometries, see Section 1.11. 1.5 Data Model The Spatial data model is a hierarchical structure consisting of elements, geometries, and layers. Layers are composed of geometries, which in turn are made up of elements. 1.5.1 Element An element is the basic building block of a geometry. The supported spatial element types are points, line strings, and polygons. For example, elements might model star constellations (point clusters), roads (line strings), and county boundaries (polygons). Each coordinate in an element is stored as an X,Y pair. The exterior ring and zero or more interior rings (holes) of a complex polygon are considered a single element. Point Line String Polygon Arc Line String Arc Polygon Compound Polygon Compound Line String Circle Rectangle Data Model Spatial Concepts 1-5 Point data consists of one coordinate. Line data consists of two coordinates representing a line segment of the element. Polygon data consists of coordinate pair values, one vertex pair for each line segment of the polygon. Coordinates are defined in order around the polygon (counterclockwise for an exterior polygon ring, clockwise for an interior polygon ring). 1.5.2 Geometry A geometry (or geometry object) is the representation of a spatial feature, modeled as an ordered set of primitive elements. A geometry can consist of a single element, which is an instance of one of the supported primitive types, or a homogeneous or heterogeneous collection of elements. A multipolygon, such as one used to represent a set of islands, is a homogeneous collection. A heterogeneous collection is one in which the elements are of different types, for example, a point and a polygon. An example of a geometry might describe the buildable land in a town. This could be represented as a polygon with holes where water or zoning prevents construction. 1.5.3 Layer A layer is a collection of geometries having the same attribute set. For example, one layer in a GIS might include topographical features, while another describes population density, and a third describes the network of roads and bridges in the area (lines and points). The geometries and associated spatial index for each layer are stored in the database in standard tables. 1.5.4 Coordinate System A coordinate system (also called a spatial reference system) is a means of assigning coordinates to a location and establishing relationships between sets of such coordinates. It enables the interpretation of a set of coordinates as a representation of a position in a real world space. Any spatial data has a coordinate system associated with it. The coordinate system can be georeferenced (related to a specific representation of the Earth) or not georeferenced (that is, Cartesian, and not related to a specific representation of the Earth). If the coordinate system is georeferenced, it has a default unit of measurement (such as meters) associated with it, but you can have Spatial automatically return results in another specified unit (such as miles). (For more information about unit of measurement support, see Section 2.10.) Spatial data can be associated with a Cartesian, geodetic (geographical), projected, or local coordinate system: ■ Cartesian coordinates are coordinates that measure the position of a point from a defined origin along axes that are perpendicular in the represented two-dimensional or three-dimensional space. If a coordinate system is not explicitly associated with a geometry, a Cartesian coordinate system is assumed. ■ Geodetic coordinates (sometimes called geographic coordinates) are angular coordinates (longitude and latitude), closely related to spherical polar coordinates, and are defined relative to a particular Earth geodetic datum. (A geodetic datum is a means of representing the figure of the Earth and is the reference for the system of geodetic coordinates.) ■ Projected coordinates are planar Cartesian coordinates that result from performing a mathematical mapping from a point on the Earth’s surface to a Data Model 1-6 Oracle Spatial Developer's Guide plane. There are many such mathematical mappings, each used for a particular purpose. ■ Local coordinates are Cartesian coordinates in a non-Earth (non-georeferenced) coordinate system. Local coordinate systems are often used for CAD applications and local surveys. When performing operations on geometries, Spatial uses either a Cartesian or curvilinear computational model, as appropriate for the coordinate system associated with the spatial data. For more information about coordinate system support in Spatial, including geodetic, projected, and local coordinates and coordinate system transformation, see Chapter 6. 1.5.5 Tolerance Tolerance is used to associate a level of precision with spatial data. Tolerance reflects the distance that two points can be apart and still be considered the same (for example, to accommodate rounding errors). The tolerance value must be a positive number greater than zero. The significance of the value depends on whether or not the spatial data is associated with a geodetic coordinate system. (Geodetic and other types of coordinate systems are described in Section 1.5.4.) ■ For geodetic data (such as data identified by longitude and latitude coordinates), the tolerance value is a number of meters. For example, a tolerance value of 100 indicates a tolerance of 100 meters. The tolerance value for geodetic data should not be smaller than 0.05 (5 centimeters), and in most cases it should be larger. Spatial uses 0.05 as the tolerance value for geodetic data if you specify a smaller value with the following functions: SDO_GEOM.RELATE, SDO_GEOM.SDO_ DIFFERENCE, SDO_GEOM.SDO_INTERSECTION, SDO_GEOM.SDO_UNION, and SDO_GEOM.SDO_XOR; for other functions, Spatial uses the smaller tolerance value that you specify. ■ For non-geodetic data, the tolerance value is a number of the units that are associated with the coordinate system associated with the data. For example, if the unit of measurement is miles, a tolerance value of 0.005 indicates a tolerance of 0.005 (that is, 1/200) mile (approximately 26 feet or 7.9 meters), and a tolerance value of 2 indicates a tolerance of 2 miles. In both cases, the smaller the tolerance value, the more precision is to be associated with the data. For geometries that have 16 or more digits of precision, Spatial boolean operations (such as SDO_GEOM.SDO_UNION and SDO_GEOM.SDO_INTERSECTION) and the SDO_GEOM.RELATE function might produce inconsistent results due to the loss of precision in floating point arithmetic. The number of digits of precision is calculated as in the following example: if the tolerance is set to 0.0000000005 and the coordinates have 6 digits to the left of decimal (for example, 123456.4321), the precision is 10 + 6 digits (16). In such cases, it is better to use a larger tolerance value (fewer leading zeros after the decimal) to get consistent results using Spatial operations. A tolerance value is specified in two cases: ■ In the geometry metadata definition for a layer (see Section 1.5.5.1) ■ As an input parameter to certain functions (see Section 1.5.5.2) For additional information about tolerance with linear referencing system (LRS) data, see Section 7.6. Data Model Spatial Concepts 1-7 1.5.5.1 Tolerance in the Geometry Metadata for a Layer The dimensional information for a layer includes a tolerance value. Specifically, the DIMINFO column (described in Section 2.8.3) of the xxx_SDO_GEOM_METADATA views includes an SDO_TOLERANCE value for each dimension, and the value should be the same for each dimension. If a function accepts an optional tolerance parameter and this parameter is null or not specified, the SDO_TOLERANCE value of the layer is used. Using the non-geodetic data from the example in Section 2.1, the actual distance between geometries cola_b and cola_d is 0.846049894. If a query uses the SDO_GEOM.SDO_ DISTANCE function to return the distance between cola_b and cola_d and does not specify a tolerance parameter value, the result depends on the SDO_TOLERANCE value of the layer. For example: ■ If the SDO_TOLERANCE value of the layer is 0.005, this query returns .846049894. ■ If the SDO_TOLERANCE value of the layer is 0.5, this query returns 0. The zero result occurs because Spatial first constructs an imaginary buffer of the tolerance value (0.5) around each geometry to be considered, and the buffers around cola_b and cola_d overlap in this case. You can, therefore, take either of two approaches in selecting an SDO_TOLERANCE value for a layer: ■ The value can reflect the desired level of precision in queries for distances between objects. For example, if two non-geodetic geometries 0.8 units apart should be considered as separated, specify a small SDO_TOLERANCE value such as 0.05 or smaller. ■ The value can reflect the precision of the values associated with geometries in the layer. For example, if all geometries in a non-geodetic layer are defined using integers and if two objects 0.8 units apart should not be considered as separated, an SDO_TOLERANCE value of 0.5 is appropriate. To have greater precision in any query, you must override the default by specifying the tolerance parameter. With non-geodetic data, the guideline to follow for most instances of the second case (precision of the values of the geometries in the layer) is: take the highest level of precision in the geometry definitions, and use .5 at the next level as the SDO_ TOLERANCE value. For example, if geometries are defined using integers (as in the simplified example in Section 2.1), the appropriate value is 0.5; however, if geometries are defined using numbers up to four decimal positions (for example, 31.2587), the appropriate value is 0.00005. Note: This guideline should not be used if the geometries include any polygons that are so narrow at any point that the distance between facing sides is less than the proposed tolerance value. Be sure that the tolerance value is less than the shortest distance between any two sides in any polygon. Moreover, if you encounter "invalid geometry" errors with inserted or updated geometries, and if the geometries are in fact valid, consider increasing the precision of the tolerance value (for example, changing 0.00005 to 0.000005). Query Model 1-8 Oracle Spatial Developer's Guide 1.5.5.2 Tolerance as an Input Parameter Many Spatial functions accept a tolerance parameter, which (if specified) overrides the default tolerance value for the layer (explained in Section 1.5.5.1). If the distance between two points is less than or equal to the tolerance value, Spatial considers the two points to be a single point. Thus, tolerance is usually a reflection of how accurate or precise users perceive their spatial data to be. For example, assume that you want to know which restaurants are within 5 kilometers of your house. Assume also that Maria’s Pizzeria is 5.1 kilometers from your house. If the spatial data has a geodetic coordinate system and if you ask, Find all restaurants within 5 kilometers and use a tolerance of 100 (or greater, such as 500), Maria’s Pizzeria will be included, because 5.1 kilometers (5100 meters) is within 100 meters of 5 kilometers (5000 meters). However, if you specify a tolerance less than 100 (such as 50), Maria’s Pizzeria will not be included. Tolerance values for Spatial functions are typically very small, although the best value in each case depends on the kinds of applications that use or will use the data. See also the tolerance guidelines in Section 1.5.5.1, and ensure that all input geometries are valid. (Spatial functions may not work as expected if the geometry data is not valid.) 1.6 Query Model Spatial uses a two-tier query model to resolve spatial queries and spatial joins. The term is used to indicate that two distinct operations are performed to resolve queries. The output of the two combined operations yields the exact result set. The two operations are referred to as primary and secondary filter operations. ■ The primary filter permits fast selection of candidate records to pass along to the secondary filter. The primary filter compares geometry approximations to reduce computation complexity and is considered a lower-cost filter. Because the primary filter compares geometric approximations, it returns a superset of the exact result set. ■ The secondary filter applies exact computations to geometries that result from the primary filter. The secondary filter yields an accurate answer to a spatial query. The secondary filter operation is computationally expensive, but it is only applied to the primary filter results, not the entire data set. Figure 1–2 illustrates the relationship between the primary and secondary filters. Figure 1–2 Query Model As shown in Figure 1–2, the primary filter operation on a large input data set produces a smaller candidate set, which contains at least the exact result set and may contain more records. The secondary filter operation on the smaller candidate set produces the exact result set. Large Input Data Set Primary Filter Secondary Filter Smaller Candidate Set Exact Result Set Indexing of Spatial Data Spatial Concepts 1-9 Spatial uses a spatial index to implement the primary filter. Spatial does not require the use of both the primary and secondary filters. In some cases, just using the primary filter is sufficient. For example, a zoom feature in a mapping application queries for data that has any interaction with a rectangle representing visible boundaries. The primary filter very quickly returns a superset of the query. The mapping application can then apply clipping routines to display the target area. The purpose of the primary filter is to quickly create a subset of the data and reduce the processing burden on the secondary filter. The primary filter, therefore, should be as efficient (that is, selective yet fast) as possible. This is determined by the characteristics of the spatial index on the data. For more information about querying spatial data, see Section 5.2. 1.7 Indexing of Spatial Data The introduction of spatial indexing capabilities into the Oracle database engine is a key feature of the Spatial product. A spatial index, like any other index, provides a mechanism to limit searches, but in this case the mechanism is based on spatial criteria such as intersection and containment. A spatial index is needed to: ■ Find objects within an indexed data space that interact with a given point or area of interest (window query) ■ Find pairs of objects from within two indexed data spaces that interact spatially with each other (spatial join) Testing of spatial indexes with many workloads and operators is ongoing, and results and recommendations will be documented as they become available. The following sections explain the concepts and options associated with R-tree indexing. 1.7.1 R-Tree Indexing A spatial R-tree index can index spatial data of up to four dimensions. An R-tree index approximates each geometry by a single rectangle that minimally encloses the geometry (called the minimum bounding rectangle, or MBR), as shown in Figure 1–3. Figure 1–3 MBR Enclosing a Geometry For a layer of geometries, an R-tree index consists of a hierarchical index on the MBRs of the geometries in the layer, as shown in Figure 1–4. MBR Geometry Indexing of Spatial Data 1-10 Oracle Spatial Developer's Guide Figure 1–4 R-Tree Hierarchical Index on MBRs In Figure 1–4: ■ 1 through 9 are geometries in a layer. ■ a, b, c, and d are the leaf nodes of the R-tree index, and contain minimum bounding rectangles of geometries, along with pointers to the geometries. For example, a contains the MBR of geometries 1 and 2, b contains the MBR of geometries 3 and 4, and so on. ■ A contains the MBR of a and b, and B contains the MBR of c and d. ■ The root contains the MBR of A and B (that is, the entire area shown). An R-tree index is stored in the spatial index table (SDO_INDEX_TABLE in the USER_ SDO_INDEX_METADATA view, described in Section 2.9). The R-tree index also maintains a sequence object (SDO_RTREE_SEQ_NAME in the USER_SDO_INDEX_ METADATA view) to ensure that simultaneous updates by concurrent users can be made to the index. 1.7.2 R-Tree Quality A substantial number of insert and delete operations affecting an R-tree index may degrade the quality of the R-tree structure, which may adversely affect query performance. The R-tree is a hierarchical tree structure with nodes at different heights of the tree. The performance of an R-tree index structure for queries is roughly proportional to the area and perimeter of the index nodes of the R-tree. The area covered at level 0 represents the area occupied by the minimum bounding rectangles of the data geometries, the area at level 1 indicates the area covered by leaf-level R-tree nodes, and so on. The original ratio of the area at the root (topmost level) to the area at level 0 can change over time based on updates to the table; and if there is a degradation in that ratio (that is, if it increases significantly), rebuilding the index may help the performance of queries. If the performance of SDO_FILTER operations has degraded, and if there have been a large number of insert, update, or delete operations affecting geometries, the performance degradation may be due to a degradation in the quality of the associated R-tree index. You can check for degradation of index quality by using the SDO_ TUNE.QUALITY_DEGRADATION function (described in Chapter 31); and if the function returns a number greater than 2, consider rebuilding the index. Note, however, that the R-tree index quality degradation number may not be significant in terms of overall query performance due to Oracle caching strategies and other significant Oracle capabilities, such as table pinning, which can essentially remove I/O overhead from R-tree index queries. To rebuild an R-tree index, use the ALTER INDEX REBUILD statement, which is described in Chapter 18. 1 2 3 4 56 7 8 9 a b c d A B R-tree root AB abcd root Spatial Relationships and Filtering Spatial Concepts 1-11 1.8 Spatial Relationships and Filtering Spatial uses secondary filters to determine the spatial relationship between entities in the database. The spatial relationship is based on geometry locations. The most common spatial relationships are based on topology and distance. For example, the boundary of an area consists of a set of curves that separates the area from the rest of the coordinate space. The interior of an area consists of all points in the area that are not on its boundary. Given this, two areas are said to be adjacent if they share part of a boundary but do not share any points in their interior. The distance between two spatial objects is the minimum distance between any points in them. Two objects are said to be within a given distance of one another if their distance is less than the given distance. To determine spatial relationships, Spatial has several secondary filter methods: ■ The SDO_RELATE operator evaluates topological criteria. ■ The SDO_WITHIN_DISTANCE operator determines if two spatial objects are within a specified distance of each other. ■ The SDO_NN operator identifies the nearest neighbors for a spatial object. The syntax of these operators is given in Chapter 19. The SDO_RELATE operator implements a nine-intersection model for categorizing binary topological relationships between points, lines, and polygons. Each spatial object has an interior, a boundary, and an exterior. The boundary consists of points or lines that separate the interior from the exterior. The boundary of a line string consists of its end points; however, if the end points overlap (that is, if they are the same point), the line string has no boundary. The boundaries of a multiline string are the end points of each of the component line strings; however, if the end points overlap, only the end points that overlap an odd number of times are boundaries. The boundary of a polygon is the line that describes its perimeter. The interior consists of points that are in the object but not on its boundary, and the exterior consists of those points that are not in the object. Given that an object A has three components (a boundary Ab, an interior Ai, and an exterior Ae), any pair of objects has nine possible interactions between their components. Pairs of components have an empty (0) or not empty (1) set intersection. The set of interactions between two geometries is represented by a nine-intersection matrix that specifies which pairs of components intersect and which do not. Figure 1–5 shows the nine-intersection matrix for two polygons that are adjacent to one another. This matrix yields the following bit mask, generated in row-major form: "101001111". Figure 1–5 The Nine-Intersection Model A B B bie A 01b i e 00 1 1 111 A TOUCH B 9-Intersection Matrix Spatial Relationships and Filtering 1-12 Oracle Spatial Developer's Guide Some of the topological relationships identified in the seminal work by Professor Max Egenhofer (University of Maine, Orono) and colleagues have names associated with them. Spatial uses the following names: ■ DISJOINT: The boundaries and interiors do not intersect. ■ TOUCH: The boundaries intersect but the interiors do not intersect. ■ OVERLAPBDYDISJOINT: The interior of one object intersects the boundary and interior of the other object, but the two boundaries do not intersect. This relationship occurs, for example, when a line originates outside a polygon and ends inside that polygon. ■ OVERLAPBDYINTERSECT: The boundaries and interiors of the two objects intersect. ■ EQUAL: The two objects have the same boundary and interior. ■ CONTAINS: The interior and boundary of one object is completely contained in the interior of the other object. ■ COVERS: The interior of one object is completely contained in the interior or the boundary of the other object and their boundaries intersect. ■ INSIDE: The opposite of CONTAINS. A INSIDE B implies B CONTAINS A. ■ COVEREDBY: The opposite of COVERS. A COVEREDBY B implies B COVERS A. ■ ON: The interior and boundary of one object is on the boundary of the other object (and the second object covers the first object). This relationship occurs, for example, when a line is on the boundary of a polygon. ■ ANYINTERACT: The objects are non-disjoint. Figure 1–6 illustrates these topological relationships. Figure 1–6 Topological Relationships The SDO_WITHIN_DISTANCE operator determines if two spatial objects, A and B, are within a specified distance of one another. This operator first constructs a distance buffer, Db, around the reference object B. It then checks that A and Db are non-disjoint. The distance buffer of an object consists of all points within the given distance from that object. Figure 1–7 shows the distance buffers for a point, a line, and a polygon. A B A AA A A A B B B B B B A CONTAINS B A EQUAL B B INSIDE A B COVEREDBY A A COVERS B (2 polygons with identical coordinates) A TOUCH B A OVERLAPBDYINTERSECT B A DISJOINT B B TOUCH A A OVERLAPBDYDISJOINT B B OVERLAPBDYINTERSECT A B OVERLAPBDYDISJOINT A B DISJOINT AB EQUAL A A B B ON A A COVERS B Spatial Operators, Procedures, and Functions Spatial Concepts 1-13 Figure 1–7 Distance Buffers for Points, Lines, and Polygons In the point, line, and polygon geometries shown in Figure 1–7: ■ The dashed lines represent distance buffers. Notice how the buffer is rounded near the corners of the objects. ■ The geometry on the right is a polygon with a hole: the large rectangle is the exterior polygon ring and the small rectangle is the interior polygon ring (the hole). The dashed line outside the large rectangle is the buffer for the exterior ring, and the dashed line inside the small rectangle is the buffer for the interior ring. The SDO_NN operator returns a specified number of objects from a geometry column that are closest to a specified geometry (for example, the five closest restaurants to a city park). In determining how close two geometry objects are, the shortest possible distance between any two points on the surface of each object is used. 1.9 Spatial Operators, Procedures, and Functions The Spatial PL/SQL application programming interface (API) includes several operators and many procedures and functions. Spatial operators, such as SDO_FILTER and SDO_RELATE, provide optimum performance because they use the spatial index. (Spatial operators require that the geometry column in the first parameter have a spatial index defined on it.) Spatial operators must be used in the WHERE clause of a query. The first parameter of any operator specifies the geometry column to be searched, and the second parameter specifies a query window. If the query window does not have the same coordinate system as the geometry column, Spatial performs an implicit coordinate system transformation. For detailed information about the spatial operators, see Chapter 19. Spatial procedures and functions are provided as subprograms in PL/SQL packages, such as SDO_GEOM, SDO_CS, and SDO_LRS. These subprograms do not require that a spatial index be defined, and they do not use a spatial index if it is defined. These subprograms can be used in the WHERE clause or in a subquery. If two geometries are input parameters to a Spatial procedure or function, both must have the same coordinate system. The following performance-related guidelines apply to the use of spatial operators, procedures, and functions: ■ If an operator and a procedure or function perform comparable operations, and if the operator satisfies your requirements, use the operator. For example, unless you need to do otherwise, use SDO_RELATE instead of SDO_GEOM.RELATE, and use SDO_WITHIN_DISTANCE instead of SDO_GEOM.WITHIN_DISTANCE. ■ With operators, always specify TRUE in uppercase. That is, specify = 'TRUE', and do not specify <> 'FALSE' or = 'true'. ■ With operators, use the /*+ ORDERED */ optimizer hint if the query window comes from a table. (You must use this hint if multiple windows come from a Spatial Aggregate Functions 1-14 Oracle Spatial Developer's Guide table.) See the Usage Notes and Examples for specific operators for more information. For information about using operators with topologies, see Oracle Spatial Topology and Network Data Models Developer's Guide. 1.10 Spatial Aggregate Functions SQL has long had aggregate functions, which are used to aggregate the results of a SQL query. The following example uses the SUM aggregate function to aggregate employee salaries by department: SELECT SUM(salary), dept FROM employees GROUP BY dept; Oracle Spatial aggregate functions aggregate the results of SQL queries involving geometry objects. Spatial aggregate functions return a geometry object of type SDO_ GEOMETRY. For example, the following statement returns the minimum bounding rectangle of all geometries in a table (using the definitions and data from Section 2.1): SELECT SDO_AGGR_MBR(shape) FROM cola_markets; The following example returns the union of all geometries except cola_d: SELECT SDO_AGGR_UNION(SDOAGGRTYPE(c.shape, 0.005)) FROM cola_markets c WHERE c.name <> 'cola_d'; For reference information about the spatial aggregate functions and examples of their use, see Chapter 20. 1.10.1 SDOAGGRTYPE Object Type Many spatial aggregate functions accept an input parameter of type SDOAGGRTYPE. Oracle Spatial defines the object type SDOAGGRTYPE as: CREATE TYPE sdoaggrtype AS OBJECT ( geometry SDO_GEOMETRY, tolerance NUMBER); The tolerance value in the SDOAGGRTYPE definition should be the same as the SDO_TOLERANCE value specified in the DIMINFO column in the xxx_SDO_GEOM_ METADATA views for the geometries, unless you have a specific reason for wanting a different value. For more information about tolerance, see Section 1.5.5; for information about the xxx_SDO_GEOM_METADATA views, see Section 2.8. The tolerance value in the SDOAGGRTYPE definition can affect the result of a spatial aggregate function. Figure 1–8 shows a spatial aggregate union (SDO_AGGR_ UNION) operation of two geometries using two different tolerance values: one smaller and one larger than the distance between the geometries. Note: Spatial aggregate functions are supported for two-dimensional geometries only, except for SDO_AGGR_MBR, which is supported for both two-dimensional and three-dimensional geometries. Note: Do not use SDOAGGRTYPE as the data type for a column in a table. Use this type only in calls to spatial aggregate functions. Three-Dimensional Spatial Objects Spatial Concepts 1-15 Figure 1–8 Tolerance in an Aggregate Union Operation In the first aggregate union operation in Figure 1–8, where the tolerance is less than the distance between the rectangles, the result is a compound geometry consisting of two rectangles. In the second aggregate union operation, where the tolerance is greater than the distance between the rectangles, the result is a single geometry. 1.11 Three-Dimensional Spatial Objects Effective with Oracle Database Release 11.1, Oracle Spatial supports the storage and retrieval of three-dimensional spatial data, which can include points, point clouds (collections of points), lines, polygons, surfaces, and solids. Table 1–1 show the SDO_ GTYPE and element-related attributes of the SDO_GEOMETRY type that are relevant to three-dimensional geometries. (The SDO_GEOMETRY type is explained in Section 2.2.) Table 1–1 SDO_GEOMETRY Attributes for Three-Dimensional Geometries Type of 3-D Data SDO_GTYPE Element Type, Interpretation in SDO_ELEM_INFO Point 3001 Does not apply. Specify all 3 dimension values in the SDO_ POINT_TYPE attribute. Line 3002 2, 1 Polygon 3003 1003, 1: planar exterior polygon 2003, 1: planar interior polygon 1003, 3: planar exterior rectangle 2003, 3: planar interior rectangle Surface 3003 1006, 1: surface (followed by element information for the polygons) Collection 3004 Same considerations as for two-dimensional Multipoint (point cloud) 3005 1, n (where n is the number of points) Multiline 3006 Same considerations as for two-dimensional Multisurface 3007 Element definitions for one or more surfaces geom1 tolerance geom2 tolerance geom1 geom2 SDO_AGGR_ UNION SDO_AGGR_ UNION Three-Dimensional Spatial Objects 1-16 Oracle Spatial Developer's Guide The following Spatial operators consider all three dimensions in their computations: ■ SDO_ANYINTERACT ■ SDO_FILTER ■ SDO_INSIDE (for solid geometries only) ■ SDO_NN ■ SDO_WITHIN_DISTANCE The other operators consider only the first two dimensions. For some of preceding operators the height information is ignored when dealing with geodetic data, as explained later in this section. (Spatial operators are described in Chapter 19.) The SDO_GEOM.SDO_VOLUME function applies only to solid geometries, which are by definition three-dimensional; however, this function cannot be used with geodetic data. (This function is described in Chapter 24.) For information about support for three-dimensional geometries with other SDO_GEOM subprograms, see the usage information after Table 24–1, " Geometry Subprograms". For distance computations with three-dimensional geometries: ■ If the data is geodetic (geographic 3D), the distance computations are done on the geodetic surface. ■ If the data is non-geodetic (projected or local), the distance computations are valid only if the unit of measure is the same for all three dimensions. To have any functions, procedures, or operators consider all three dimensions, you must specify PARAMETERS ('sdo_indx_dims=3') in the CREATE INDEX statement when you create the spatial index on a spatial table containing Geographic3D data (longitude, latitude, ellipsoidal height). If you do not specify that parameter in the CREATE INDEX statement, a two-dimensional index is created. For Spatial functions, procedures, and operators that consider all three dimensions, distance and length computations correctly factor in the height or elevation. For example, consider two three-dimensional points, one at the origin of a Cartesian space (0,0,0), and the other at X=3 on the Y axis and a height (Z) of 4 (3,0,4). ■ If the operation considers all three dimensions, the distance between the two points is 5. (Think of the hypotenuse of a 3-4-5 right triangle.) ■ If the operation considers only two dimensions, the distance between the two points is 3. (That is, the third dimension, or height, is ignored.) Solid 3008 Simple solid formed by a single closed surface: one element type 1007, followed by one element type 1006 (the external surface) and optionally one or more element type 2006 (internal surfaces) Composite solid formed by multiple adjacent simple solids: one element type 1008 (holding the count of simple solids), followed by any number of element type 1007 (each describing one simple solid) Multisolid 3009 Element definitions for one or more simple solids (element type 1007) or composite solids (element type 1008) Table 1–1 (Cont.) SDO_GEOMETRY Attributes for Three-Dimensional Geometries Type of 3-D Data SDO_GTYPE Element Type, Interpretation in SDO_ELEM_INFO Three-Dimensional Spatial Objects Spatial Concepts 1-17 However, for the following operators and subprograms, when dealing with geodetic data, the distances with three-dimensional geometries are computed between the "ground" representations (for example, the longitude/latitude extent of the footprint of a building), and the height information is ignored: ■ SDO_NN operator ■ SDO_WITHIN_DISTANCE operator ■ SDO_GEOM.SDO_DISTANCE function ■ SDO_GEOM.WITHIN_DISTANCE function For a two-dimensional query window with three-dimensional data, you can use the SDO_FILTER operator, but not any other spatial operators. For examples of creating different types of three-dimensional spatial geometries, see Section 2.7.9. That section also includes an example showing how to update the spatial metadata and create spatial indexes for three-dimensional geometries. For information about support for three-dimensional coordinate reference systems, see Section 6.5. Three-dimensional support does not apply to many spatial aggregate functions and PL/SQL packages and subprograms. The following are supported for two-dimensional geometries only: ■ Spatial aggregate functions, except for SDO_AGGR_MBR, which is supported for both two-dimensional and three-dimensional geometries. ■ SDO_GEOM (geometry) subprograms, except for the following, which are supported for both two-dimensional and three-dimensional geometries: – SDO_GEOM.RELATE with the ANYINTERACT mask – SDO_GEOM.SDO_AREA – SDO_GEOM.SDO_DISTANCE – SDO_GEOM.SDO_LENGTH – SDO_GEOM.SDO_MAX_MBR_ORDINATE – SDO_GEOM.SDO_MBR – SDO_GEOM.SDO_MIN_MBR_ORDINATE – SDO_GEOM.SDO_VOLUME – SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT – SDO_GEOM.VALIDATE_LAYER_WITH_CONTEXT – SDO_GEOM.WITHIN_DISTANCE ■ SDO_SAM (spatial analysis and mining) subprograms ■ SDO_MIGRATE.TO_CURRENT procedure 1.11.1 Modeling Surfaces A surface contains an area but not a volume, and it can have two or three dimensions. A surface is often constructed by a set of planar regions. Surfaces can be modeled as surface-type SDO_GEOMETRY objects or, if they are very large, as SDO_TIN objects. The surface-type in SDO_GEOMETRY can be an arbitrary surface defining a contiguous area bounded by adjacent three-dimensional polygons. Three-Dimensional Spatial Objects 1-18 Oracle Spatial Developer's Guide The number of polygons in the SDO_GEOMETRY is limited by the number of ordinates that can be in the SDO_ORDINATES_ARRAY. An SDO_TIN object, on the other hand, models the surface as a network of triangles with no explicit limit on the number of triangles. Surfaces are stored as a network of triangles, called triangulated irregular networks, or TINs. The TIN model represents a surface as a set of contiguous, non-overlapping triangles. Within each triangle the surface is represented by a plane. The triangles are made from a set of points called mass points. If mass points are carefully selected, the TIN represents an accurate representation of the model of the surface. Well-placed mass points occur where there is a major change in the shape of the surface, for example, at the peak of a mountain, the floor of a valley, or at the edge (top and bottom) of cliffs. TINs are generally computed from a set of three-dimensional points specifying coordinate values in the longitude (x), latitude (y), and elevation (z) dimensions. Oracle TIN generation software uses the Delaunay triangulation algorithm, but it is not required that TIN data be formed using only Delaunay triangulation techniques. During and after the generation of TINs, you can specify stop lines. Stop lines typically indicate places where the elevation lines are not continuous, such as the slope from the top to the bottom of a cliff. Such regions are to be excluded from the TIN. The general process for working with a TIN is as follows: 1. Initialize the TIN, using the SDO_TIN_PKG.INIT function. 2. Create the TIN, using the SDO_TIN_PKG.CREATE_TIN procedure. 3. As needed for queries, clip the TIN, using the SDO_TIN_PKG.CLIP_TIN function. 4. If necessary, use the SDO_TIN_PKG.TO_GEOMETRY function (for example, to convert the result of a clip operation into a single SDO_GEOMETRY object). The PL/SQL subprograms for working with TINs are described in Chapter 30. For a Java example of working with TINs, see the following files: $ORACLE_HOME/md/demo/TIN/examples/java/README.txt $ORACLE_HOME/md/demo/TIN/examples/java/readTIN.java 1.11.2 Modeling Solids The simplest types of solids can be represented as cuboids, such as a cube or a brick. A more complex solid is a frustum, which is a pyramid formed by cutting a larger pyramid (with three or more faces) by a plane parallel to the base of that pyramid. Frustums can only be used as query windows to spatial operators. Frustums and cubes are typically modeled as solid-type SDO_GEOMETRY objects. Figure 1–9 shows a frustum as a query window, with two spatial objects at different distances from the view point. Three-Dimensional Spatial Objects Spatial Concepts 1-19 Figure 1–9 Frustum as Query Window for Spatial Objects Point clouds, which are large collections of points, can sometimes be used to model the shape or structure of solid and surface geometries. Most applications that use point cloud data contain one or both of the following kinds of spatial queries: queries based on location, and queries based on both location and visibility (that is, visibility queries). Most applications that use point cloud data seek to minimize data transfer by retrieving objects based on their distance from a view point. For example, in Figure 1–9, object B is farther from the view point than object A, and therefore the application might retrieve object A in great detail (high resolution) and object B in less detail (low resolution). In most scenarios, the number of objects increases significantly as the distance from the view point increases; and if farther objects are retrieved at lower resolutions than nearer objects, the number of bytes returned by the query and the rendering time for the objects decrease significantly. The general process for working with a point cloud is as follows: 1. Initialize the point cloud, using the SDO_PC_PKG.INIT function. 2. Create the point cloud, using the SDO_PC_PKG.CREATE_PC procedure. 3. As needed for queries, clip the point cloud, using the SDO_PC_PKG.CLIP_PC function. 4. If necessary, use the SDO_PC_PKG.TO_GEOMETRY function (for example, to convert the result of a clip operation into a single SDO_GEOMETRY object). The PL/SQL subprograms for working with point clouds are described in Chapter 28. For a Java example of working with point clouds, see the following files: $ORACLE_HOME/md/demo/PointCloud/examples/java/README.txt $ORACLE_HOME/md/demo/PointCloud/examples/java/readPointCloud.java 1.11.3 Three-Dimensional Optimized Rectangles Instead of specifying all the vertices for a three-dimensional rectangle (a polygon in the shape of rectangle in three-dimensional space), you can represent the rectangle by specifying just the two corners corresponding to the minimum ordinate values (min-corner) and the maximum ordinate values (max-corner) for the X, Y, and Z dimensions. The orientation of a three-dimensional rectangle defined in this way is as follows: View Point A B View Frustum Three-Dimensional Spatial Objects 1-20 Oracle Spatial Developer's Guide ■ If the rectangle is specified as , the normal points in the positive direction of the perpendicular third dimension. ■ If the rectangle is specified as , the normal points in the negative direction of the perpendicular third dimension. For example, if the rectangle is in the XY plane and the order of the vertices is , the normal is along the positive Z-axis; but if the order is , the normal is along the negative Z-axis. Using these orientation rules for rectangles, you can specify the order of the min-corner and max-corner vertices for a rectangle appropriately so that the following requirements are met: ■ The normal for each polygon in a solid always points outward from the solid when the rectangle is part of the solid. ■ An inner rectangle polygon is oriented in the reverse direction as its outer when the rectangle is part of a surface. 1.11.4 Using Texture Data A texture is an image that represents one or more parts of a feature. Textures are commonly used with visualizer applications (viewers) that display objects stored as spatial geometries. For example, a viewer might display an office building (three-dimensional solid) using textures, to allow a more realistic visualization than using just colors. Textures can be used with two-dimensional and three-dimensional geometries. In the simplest case, a rectangular geometry can be draped with a texture bitmap. However, often only a sub-region of a texture bitmap is used, as in the following example cases: ■ If the texture bitmap contains multiple sides of the same building, as well as the roof and rood gables. In this case, each bitmap portion is draped over one of the geometry faces. ■ If the texture bitmap represents a single panel or window on the building surface, and a geometric face represents a wall with 15 such panels or windows (five on each of three floors). In this case, the single texture bitmap is tiled 15 times over the face. ■ If the face is non-rectangular sub-faces, such as roof gables. In this case, only a portion (possible triangular) of the texture bitmap is used. Figure 1–10 shows a large rectangular surface that, when viewed, appears to consist of three textures, each of which is repeated multiple times in various places on the surface. Note: This section describes concepts that you will need to understand for using texture data with Spatial. However, the texture metadata is not yet fully implemented in Oracle Spatial, and a viewer is not yet supported. This section will be updated when texture support is released. Three-Dimensional Spatial Objects Spatial Concepts 1-21 Figure 1–10 Faces and Textures As shown in Figure 1–10: ■ The entire image is a large surface that consists of 12 smaller rectangular faces (surface geometries), each of which can be represented by one of three images (labeled A, B, and C). ■ Three texture bitmaps (labeled A, B, and C) can be used to visualize all of the faces. In this case, bitmap A is used 3 times, bitmap B is used 6 times, and bitmap C is used 3 times. Figure 1–11 shows a texture bitmap mapped to a triangular face. Figure 1–11 Texture Mapped to a Face As shown in Figure 1–11: ■ The face (surface geometry) is a triangle. (For example, a side or roof of a building may contain several occurrences of this face.) ■ The texture bitmap (image) is a rectangle, shown in the box in the middle. ■ A portion of the texture bitmap represents an image of the face. This portion is shown by a dashed line in the box on the right. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 A C Texture bitmaps (images): B A AB B C C C B B B B A A Texture bitmap:Face geometry: Texture mapped to face: (image) (image) Three-Dimensional Spatial Objects 1-22 Oracle Spatial Developer's Guide In your application, you will need to specify coordinates within the texture bitmap to map the appropriate portion to the face geometry. To minimize the storage requirements for image data representing surfaces, you should store images for only the distinct textures that will be needed. The data type for storing a texture is SDO_ORDINATE_ARRAY, which is used in the SDO_GEOMETRY type definition (explained in Section 2.2). For example, assume that the large surface in Figure 1–10 has the following definition: SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,1), -- one polygon (exterior polygon ring) SDO_ORDINATE_ARRAY(1,1. 1,13, 13,13, 1,13, 1,1) ) Assume that you have a MY_TEXTURE_COORDINATES table with the following definition: CREATE TABLE my_texture_coordinates ( texture_coord_id NUMBER PRIMARY KEY, texture_name VARCHAR2(32), texture_coordinates SDO_ORDINATE_ARRAY); Example 1–1 inserts three texture coordinate definitions into this table. For each texture, its coordinates reflect one of the appropriate smaller rectangles shown in Figure 1–10; however, you can choose any one of the appropriate rectangles for each texture. In Example 1–1, the SDO_ORDINATE_ARRAY definitions for each texture reflect a polygon near the top of Figure 1–10. Example 1–1 Inserting Texture Coordinate Definitions INSERT INTO my_texture_coordinates VALUES( 1, 'Texture_A', SDO_ORDINATE_ARRAY(1,9, 1,5, 5,12, 1,12, 1,9) ); INSERT INTO my_texture_coordinates VALUES( 2, 'Texture_B', SDO_ORDINATE_ARRAY(5,9, 9,9, 9,12, 5,12, 5,9) ); INSERT INTO my_texture_coordinates VALUES( 3, 'Texture_C', SDO_ORDINATE_ARRAY(1,12, 13,12, 13,13, 1,13, 1,12) ); 1.11.4.1 Schema Considerations with Texture Data Texture bitmaps (stored as BLOBs or as URLs in VARCHAR2 format) and texture coordinate arrays (stored using type SDO_ORDINATE_ARRAY) can be stored in the same table as the SDO_GEOMETRY column or in separate tables; however, especially for the texture bitmaps, it is usually better to use separate tables. Texture bitmaps are likely to be able to be shared among features (such as different office buildings), but texture coordinate definitions are less likely to be shareable among features. (For example, many office buildings may share the same general type of glass exterior, but Three-Dimensional Spatial Objects Spatial Concepts 1-23 few of the buildings have the same number of windows and floors. In designing your textures and applications, you must consider how many buildings use the same texture sub-region or drape the texture in the same size of repetitive matrix.) An exception is a texture coordinate array that drapes an entire texture bitmap over a rectangular geometric face. In this case, the texture coordinate array can be specified as (0,0, 1,0, 1,1, 0,1, 1,1), defined by vertices “lower left”, “lower right”, “upper right”, “upper left”, and closing with “lower left”. Many data sets use this texture coordinate array extensively, because they have primarily rectangular faces and they store one facade for each texture bitmap. If you used separate tables, you could link them to the surface geometries using foreign keys, as in Example 1–2. Example 1–2 Creating Tables for Texture Coordinates, Textures, and Surfaces -- One row for each texture coordinates definition. CREATE TABLE my_texture_coordinates ( texture_coord_id NUMBER PRIMARY KEY, texture_coordinates SDO_ORDINATE_ARRAY); -- One row for each texture. CREATE TABLE my_textures( texture_id NUMBER PRIMARY KEY, texture BLOB); -- One row for each surface (each individual "piece" of a -- potentially larger surface). CREATE TABLE my_surfaces( surface_id NUMBER PRIMARY KEY, surface_geometry SDO_GEOMETRY, texture_id NUMBER, texture_coord_id NUMBER, CONSTRAINT texture_id_fk FOREIGN KEY (texture_id) REFERENCES my_textures(texture_id), CONSTRAINT texture_coord_id_fk FOREIGN KEY (texture_coord_id) REFERENCES my_texture_coordinates(texture_coord_id)); 1.11.5 Validation Checks for Three-Dimensional Geometries The SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT and SDO_ GEOM.VALIDATE_LAYER_WITH_CONTEXT subprograms can validate two-dimensional and three-dimensional geometries. For a three-dimensional geometry, these subprograms perform any necessary checks on any two-dimensional geometries (see the Usage Notes for SDO_GEOM.VALIDATE_GEOMETRY_WITH_ CONTEXT) within the overall three-dimensional geometry, but also several checks specific to the three-dimensional nature of the overall object. For a simple solid (one outer surface and any number of inner surfaces), these subprograms perform the following checks: ■ Closedness: The solid must be closed. ■ Reachability: Each face of a solid must have a full-edge intersection with its neighboring faces, and all faces must be reachable from any face. ■ Inner-outer disjointedness: An inner surface must not intersect the outer surface at more than a point or a line; that is, there must be no overlapping areas with inner surfaces. Geocoding 1-24 Oracle Spatial Developer's Guide ■ No surface patch: No additional surfaces can be defined on the surfaces that make up the solid. ■ Orientation: For all surfaces, the vertices must be aligned so that the normal vector (or surface normal, or "the normal") points to the outside of (away from) the outer solid. Thus, the volume of the outer solid must be greater than zero, and the volume of any inner solid must be less than zero. For a composite solid (one or more solids connected to each other), these subprograms perform the following checks: ■ Connectedness: All solids of a composite solid must share at least one face. ■ Zero-volume intersections: Any intersections of the solids in a composite solid must have a volume of zero. For a multisolid (one or more solids, each of which is a simple or composite solid), these subprograms perform the following check: ■ Disjointedness: Any two solids of a multisolid can share points or lines, but must not intersect in any other manner. 1.12 Geocoding Geocoding is the process of converting tables of address data into standardized address, location, and possibly other data. The result of a geocoding operation includes the pair of longitude and latitude coordinates that correspond with the input address or location. For example, if the input address is 22 Monument Square, Concord, MA 01742, the longitude and latitude coordinates in the result of the geocoding operation may be (depending on the geocoding data provider) -71.34937 and 42.46101, respectively. Given a geocoded address, you can perform proximity or location queries using a spatial engine, such as Oracle Spatial, or demographic analysis using tools and data from Oracle’s business partners. In addition, you can use geocoded data with other spatial data such as block group, postal code, and county code for association with demographic information. Results of analyses or queries can be presented as maps, in addition to tabular formats, using third-party software integrated with Oracle Spatial. For conceptual and usage information about the geocoding capabilities of Oracle Spatial, see Chapter 11. For reference information about the MDSYS.SDO_GCDR PL/SQL package, see Chapter 23. 1.13 Spatial Java Application Programming Interface Oracle Spatial provides a Java application programming interface (API) that includes the following packages: ■ oracle.spatial.geometry provides support for the Spatial SQL SDO_ GEOMETRY data type, which is documented in this guide. ■ oracle.spatial.georaster provides support for the core GeoRaster features, which are documented in Oracle Spatial GeoRaster Developer's Guide. ■ oracle.spatial.georaster.image provides support for generating Java images from a GeoRaster object or subset of a GeoRaster object, and for processing the images. These features are documented in Oracle Spatial GeoRaster Developer's Guide. Predefined User Accounts Created by Spatial Spatial Concepts 1-25 ■ oracle.spatial.georaster.sql provides support for wrapping the GeoRaster PL/SQL API, which is documented in Oracle Spatial GeoRaster Developer's Guide. ■ oracle.spatial.network provides support for the Oracle Spatial network data model, which is documented in Oracle Spatial Topology and Network Data Models Developer's Guide. ■ oracle.spatial.network.lod provides support for the load-on-demand (LOD) approach of network analysis in the Oracle Spatial network data model, which is documented in Oracle Spatial Topology and Network Data Models Developer's Guide. ■ oracle.spatial.network.lod.config provides support for the configuration of load-on-demand (LOD) network analysis in the Oracle Spatial network data model, which is documented in Oracle Spatial Topology and Network Data Models Developer's Guide. ■ oracle.spatial.topo provides support for the Oracle Spatial topology data model, which is documented in Oracle Spatial Topology and Network Data Models Developer's Guide. ■ oracle.spatial.util provides classes that perform miscellaneous operations. For detailed reference information about the classes and interfaces in these packages, see Oracle Spatial Java API Reference (Javadoc). The Spatial Java class libraries are in .jar files under the /md/jlib/ directory. 1.14 Predefined User Accounts Created by Spatial During installation, Spatial creates user accounts that have the minimum privileges needed to perform their jobs. These accounts are created locked and expired; so if you need to use the accounts, you must unlock them. Table 1–2 lists the predefined user accounts created by Spatial. For information about Oracle Database predefined user accounts, including how to secure these accounts, see Oracle Database 2 Day + Security Guide. Table 1–2 Predefined User Accounts Created by Spatial User Account Description MDDATA The schema used by Oracle Spatial for storing data used by geocoding and routing applications. This is the default schema for Oracle software that accesses geocoding and routing data. SPATIAL_CSW_ADMIN_ USR The Catalog Services for the Web (CSW) account. It is used by the Oracle Spatial CSW cache manager to load all record type metadata, and record instances from the database into the main memory for the record types that are cached. SPATIAL_WFS_ADMIN_ USR The Web Feature Service (WFS) account. It is used by the Oracle Spatial WFS cache manager to load all feature type metadata, and feature instances from the database into main memory for the feature types that are cached. Performance and Tuning Information 1-26 Oracle Spatial Developer's Guide 1.15 Performance and Tuning Information Many factors can affect the performance of Oracle Spatial applications, such as the use of optimizer hints to influence the plan for query execution. This guide contains some information about performance and tuning where it is relevant to a particular topic. For example, Section 1.7.2 discusses R-tree quality and its possible effect on query performance, and Section 1.9 explains why spatial operators provide better performance than procedures and functions. In addition, more Spatial performance and tuning information is available in one or more white papers through the Oracle Technology Network (OTN). That information is often more detailed than what is in this guide, and it is periodically updated as a result of internal testing and consultations with Spatial users. To find that information on the OTN, go to http://www.oracle.com/technology/products/spatial/ Look for material relevant to Spatial performance and tuning. 1.16 OGC and ISO Compliance Oracle Spatial is conformant with Open Geospatial Consortium (OGC) Simple Features Specification 1.1.1 (Document 99-049), starting with Oracle Database release 10g (version 10.1.0.4). Conformance with the Geometry Types Implementation means that Oracle Spatial supports all the types, functions, and language constructs detailed in Section 3.2 of the specification. Synonyms are created to match all OGC function names except for X(p Point) and Y(p Point). For these functions, you must use the names OGC_X and OGC_Y instead of just X and Y. Oracle Spatial is conformant with the following International Organization for Standardization (ISO) standards: ■ ISO 13249-3 SQL Multimedia and Application Packages - Part 3: Spatial ■ ISO 19101: Geographic information - Reference model (definition of terms and approach) ■ ISO 19109: Geographic information - Rules for application schema (called the General Feature Model) ■ ISO 19111: Geographic information - Spatial referencing by coordinates (also OGC Abstract specification for coordinate reference systems) ■ ISO 19118: Geographic information - Encoding (GML 2.1 and GML 3.1.1) ■ ISO 19107: Geographic information - Spatial schema (also OGC Abstract specification for Geometry) However, standards compliance testing for Oracle Spatial is ongoing, and compliance with more recent versions of standards or with new standards might be announced at any time. For current information about compliance with standards, see http://www.oracle.com/technology/products/spatial/. 1.17 Spatial Release (Version) Number To check which release of Spatial you are running, use the SDO_VERSION function. For example: SELECT SDO_VERSION FROM DUAL; Spatial Examples Spatial Concepts 1-27 SDO_VERSION -------------------------------------------------------------------------------- 11.1.0.0.0 1.18 Spatial Application Hardware Requirement Considerations This section discusses some general guidelines that affect the amount of disk storage space and CPU power needed for applications that use Oracle Spatial. These guidelines are intended to supplement, not replace, any other guidelines you use for general application sizing. The following characteristics of spatial applications can affect the need for storage space and CPU power: ■ Data volumes: The amount of storage space needed for spatial objects depends on their complexity (precision of representation and number of points for each object). For example, storing one million point objects takes less space than storing one million road segments or land parcels. Complex natural features such as coastlines, seismic fault lines, rivers, and land types can require significant storage space if they are stored at a high precision. ■ Query complexity: The CPU requirements for simple mapping queries, such as Select all features in this rectangle, are lower than for more complex queries, such as Find all seismic fault lines that cross this coastline. 1.19 Spatial Error Messages Spatial error messages are documented in Oracle Database Error Messages. Oracle error message documentation is only available in HTML. If you only have access to the Oracle Documentation DVD, you can browse the error messages by range. Once you find the specific range, use your browser's "find in page" feature to locate the specific message. When connected to the Internet, you can search for a specific error message using the error message search feature of the Oracle online documentation. 1.20 Spatial Examples Oracle Spatial provides examples that you can use to reinforce your learning and to create models for coding certain operations. If you installed the demo files from the Oracle Database Examples media (see Oracle Database Examples Installation Guide), several examples are provided in the following directory: $ORACLE_HOME/md/demo/examples The following files in that directory are helpful for applications that use the Oracle Call Interface (OCI): ■ readgeom.c and readgeom.h ■ writegeom.c and writegeom.h This guide also includes many examples in SQL and PL/SQL. One or more examples are usually provided with the reference information for each function or procedure, and several simplified examples are provided that illustrate table and index creation, combinations of functions and procedures, and advanced features: ■ Inserting, indexing, and querying spatial data (Section 2.1) README File for Spatial and Related Features 1-28 Oracle Spatial Developer's Guide ■ Coordinate systems (spatial reference systems) (Section 6.13) ■ Linear referencing system (LRS) (Section 7.7) ■ SDO_GEOMETRY objects in function-based indexes (Section 9.2) ■ Complex queries (Appendix C) 1.21 README File for Spatial and Related Features A README.txt file supplements the information in the following manuals: Oracle Spatial Developer's Guide (this manual), Oracle Spatial GeoRaster Developer's Guide, and Oracle Spatial Topology and Network Data Models Developer's Guide. This file is located at: $ORACLE_HOME/md/doc/README.txt 2 Spatial Data Types and Metadata 2-1 2 Spatial Data Types and Metadata Oracle Spatial consists of a set of object data types, type methods, and operators, functions, and procedures that use these types. A geometry is stored as an object, in a single row, in a column of type SDO_GEOMETRY. Spatial index creation and maintenance is done using basic DDL (CREATE, ALTER, DROP) and DML (INSERT, UPDATE, DELETE) statements. This chapter starts with a simple example that inserts, indexes, and queries spatial data. You may find it helpful to read this example quickly before you examine the detailed data type and metadata information later in the chapter. This chapter contains the following major sections: ■ Section 2.1, "Simple Example: Inserting, Indexing, and Querying Spatial Data" ■ Section 2.2, "SDO_GEOMETRY Object Type" ■ Section 2.3, "SDO_GEOMETRY Methods" ■ Section 2.4, "SDO_GEOMETRY Constructors" ■ Section 2.5, "TIN-Related Object Types" ■ Section 2.6, "Point Cloud-Related Object Types" ■ Section 2.7, "Geometry Examples" ■ Section 2.8, "Geometry Metadata Views" ■ Section 2.9, "Spatial Index-Related Structures" ■ Section 2.10, "Unit of Measurement Support" 2.1 Simple Example: Inserting, Indexing, and Querying Spatial Data This section presents a simple example of creating a spatial table, inserting data, creating the spatial index, and performing spatial queries. It refers to concepts that were explained in Chapter 1 and that will be explained in other sections of this chapter. The scenario is a soft drink manufacturer that has identified geographical areas of marketing interest for several products (colas). The colas could be those produced by the company or by its competitors, or some combination. Each area of interest could represent any user-defined criterion: for example, an area where that cola has the majority market share, or where the cola is under competitive pressure, or where the cola is believed to have significant growth potential. Each area could be a neighborhood in a city, or a part of a state, province, or country. Figure 2–1 shows the areas of interest for four colas. Simple Example: Inserting, Indexing, and Querying Spatial Data 2-2 Oracle Spatial Developer's Guide Figure 2–1 Areas of Interest for the Simple Example Example 2–1 performs the following operations: ■ Creates a table (COLA_MARKETS) to hold the spatial data ■ Inserts rows for four areas of interest (cola_a, cola_b, cola_c, cola_d) ■ Updates the USER_SDO_GEOM_METADATA view to reflect the dimensional information for the areas ■ Creates a spatial index (COLA_SPATIAL_IDX) ■ Performs some spatial queries Many concepts and techniques in Example 2–1 are explained in detail in other sections of this chapter. Example 2–1 Simple Example: Inserting, Indexing, and Querying Spatial Data -- Create a table for cola (soft drink) markets in a -- given geography (such as city or state). -- Each row will be an area of interest for a specific -- cola (for example, where the cola is most preferred -- by residents, where the manufacturer believes the -- cola has growth potential, and so on). -- (For restrictions on spatial table and column names, see -- Section 2.8.1 and Section 2.8.2.) CREATE TABLE cola_markets ( mkt_id NUMBER PRIMARY KEY, name VARCHAR2(32), shape SDO_GEOMETRY); -- The next INSERT statement creates an area of interest for -- Cola A. This area happens to be a rectangle. -- The area could represent any user-defined criterion: for -- example, where Cola A is the preferred drink, where -- Cola A is under competitive pressure, where Cola A -- has strong growth potential, and so on. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 cola_a cola_b cola_c cola_d Simple Example: Inserting, Indexing, and Querying Spatial Data Spatial Data Types and Metadata 2-3 INSERT INTO cola_markets VALUES( 1, 'cola_a', SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), -- one rectangle (1003 = exterior) SDO_ORDINATE_ARRAY(1,1, 5,7) -- only 2 points needed to -- define rectangle (lower left and upper right) with -- Cartesian-coordinate data ) ); -- The next two INSERT statements create areas of interest for -- Cola B and Cola C. These areas are simple polygons (but not -- rectangles). INSERT INTO cola_markets VALUES( 2, 'cola_b', SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,1), -- one polygon (exterior polygon ring) SDO_ORDINATE_ARRAY(5,1, 8,1, 8,6, 5,7, 5,1) ) ); INSERT INTO cola_markets VALUES( 3, 'cola_c', SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,1), -- one polygon (exterior polygon ring) SDO_ORDINATE_ARRAY(3,3, 6,3, 6,5, 4,5, 3,3) ) ); -- Now insert an area of interest for Cola D. This is a -- circle with a radius of 2. It is completely outside the -- first three areas of interest. INSERT INTO cola_markets VALUES( 4, 'cola_d', SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,4), -- one circle SDO_ORDINATE_ARRAY(8,7, 10,9, 8,11) ) ); --------------------------------------------------------------------------- -- UPDATE METADATA VIEW -- Simple Example: Inserting, Indexing, and Querying Spatial Data 2-4 Oracle Spatial Developer's Guide --------------------------------------------------------------------------- -- Update the USER_SDO_GEOM_METADATA view. This is required -- before the Spatial index can be created. Do this only once for each -- layer (that is, table-column combination; here: COLA_MARKETS and SHAPE). INSERT INTO user_sdo_geom_metadata (TABLE_NAME, COLUMN_NAME, DIMINFO, SRID) VALUES ( 'cola_markets', 'shape', SDO_DIM_ARRAY( -- 20X20 grid SDO_DIM_ELEMENT('X', 0, 20, 0.005), SDO_DIM_ELEMENT('Y', 0, 20, 0.005) ), NULL -- SRID ); ------------------------------------------------------------------- -- CREATE THE SPATIAL INDEX -- ------------------------------------------------------------------- CREATE INDEX cola_spatial_idx ON cola_markets(shape) INDEXTYPE IS MDSYS.SPATIAL_INDEX; -- Preceding statement created an R-tree index. ------------------------------------------------------------------- -- PERFORM SOME SPATIAL QUERIES -- ------------------------------------------------------------------- -- Return the topological intersection of two geometries. SELECT SDO_GEOM.SDO_INTERSECTION(c_a.shape, c_c.shape, 0.005) FROM cola_markets c_a, cola_markets c_c WHERE c_a.name = 'cola_a' AND c_c.name = 'cola_c'; -- Do two geometries have any spatial relationship? SELECT SDO_GEOM.RELATE(c_b.shape, 'anyinteract', c_d.shape, 0.005) FROM cola_markets c_b, cola_markets c_d WHERE c_b.name = 'cola_b' AND c_d.name = 'cola_d'; -- Return the areas of all cola markets. SELECT name, SDO_GEOM.SDO_AREA(shape, 0.005) FROM cola_markets; -- Return the area of just cola_a. SELECT c.name, SDO_GEOM.SDO_AREA(c.shape, 0.005) FROM cola_markets c WHERE c.name = 'cola_a'; -- Return the distance between two geometries. SELECT SDO_GEOM.SDO_DISTANCE(c_b.shape, c_d.shape, 0.005) FROM cola_markets c_b, cola_markets c_d WHERE c_b.name = 'cola_b' AND c_d.name = 'cola_d'; -- Is a geometry valid? SELECT c.name, SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT(c.shape, 0.005) FROM cola_markets c WHERE c.name = 'cola_c'; -- Is a layer valid? (First, create the results table.) CREATE TABLE val_results (sdo_rowid ROWID, result VARCHAR2(2000)); CALL SDO_GEOM.VALIDATE_LAYER_WITH_CONTEXT('COLA_MARKETS', 'SHAPE', SDO_GEOMETRY Object Type Spatial Data Types and Metadata 2-5 'VAL_RESULTS', 2); SELECT * from val_results; 2.2 SDO_GEOMETRY Object Type With Spatial, the geometric description of a spatial object is stored in a single row, in a single column of object type SDO_GEOMETRY in a user-defined table. Any table that has a column of type SDO_GEOMETRY must have another column, or set of columns, that defines a unique primary key for that table. Tables of this sort are sometimes referred to as spatial tables or spatial geometry tables. Oracle Spatial defines the object type SDO_GEOMETRY as: CREATE TYPE sdo_geometry AS OBJECT ( SDO_GTYPE NUMBER, SDO_SRID NUMBER, SDO_POINT SDO_POINT_TYPE, SDO_ELEM_INFO SDO_ELEM_INFO_ARRAY, SDO_ORDINATES SDO_ORDINATE_ARRAY); Oracle Spatial also defines the SDO_POINT_TYPE, SDO_ELEM_INFO_ARRAY, and SDO_ORDINATE_ARRAY types, which are used in the SDO_GEOMETRY type definition, as follows: CREATE TYPE sdo_point_type AS OBJECT ( X NUMBER, Y NUMBER, Z NUMBER); CREATE TYPE sdo_elem_info_array AS VARRAY (1048576) of NUMBER; CREATE TYPE sdo_ordinate_array AS VARRAY (1048576) of NUMBER; Because the maximum SDO_ORDINATE_ARRAY size is 1,048,576 numbers, the maximum number of vertices in an SDO_GEOMETRY object depends on the number of dimensions per vertex: 524,288 for two dimensions, 349,525 for three dimensions, and 262,144 for four dimensions. The sections that follow describe the semantics of each SDO_GEOMETRY attribute, and then describe some usage considerations (Section 2.2.6). The SDO_GEOMETRY object type has methods that provide convenient access to some of the attributes. These methods are described in Section 2.3. Some Spatial data types are described in locations other than this section: ■ Section 11.2 describes data types for geocoding. ■ Oracle Spatial GeoRaster Developer's Guide describes data types for Oracle Spatial GeoRaster. ■ Oracle Spatial Topology and Network Data Models Developer's Guide describes data types for the Oracle Spatial topology data model. 2.2.1 SDO_GTYPE The SDO_GTYPE attribute indicates the type of the geometry. Valid geometry types correspond to those specified in the Geometry Object Model for the OGIS Simple Features for SQL specification (with the exception of Surfaces). The numeric values differ from those given in the OGIS specification, but there is a direct correspondence between the names and semantics where applicable. The SDO_GTYPE value is 4 digits in the format DLTT, where: SDO_GEOMETRY Object Type 2-6 Oracle Spatial Developer's Guide ■ D identifies the number of dimensions (2, 3, or 4) ■ L identifies the linear referencing measure dimension for a three-dimensional linear referencing system (LRS) geometry, that is, which dimension (3 or 4) contains the measure value. For a non-LRS geometry, or to accept the Spatial default of the last dimension as the measure for an LRS geometry, specify 0. For information about the linear referencing system (LRS), see Chapter 7. ■ TT identifies the geometry type (00 through 09, with 10 through 99 reserved for future use). Table 2–1 shows the valid SDO_GTYPE values. The Geometry Type and Description values reflect the OGIS specification. The D in the Value column of Table 2–1 is the number of dimensions: 2, 3, or 4. For example, an SDO_GTYPE value of 2003 indicates a two-dimensional polygon. The number of dimensions reflects the number of ordinates used to represent each vertex (for example, X,Y for two-dimensional objects). In any given layer (column), all geometries must have the same number of dimensions. For example, you cannot mix two-dimensional and three-dimensional data in the same layer. Table 2–1 Valid SDO_GTYPE Values Value Geometry Type Description DL00 UNKNOWN_ GEOMETRY Spatial ignores this geometry. DL01 POINT Geometry contains one point. DL02 LINE or CURVE Geometry contains one line string that can contain straight or circular arc segments, or both. (LINE and CURVE are synonymous in this context.) DL03 POLYGON or SURFACE Geometry contains one polygon with or without holes,1 or one surface consisting of one or more polygons. In a three-dimensional polygon, all points must be on the same plane. 1 For a polygon with holes, enter the exterior boundary first, followed by any interior boundaries. DL04 COLLECTION Geometry is a heterogeneous collection of elements. COLLECTION is a superset that includes all other types. DL05 MULTIPOINT Geometry has one or more points. (MULTIPOINT is a superset of POINT.) DL06 MULTILINE or MULTICURVE Geometry has one or more line strings. (MULTILINE and MULTICURVE are synonymous in this context, and each is a superset of both LINE and CURVE.) DL07 MULTIPOLYGON or MULTISURFACE Geometry can have multiple, disjoint polygons (more than one exterior boundary). or surfaces (MULTIPOLYGON is a superset of POLYGON, and MULTISURFACE is a superset of SURFACE.) DL08 SOLID Geometry consists of multiple surfaces and is completely enclosed in a three-dimensional space. Can be a cuboid or a frustum. DL09 MULTISOLID Geometry can have multiple, disjoint solids (more than one exterior boundary). (MULTISOLID is a superset of SOLID.) SDO_GEOMETRY Object Type Spatial Data Types and Metadata 2-7 The following methods are available for returning the individual DLTT components of the SDO_GTYPE for a geometry object: Get_Dims, Get_LRS_Dim, and Get_Gtype. These methods are described in Section 2.3. For more information about SDO_GTYPE values for three-dimensional geometries, see Table 1–1 in Section 1.11. 2.2.2 SDO_SRID The SDO_SRID attribute can be used to identify a coordinate system (spatial reference system) to be associated with the geometry. If SDO_SRID is null, no coordinate system is associated with the geometry. If SDO_SRID is not null, it must contain a value from the SRID column of the SDO_COORD_REF_SYS table (described in Section 6.7.9), and this value must be inserted into the SRID column of the USER_SDO_GEOM_ METADATA view (described in Section 2.8). All geometries in a geometry column must have the same SDO_SRID value if a spatial index will be built on that column. For information about coordinate systems, see Chapter 6. 2.2.3 SDO_POINT The SDO_POINT attribute is defined using the SDO_POINT_TYPE object type, which has the attributes X, Y, and Z, all of type NUMBER. (The SDO_POINT_TYPE definition is shown in Section 2.2.) If the SDO_ELEM_INFO and SDO_ORDINATES arrays are both null, and the SDO_POINT attribute is non-null, then the X, Y, and Z values are considered to be the coordinates for a point geometry. Otherwise, the SDO_ POINT attribute is ignored by Spatial. You should store point geometries in the SDO_ POINT attribute for optimal storage; and if you have only point geometries in a layer, it is strongly recommended that you store the point geometries in the SDO_POINT attribute. Section 2.7.5 illustrates a point geometry and provides examples of inserting and querying point geometries. 2.2.4 SDO_ELEM_INFO The SDO_ELEM_INFO attribute is defined using a varying length array of numbers. This attribute lets you know how to interpret the ordinates stored in the SDO_ ORDINATES attribute (described in Section 2.2.5). Each triplet set of numbers is interpreted as follows: ■ SDO_STARTING_OFFSET -- Indicates the offset within the SDO_ORDINATES array where the first ordinate for this element is stored. Offset values start at 1 and not at 0. Thus, the first ordinate for the first element will be at SDO_ GEOMETRY.SDO_ORDINATES(1). If there is a second element, its first ordinate will be at SDO_GEOMETRY.SDO_ORDINATES(n), where n reflects the position within the SDO_ORDINATE_ARRAY definition (for example, 19 for the 19th number, as in Figure 2–4 in Section 2.7.2). Note: Do not use the SDO_POINT attribute in defining a linear referencing system (LRS) point or an oriented point. For information about LRS, see Chapter 7. For information about oriented points, see Section 2.7.6. SDO_GEOMETRY Object Type 2-8 Oracle Spatial Developer's Guide ■ SDO_ETYPE -- Indicates the type of the element. Valid values are shown in Table 2–2. SDO_ETYPE values 1, 2, 1003, and 2003 are considered simple elements. They are defined by a single triplet entry in the SDO_ELEM_INFO array. For SDO_ETYPE values 1003 and 2003, the first digit indicates exterior (1) or interior (2): 1003: exterior polygon ring (must be specified in counterclockwise order) 2003: interior polygon ring (must be specified in clockwise order) SDO_ETYPE values 4, 1005, 2005, 1006, and 2006 are considered compound elements. They contain at least one header triplet with a series of triplet values that belong to the compound element. For 4-digit SDO_ETYPE values, the first digit indicates exterior (1) or interior (2): 1005: exterior polygon ring (must be specified in counterclockwise order) 2005: interior polygon ring (must be specified in clockwise order) 1006: exterior surface consisting of one or more polygon rings 2006: interior surface in a solid element 1007: solid element The elements of a compound element are contiguous. The last point of a subelement in a compound element is the first point of the next subelement. The point is not repeated. ■ SDO_INTERPRETATION -- Means one of two things, depending on whether or not SDO_ETYPE is a compound element. If SDO_ETYPE is a compound element (4, 1005, or 2005), this field specifies how many subsequent triplet values are part of the element. If the SDO_ETYPE is not a compound element (1, 2, 1003, or 2003), the interpretation attribute determines how the sequence of ordinates for this element is interpreted. For example, a line string or polygon boundary may be made up of a sequence of connected straight line segments or circular arcs. Descriptions of valid SDO_ETYPE and SDO_INTERPRETATION value pairs are given in Table 2–2. If a geometry consists of more than one element, then the last ordinate for an element is always one less than the starting offset for the next element. The last element in the geometry is described by the ordinates from its starting offset to the end of the SDO_ ORDINATES varying length array. For compound elements (SDO_ETYPE values 4, 1005, or 2005), a set of n triplets (one for each subelement) is used to describe the element. It is important to remember that subelements of a compound element are contiguous. The last point of a subelement is Note: The use of 3 as an SDO_ETYPE value for polygon ring elements in a single geometry is discouraged. You should specify 3 only if you do not know if the simple polygon is exterior or interior, and you should then upgrade the table or layer to the current format using the SDO_MIGRATE.TO_CURRENT procedure, described in Chapter 26. You cannot mix 1-digit and 4-digit SDO_ETYPE values in a single geometry. SDO_GEOMETRY Object Type Spatial Data Types and Metadata 2-9 the first point of the next subelement. For subelements 1 through n-1, the end point of one subelement is the same as the starting point of the next subelement. The starting point for subelements 2...n-2 is the same as the end point of subelement 1...n-1. The last ordinate of subelement n is either the starting offset minus 1 of the next element in the geometry, or the last ordinate in the SDO_ORDINATES varying length array. The current size of a varying length array can be determined by using the function varray_variable.Count in PL/SQL or OCICollSize in the Oracle Call Interface (OCI). The semantics of each SDO_ETYPE element and the relationship between the SDO_ ELEM_INFO and SDO_ORDINATES varying length arrays for each of these SDO_ ETYPE elements are given in Table 2–2. Table 2–2 Values and Semantics in SDO_ELEM_INFO SDO_ ETYPE SDO_ INTERPRETATION Meaning 0 (any numeric value) Type 0 (zero) element. Used to model geometry types not supported by Oracle Spatial. For more information, see Section 2.7.7. 1 1 Point type. 1 0 Orientation for an oriented point. For more information, see Section 2.7.6. 1 n > 1 Point cluster with n points. 2 1 Line string whose vertices are connected by straight line segments. 2 2 Line string made up of a connected sequence of circular arcs. Each circular arc is described using three coordinates: the start point of the arc, any point on the arc, and the end point of the arc. The coordinates for a point designating the end of one arc and the start of the next arc are not repeated. For example, five coordinates are used to describe a line string made up of two connected circular arcs. Points 1, 2, and 3 define the first arc, and points 3, 4, and 5 define the second arc, where point 3 is only stored once. 1003 or 2003 1 Simple polygon whose vertices are connected by straight line segments. You must specify a point for each vertex; and the last point specified must be exactly the same point as the first (within the tolerance value), to close the polygon. For example, for a 4-sided polygon, specify 5 points, with point 5 the same as point 1. 1003 or 2003 2 Polygon made up of a connected sequence of circular arcs that closes on itself. The end point of the last arc is the same as the start point of the first arc. Each circular arc is described using three coordinates: the start point of the arc, any point on the arc, and the end point of the arc. The coordinates for a point designating the end of one arc and the start of the next arc are not repeated. For example, five coordinates are used to describe a polygon made up of two connected circular arcs. Points 1, 2, and 3 define the first arc, and points 3, 4, and 5 define the second arc. The coordinates for points 1 and 5 must be the same (tolerance is not considered), and point 3 is not repeated. SDO_GEOMETRY Object Type 2-10 Oracle Spatial Developer's Guide 1003 or 2003 3 Rectangle type (sometimes called optimized rectangle). A bounding rectangle such that only two points, the lower-left and the upper-right, are required to describe it. The rectangle type can be used with geodetic or non-geodetic data. However, with geodetic data, use this type only to create a query window (not for storing objects in the database). For information about using this type with geodetic data, including examples, see Section 6.2.4. For information about creating three-dimensional optimized rectangles, see Section 1.11.3. 1003 or 2003 4 Circle type. Described by three distinct non-colinear points, all on the circumference of the circle. 4 n > 1 Compound line string with some vertices connected by straight line segments and some by circular arcs. The value n in the Interpretation column specifies the number of contiguous subelements that make up the line string. The next n triplets in the SDO_ELEM_INFO array describe each of these subelements. The subelements can only be of SDO_ETYPE 2. The last point of a subelement is the first point of the next subelement, and must not be repeated. See Section 2.7.3 and Figure 2–5 for an example of a compound line string geometry. 1005 or 2005 n > 1 Compound polygon with some vertices connected by straight line segments and some by circular arcs. The value n in the Interpretation column specifies the number of contiguous subelements that make up the polygon. The next n triplets in the SDO_ELEM_INFO array describe each of these subelements. The subelements can only be of SDO_ETYPE 2. The end point of a subelement is the start point of the next subelement, and it must not be repeated. The start and end points of the polygon must be exactly the same point (tolerance is ignored). See Section 2.7.4 and Figure 2–6 for an example of a compound polygon geometry. 1006 or 2006 n > 1 Surface consisting of one or more polygons, with each edge shared by no more than two polygons. A surface contains an area but not a volume. The value n in the Interpretation column specifies the number of polygons that make up the surface. The next n triplets in the SDO_ELEM_INFO array describe each of these polygon subelements. A surface can be two-dimensional or three-dimensional. For an explanation of three-dimensional support in Spatial, see Section 1.11. Table 2–2 (Cont.) Values and Semantics in SDO_ELEM_INFO SDO_ ETYPE SDO_ INTERPRETATION Meaning SDO_GEOMETRY Object Type Spatial Data Types and Metadata 2-11 2.2.5 SDO_ORDINATES The SDO_ORDINATES attribute is defined using a varying length array (1048576) of NUMBER type that stores the coordinate values that make up the boundary of a spatial object. This array must always be used in conjunction with the SDO_ELEM_ INFO varying length array. The values in the array are ordered by dimension. For example, a polygon whose boundary has four two-dimensional points is stored as {X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1}. If the points are three-dimensional, then they are stored as {X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3, X4, Y4, Z4, X1, Y1, Z1}. The number of dimensions associated with each point is stored as metadata in the xxx_SDO_GEOM_ METADATA views, described in Section 2.8. The values in the SDO_ORDINATES array must all be valid and non-null. There are no special values used to delimit elements in a multielement geometry. The start and end points for the sequence describing a specific element are determined by the STARTING_OFFSET values for that element and the next element in the SDO_ELEM_ INFO array, as explained in Section 2.2.4. The offset values start at 1. SDO_ ORDINATES(1) is the first ordinate of the first point of the first element. 2.2.6 Usage Considerations You should use the SDO_GTYPE values as shown in Table 2–1; however, Spatial does not check or enforce all geometry consistency constraints. Spatial does check the following: ■ For SDO_GTYPE values d001 and d005, any subelement not of SDO_ETYPE 1 is ignored. ■ For SDO_GTYPE values d002 and d006, any subelement not of SDO_ETYPE 2 or 4 is ignored. ■ For SDO_GTYPE values d003 and d007, any subelement not of SDO_ETYPE 3 or 5 is ignored. (This includes SDO_ETYPE variants 1003, 2003, 1005, and 2005, which are explained in Section 2.2.4). 1007 n = 1 or 3 Solid consisting of multiple surfaces that are completely enclosed in a three-dimensional space, so that the solid has an interior volume. A solid element can have one exterior surface defined by the 1006 elements and zero or more interior boundaries defined by the 2006 elements. The value n in the Interpretation column must be 1 or 3. Subsequent triplets in the SDO_ELEM_INFO array describe the exterior 1006 and optional interior 2006 surfaces that make up the solid element. If n is 3, the solid is an optimized box, such that only two three-dimensional points are required to define it: one with minimum values for the box in the X, Y, and Z dimensions and another with maximum values for the box in the X, Y, and Z dimensions. For example: SDO_GEOMETRY(3008, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1007,3), SDO_ORDINATE_ARRAY(1,1,1, 3,3,3)) For an explanation of three-dimensional support in Spatial, see Section 1.11. Table 2–2 (Cont.) Values and Semantics in SDO_ELEM_INFO SDO_ ETYPE SDO_ INTERPRETATION Meaning SDO_GEOMETRY Methods 2-12 Oracle Spatial Developer's Guide The SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT function can be used to evaluate the consistency of a single geometry object or of all geometry objects in a specified feature table. 2.3 SDO_GEOMETRY Methods The SDO_GEOMETRY object type (described in Section 2.2) has methods (member functions) that retrieve information about a geometry object. Table 2–3 lists these methods. Example 2–2 shows most of the SDO_GEOMETRY methods. (The Get_WKB method is not included because its output cannot be displayed by SQL*Plus.) Example 2–2 SDO_GEOMETRY Methods SELECT c.shape.Get_Dims() FROM cola_markets c WHERE c.name = 'cola_b'; C.SHAPE.GET_DIMS() ------------------ 2 Table 2–3 SDO_GEOMETRY Methods Name Returns Description Get_Dims NUMBER Returns the number of dimensions of a geometry object, as specified in its SDO_GTYPE value. In Oracle Spatial, the Get_ Dims and ST_CoordDim methods return the same result. Get_GType NUMBER Returns the geometry type of a geometry object, as specified in its SDO_GTYPE value. Get_LRS_Dim NUMBER Returns the measure dimension of an LRS geometry object, as specified in its SDO_GTYPE value. A return value of 0 indicates that the geometry is a standard (non-LRS) geometry, or is an LRS geometry in the format before release 9.0.1 and with measure as the default (last) dimension; 3 indicates that the third dimension contains the measure information; 4 indicates that the fourth dimension contains the measure information. Get_WKB BLOB Returns the well-known binary (WKB) format of a geometry object. (The returned object does not include any SRID information.) Get_WKT CLOB Returns the well-known text (WKT) format (explained in Section 6.8.1.1) of a geometry object. (The returned object does not include any SRID information.) ST_CoordDim NUMBER Returns the coordinate dimension (as defined by the ISO/IEC SQL Multimedia standard) of a geometry object. In Oracle Spatial, the Get_Dims and ST_CoordDim methods return the same result. ST_IsValid NUMBER Returns 0 if a geometry object is invalid or 1 if it is valid. (The ISO/IEC SQL Multimedia standard uses the term well formed for valid in this context.) This method uses 0.001 as the tolerance value. (Tolerance is explained in Section 1.5.5.) To specify a different tolerance value or to learn more about why a geometry is invalid, use the SDO_ GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT function, which is documented in Chapter 24. SDO_GEOMETRY Constructors Spatial Data Types and Metadata 2-13 SELECT c.shape.Get_GType() FROM cola_markets c WHERE c.name = 'cola_b'; C.SHAPE.GET_GTYPE() ------------------- 3 SELECT a.route_geometry.Get_LRS_Dim() FROM lrs_routes a WHERE a.route_id = 1; A.ROUTE_GEOMETRY.GET_LRS_DIM() ------------------------------ 3 SELECT c.shape.Get_WKT() FROM cola_markets c WHERE c.name = 'cola_b'; C.SHAPE.GET_WKT() -------------------------------------------------------------------------------- POLYGON ((5.0 1.0, 8.0 1.0, 8.0 6.0, 5.0 7.0, 5.0 1.0)) SELECT c.shape.ST_CoordDim() FROM cola_markets c WHERE c.name = 'cola_b'; C.SHAPE.ST_COORDDIM() --------------------- 2 SELECT c.shape.ST_IsValid() FROM cola_markets c WHERE c.name = 'cola_b'; C.SHAPE.ST_ISVALID() -------------------- 1 2.4 SDO_GEOMETRY Constructors The SDO_GEOMETRY object type (described in Section 2.2) has constructors that create a geometry object from a well-known text (WKT) string in CLOB or VARCHAR2 format, or from a well-known binary (WKB) object in BLOB format. The following constructor formats are available: SDO_GEOMETRY(wkt CLOB, srid NUMBER DEFAULT NULL); SDO_GEOMETRY(wkt VARCHAR2, srid NUMBER DEFAULT NULL); SDO_GEOMETRY(wkb BLOB, srid NUMBER DEFAULT NULL); If the created geometry is inserted into a table, the SRID value used with the constructor must match the SDO_SRID value of the geometries in the table. The following simple example constructs a point geometry using a well-known text string. (In a WKT, spaces separate ordinates of a vertex, and commas separate vertices.) SELECT SDO_GEOMETRY('POINT(-79 37)') FROM DUAL; SDO_GEOMETRY('POINT(-7937)')(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_I -------------------------------------------------------------------------------- SDO_GEOMETRY(2001, NULL, SDO_POINT_TYPE(-79, 37, NULL), NULL, NULL) TIN-Related Object Types 2-14 Oracle Spatial Developer's Guide Example 2–3 shows SDO_GEOMETRY constructors that create geometry objects, insert the objects into a table, and display the objects that were added to the table. Example 2–3 SDO_GEOMETRY Constructors to Create Geometries DECLARE cola_b_wkb BLOB; cola_b_wkt_clob CLOB; cola_b_wkt_varchar VARCHAR2(255); cola_b_geom SDO_GEOMETRY; BEGIN -- Get cola_b geometry into CLOB, VARCHAR2, and BLOB objects, -- for use by the constructor. SELECT c.shape.Get_WKT() INTO cola_b_wkt_clob FROM cola_markets c WHERE c.name = 'cola_b'; cola_b_wkt_varchar := cola_b_wkt_clob; SELECT c.shape.Get_WKB() INTO cola_b_wkb FROM cola_markets c WHERE c.name = 'cola_b'; -- Use some SDO_GEOMETRY constructors; -- insert 3 geometries into the table; display the geometries later. cola_b_geom := SDO_GEOMETRY(cola_b_wkt_clob); INSERT INTO cola_markets VALUES (101, 'cola_b_from_clob', cola_b_geom); cola_b_geom := SDO_GEOMETRY(cola_b_wkt_varchar); INSERT INTO cola_markets VALUES (102, 'cola_b_from_varchar', cola_b_geom); cola_b_geom := SDO_GEOMETRY(cola_b_wkb); INSERT INTO cola_markets VALUES (103, 'cola_b_from_wkb', cola_b_geom); END; / PL/SQL procedure successfully completed. -- Display the geometries created using SDO_GEOMETRY constructors. -- All three geometries are identical. SELECT name, shape FROM cola_markets WHERE mkt_id > 100; NAME -------------------------------- SHAPE(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDINATES) -------------------------------------------------------------------------------- cola_b_from_clob SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(5, 1, 8, 1, 8, 6, 5, 7, 5, 1)) cola_b_from_varchar SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(5, 1, 8, 1, 8, 6, 5, 7, 5, 1)) cola_b_from_wkb SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(5, 1, 8, 1, 8, 6, 5, 7, 5, 1)) 2.5 TIN-Related Object Types This section describes the following object types related to support for triangulated irregular networks (TINs): ■ SDO_TIN TIN-Related Object Types Spatial Data Types and Metadata 2-15 ■ SDO_TIN_BLK_TYPE ■ SDO_TIN_BLK 2.5.1 SDO_TIN Object Type The description of a TIN is stored in a single row, in a single column of object type SDO_TIN in a user-defined table. The object type SDO_TIN is defined as: CREATE TYPE sdo_tin AS OBJECT (base_table VARCHAR2(70), base_table_col VARCHAR2(1024), tin_id NUMBER. blk_table VARCHAR2(70), ptn_params VARCHAR2(1024), tin_extent SDO_GEOMETRY, tin_tol NUMBER, tin_tot_dimensions NUMBER, tin_domain SDO_ORGSCL_TYPE, tin_break_lines SDO_GEOMETRY, tin_stop_lines SDO_GEOMETRY, tin_void_rgns SDO_GEOMETRY, tin_val_attr_tables SDO_STRING_ARRAY, tin_other_attrs XMLTYPE); The SDO_TIN type has the attributes shown in Table 2–4. Table 2–4 SDO_TIN Type Attributes Attribute Explanation BASE_TABLE Name of the base table containing a column of type SDO_TIN BASE_TABLE_ COL Name of the column of type SDO_TIN in the base table TIN_ID ID number for the TIN. (This unique ID number is generated by Spatial.) BLK_TABLE Name of the table that contains information about each block in the TIN. This table contains the columns shown in Table 2–5. PTN_PARAMS Parameters for partitioning the TIN TIN_EXTENT SDO_GEOMETRY object representing the spatial extent of the TIN (the minimum bounding object enclosing all objects in the TIN) TIN_TOL Tolerance value for objects in the TIN. (For information about spatial tolerance, see Section 1.5.5.) TIN_TOT_ DIMENSIONS Total number of dimensions in the TIN. Includes spatial dimensions and any nonspatial dimensions, up to a maximum total of 9. TIN_DOMAIN (Not currently used.) TIN_BREAK_ LINES (Not currently used.) TIN_STOP_ LINES Line string or multiline string SDO_GEOMETRY object representing the stop line or lines in the TIN. Stop lines typically indicate places where the elevation lines are not continuous, such as the slope from the top to the bottom of a cliff. Such regions are to be excluded from the TIN. TIN_VOID_ RGNS (Not currently used.). TIN_VAL_ ATTR_TABLES SDO_STRING_ARRAY object specifying the names of any value attribute tables for the TIN. Type SDO_STRING_ARRAY is defined as VARRAY(1048576) OF VARCHAR2(32). TIN-Related Object Types 2-16 Oracle Spatial Developer's Guide Figure 2–2 shows the storage model for TIN data, in which the TIN block table (specified in the BLK_TABLE attribute of the SDO_TIN type) stores the blocks associated with the SDO_TIN object. Figure 2–2 Storage of TIN Data The TIN block table contains the columns shown in Table 2–5. TIN_OTHER_ ATTRS XMLTYPE object specifying any other attributes of the TIN Table 2–5 Columns in the TIN Block Table Column Name Data Type Purpose BLK_ID NUMBER ID number of the block. BLK_EXTENT SDO_ GEOMETRY Spatial extent of the block. BLK_DOMAIN SDO_ ORGSCL_ TYPE (Not currently used.) Table 2–4 (Cont.) SDO_TIN Type Attributes Attribute Explanation Spatial table containing TIN data, for each row: (Various user-defined columns...) SDO_TIN object (for example, for __???) Base_Table Base_Table_Col . . .TIN_Id Blk_Table Obj_ID Blk_ID . . . Each Row = Table of TIN Blocks (with one row of SDO_PC_BLK object type for each block) SDO_TIN object Obj_ID Blk_ID . . . Obj_ID Blk_ID . . . . . . . . . Blk_Extent Blk_Extent Blk_Extent Blk_Domain Blk_Domain Blk_Domain PCBlk_Min_Res PCBlk_Min_Res PCBlk_Min_Res TIN-Related Object Types Spatial Data Types and Metadata 2-17 For each BLOB in the POINTS column of the TIN block table: ■ The total size is (tdim+1)*8, where tdim is the total dimensionality of each block. ■ The total size should be less than 5 MB for Oracle Database Release 11.1.0.6 or earlier; it should be less than 12 MB for Oracle Database Release 11.1.0.7 or later. You can use an attribute name in a query on an object of SDO_TIN. Example 2–4 shows part of a SELECT statement that queries the TIN_EXTENT attribute of the TERRAIN column of a hypothetical LANDSCAPES table. PCBLK_MIN_RES NUMBER For point cloud data, the minimum resolution level at which the block is visible in a query. The block is retrieved only if the query window intersects the spatial extent of the block and if the minimum - maximum resolution interval of the block intersects the minimum - maximum resolution interval of the query. Usually, lower values mean farther from the view point, and higher values mean closer to the view point. PCBLK_MAX_RES NUMBER For point cloud data, the maximum resolution level at which the block is visible in a query. The block is retrieved only if the query window intersects the spatial extent of the block and if the minimum - maximum resolution interval of the block intersects the minimum - maximum resolution interval of the query. Usually, lower values mean farther from the view point, and higher values mean closer to the view point. NUM_POINTS NUMBER For point cloud data, the total number of points in the POINTS BLOB NUM_UNSORTED_ POINTS NUMBER For point cloud data, the number of unsorted points in the POINTS BLOB PT_SORT_DIM NUMBER For point cloud data, the number of spatial dimensions for the points (2 or 3) POINTS BLOB For point cloud data, BLOB containing the points. Consists of an array of points, with the following information for each point: ■ d 8-byte IEEE doubles, where d is the point cloud total number of dimensions ■ 4-byte big-endian integer for the BLK_ID value ■ 4-byte big-endian integer for the PT_ID value TR_LVL NUMBER (Not currently used.) TR_RES NUMBER (Not currently used.) NUM_TRIANGLES NUMBER Number of triangles in the TRIANGLES BLOB. TR_SORT_DIM NUMBER (Not currently used.) TRIANGLES BLOB BLOB containing the triangles. Consists of an array of triangles for the block: ■ Each triangle is specified by three vertices. ■ Each vertex is specified by the pair (BLK_ID, PT_ID), with each value being a 4-byte big-endian integer. Table 2–5 (Cont.) Columns in the TIN Block Table Column Name Data Type Purpose Point Cloud-Related Object Types 2-18 Oracle Spatial Developer's Guide Example 2–4 SDO_TIN Attribute in a Query SELECT l.terrain.tin_extent FROM landscapes l WHERE ...; 2.5.2 SDO_TIN_BLK_TYPE and SDO_TIN_BLK Object Types When you perform a clip operation using the SDO_TIN_PKG.CLIP_TIN function, an object of SDO_TIN_BLK_TYPE is returned, which is defined as TABLE OF SDO_TIN_ BLK. The attributes of the SDO_TIN_BLK object type are the same as the columns in the TIN block table, which is described in Table 2–5 in Section 2.5.2. 2.6 Point Cloud-Related Object Types This section describes the following object types related to support for point clouds: ■ SDO_PC ■ SDO_PC_BLK 2.6.1 SDO_PC Object Type The description of a point cloud is stored in a single row, in a single column of object type SDO_PC in a user-defined table. The object type SDO_PC is defined as: CREATE TYPE sdo_pc AS OBJECT (base_table VARCHAR2(70), base_table_col VARCHAR2(1024), pc_id NUMBER. blk_table VARCHAR2(70), ptn_params VARCHAR2(1024), pc_extent SDO_GEOMETRY, pc_tol NUMBER, pc_tot_dimensions NUMBER, pc_domain SDO_ORGSCL_TYPE, pc_val_attr_tables SDO_STRING_ARRAY, pc_other_attrs XMLTYPE); The SDO_PC type has the attributes shown in Table 2–6. Table 2–6 SDO_PC Type Attributes Attribute Explanation BASE_TABLE Name of the base table containing a column of type SDO_PC BASE_TABLE_ COL Name of the column of type SDO_PC in the base table PC_ID ID number for the point cloud. (This unique ID number is generated by Spatial.) BLK_TABLE Name of the table that contains information about each block in the point cloud. This table contains the columns shown in Table 2–7. PTN_PARAMS Parameters for partitioning the point cloud PC_EXTENT SDO_GEOMETRY object representing the spatial extent of the point cloud (the minimum bounding object enclosing all objects in the point cloud) PC_TOL Tolerance value for points in the point cloud. (For information about spatial tolerance, see Section 1.5.5.) Point Cloud-Related Object Types Spatial Data Types and Metadata 2-19 The point cloud block table (specified in the BLK_TABLE attribute of the SDO_PC type) contains the columns shown in Table 2–7. PC_TOT_ DIMENSIONS Total number of dimensions in the point cloud. Includes spatial dimensions and any nonspatial dimensions, up to a maximum total of 9. PC_DOMAINS (Not currently used.) PC_VAL_ ATTR_TABLES SDO_STRING_ARRAY object specifying the names of any value attribute tables for the point cloud. Type SDO_STRING_ARRAY is defined as VARRAY(1048576) OF VARCHAR2(32). PC_OTHER_ ATTRS XMLTYPE object specifying any other attributes of the point cloud Table 2–7 Columns in the Point Cloud Block Table Column Name Data Type Purpose OBJ_ID NUMBER ID number of the point cloud object. BLK_ID NUMBER ID number of the block. BLK_EXTENT SDO_ GEOMETRY Spatial extent of the block. BLK_DOMAIN SDO_ ORGSCL_ TYPE (Not currently used.) PCBLK_MIN_RES NUMBER For point cloud data, the minimum resolution level at which the block is visible in a query. The block is retrieved only if the query window intersects the spatial extent of the block and if the minimum - maximum resolution interval of the block intersects the minimum - maximum resolution interval of the query. Usually, lower values mean farther from the view point, and higher values mean closer to the view point. PCBLK_MAX_RES NUMBER For point cloud data, the maximum resolution level at which the block is visible in a query. The block is retrieved only if the query window intersects the spatial extent of the block and if the minimum - maximum resolution interval of the block intersects the minimum - maximum resolution interval of the query. Usually, lower values mean farther from the view point, and higher values mean closer to the view point. NUM_POINTS NUMBER For point cloud data, the total number of points in the POINTS BLOB NUM_UNSORTED_ POINTS NUMBER For point cloud data, the number of unsorted points in the POINTS BLOB PT_SORT_DIM NUMBER Number of the dimension (1 for the first dimension, 2 for the second dimension, and so on) on which the points are sorted. POINTS BLOB BLOB containing the points. Consists of an array of points, with the following information for each point: ■ d 8-byte IEEE doubles, where d is the PC_TOT_ DIMENSIONS value ■ 4-byte big-endian integer for the BLK_ID value ■ 4-byte big-endian integer for the PT_ID value Table 2–6 (Cont.) SDO_PC Type Attributes Attribute Explanation Geometry Examples 2-20 Oracle Spatial Developer's Guide You can use an attribute name in a query on an object of SDO_PC. Example 2–5 shows part of a SELECT statement that queries the PC_EXTENT attribute of the OCEAN_ FLOOR column of a hypothetical OCEAN_FLOOR_MODEL table. Example 2–5 SDO_PC Attribute in a Query SELECT o.ocean_floor.pc_extent FROM ocean_floor_model o WHERE ...; 2.6.2 SDO_PC_BLK_TYPE and SDO_PC_BLK Object Type When you perform a clip operation using the SDO_PC_PKG.CLIP_PC function, an object of SDO_PC_BLK_TYPE is returned, which is defined as TABLE OF SDO_PC_ BLK. The attributes of the SDO_PC_BLK object type are the same as the columns in the point cloud block table, which is described in Table 2–7 in Section 2.6.1. 2.7 Geometry Examples This section contains examples of many geometry types: ■ Section 2.7.1, "Rectangle" ■ Section 2.7.2, "Polygon with a Hole" ■ Section 2.7.3, "Compound Line String" ■ Section 2.7.4, "Compound Polygon" ■ Section 2.7.5, "Point" ■ Section 2.7.6, "Oriented Point" ■ Section 2.7.7, "Type 0 (Zero) Element" ■ Section 2.7.8, "Several Two-Dimensional Geometry Types" 2.7.1 Rectangle Figure 2–3 illustrates the rectangle that represents cola_a in the example in Section 2.1. Figure 2–3 Rectangle In the SDO_GEOMETRY definition of the geometry illustrated in Figure 2–3: ■ SDO_GTYPE = 2003. The 2 indicates two-dimensional, and the 3 indicates a polygon. ■ SDO_SRID = NULL. (1, 7) (5, 7) (1, 1) (5, 1) Geometry Examples Spatial Data Types and Metadata 2-21 ■ SDO_POINT = NULL. ■ SDO_ELEM_INFO = (1, 1003, 3). The final 3 in 1,1003,3 indicates that this is a rectangle. Because it is a rectangle, only two ordinates are specified in SDO_ ORDINATES (lower-left and upper-right). ■ SDO_ORDINATES = (1,1, 5,7). These identify the lower-left and upper-right ordinates of the rectangle. Example 2–6 shows a SQL statement that inserts the geometry illustrated in Figure 2–3 into the database. Example 2–6 SQL Statement to Insert a Rectangle INSERT INTO cola_markets VALUES( 1, 'cola_a', SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), -- one rectangle (1003 = exterior) SDO_ORDINATE_ARRAY(1,1, 5,7) -- only 2 points needed to -- define rectangle (lower left and upper right) with -- Cartesian-coordinate data ) ); 2.7.2 Polygon with a Hole Figure 2–4 illustrates a polygon consisting of two elements: an exterior polygon ring and an interior polygon ring. The inner element in this example is treated as a void (a hole). Figure 2–4 Polygon with a Hole In the SDO_GEOMETRY definition of the geometry illustrated in Figure 2–4: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (10,3)(4,3) (13,5) (13,9) (11,13)(5,13) (2,11) (2,4) (10,10) (10,5)(7,5) (7,10) Geometry Examples 2-22 Oracle Spatial Developer's Guide ■ SDO_GTYPE = 2003. The 2 indicates two-dimensional, and the 3 indicates a polygon. ■ SDO_SRID = NULL. ■ SDO_POINT = NULL. ■ SDO_ELEM_INFO = (1,1003,1, 19,2003,1). There are two triplet elements: 1,1003,1 and 19,2003,1. 1003 indicates that the element is an exterior polygon ring; 2003 indicates that the element is an interior polygon ring. 19 indicates that the second element (the interior polygon ring) ordinate specification starts at the 19th number in the SDO_ORDINATES array (that is, 7, meaning that the first point is 7,5). ■ SDO_ORDINATES = (2,4, 4,3, 10,3, 13,5, 13,9, 11,13, 5,13, 2,11, 2,4, 7,5, 7,10, 10,10, 10,5, 7,5). ■ The area (SDO_GEOM.SDO_AREA function) of the polygon is the area of the exterior polygon minus the area of the interior polygon. In this example, the area is 84 (99 - 15). ■ The perimeter (SDO_GEOM.SDO_LENGTH function) of the polygon is the perimeter of the exterior polygon plus the perimeter of the interior polygon. In this example, the perimeter is 52.9193065 (36.9193065 + 16). Example 2–7 shows a SQL statement that inserts the geometry illustrated in Figure 2–4 into the database. Example 2–7 SQL Statement to Insert a Polygon with a Hole INSERT INTO cola_markets VALUES( 10, 'polygon_with_hole', SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,1, 19,2003,1), -- polygon with hole SDO_ORDINATE_ARRAY(2,4, 4,3, 10,3, 13,5, 13,9, 11,13, 5,13, 2,11, 2,4, 7,5, 7,10, 10,10, 10,5, 7,5) ) ); An example of such a "polygon with a hole" might be a land mass (such as a country or an island) with a lake inside it. Of course, an actual land mass might have many such interior polygons: each one would require a triplet element in SDO_ELEM_INFO, plus the necessary ordinate specification. Exterior and interior rings cannot be nested. For example, if a country has a lake and there is an island in the lake (and perhaps a lake on the island), a separate polygon must be defined for the island; the island cannot be defined as an interior polygon ring within the interior polygon ring of the lake. In a multipolygon (polygon collection), rings must be grouped by polygon, and the first ring of each polygon must be the exterior ring. For example, consider a polygon collection that contains two polygons (A and B): ■ Polygon A (one interior "hole"): exterior ring A0, interior ring A1 ■ Polygon B (two interior "holes"): exterior ring B0, interior ring B1, interior ring B2 Geometry Examples Spatial Data Types and Metadata 2-23 The elements in SDO_ELEM_INFO and SDO_ORDINATES must be in one of the following orders (depending on whether you specify Polygon A or Polygon B first): ■ A0, A1; B0, B1, B2 ■ B0, B1, B2; A0, A1 2.7.3 Compound Line String Figure 2–5 illustrates a crescent-shaped object represented as a compound line string made up of one straight line segment and one circular arc. Four points are required to represent this shape: points (10,10) and (10,14) describe the straight line segment, and points (10,14), (6,10), and (14,10) describe the circular arc. Figure 2–5 Compound Line String In the SDO_GEOMETRY definition of the geometry illustrated in Figure 2–5: ■ SDO_GTYPE = 2002. The first 2 indicates two-dimensional, and the second 2 indicates one or more line segments. ■ SDO_SRID = NULL. ■ SDO_POINT = NULL. ■ SDO_ELEM_INFO = (1,4,2, 1,2,1, 3,2,2). There are three triplet elements: 1,4,2, 1,2,1, and 3,2,2. The first triplet indicates that this element is a compound line string made up of two subelement line strings, which are described with the next two triplets. The second triplet indicates that the line string is made up of straight line segments and that the ordinates for this line string start at offset 1. The end point of this line string is determined by the starting offset of the second line string, 3 in this instance. The third triplet indicates that the second line string is made up of circular arcs with ordinates starting at offset 3. The end point of this line string is determined by the starting offset of the next element or the current length of the SDO_ ORDINATES array, if this is the last element. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (10,10) (6,10) (10,14) (14,10) Geometry Examples 2-24 Oracle Spatial Developer's Guide ■ SDO_ORDINATES = (10,10, 10,14, 6,10, 14,10). Example 2–8 shows a SQL statement that inserts the geometry illustrated in Figure 2–5 into the database. Example 2–8 SQL Statement to Insert a Compound Line String INSERT INTO cola_markets VALUES( 11, 'compound_line_string', SDO_GEOMETRY( 2002, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,4,2, 1,2,1, 3,2,2), -- compound line string SDO_ORDINATE_ARRAY(10,10, 10,14, 6,10, 14,10) ) ); 2.7.4 Compound Polygon Figure 2–6 illustrates an ice cream cone-shaped object represented as a compound polygon made up of one straight line segment and one circular arc. Five points are required to represent this shape: points (6,10), (10,1), and (14,10) describe one acute angle-shaped line string, and points (14,10), (10,14), and (6,10) describe the circular arc. The starting point of the line string and the ending point of the circular arc are the same point (6,10). The SDO_ELEM_INFO array contains three triplets for this compound line string. These triplets are {(1,1005,2), (1,2,1), (5,2,2)}. Figure 2–6 Compound Polygon In the SDO_GEOMETRY definition of the geometry illustrated in Figure 2–6: ■ SDO_GTYPE = 2003. The 2 indicates two-dimensional, and the 3 indicates a polygon. ■ SDO_SRID = NULL. ■ SDO_POINT = NULL. (10,1) (10,14) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (6,10) (14,10) Geometry Examples Spatial Data Types and Metadata 2-25 ■ SDO_ELEM_INFO = (1,1005,2, 1,2,1, 5,2,2). There are three triplet elements: 1,1005,2, 1,2,1, and 5,2,2. The first triplet indicates that this element is a compound polygon made up of two subelement line strings, which are described using the next two triplets. The second triplet indicates that the first subelement line string is made up of straight line segments and that the ordinates for this line string start at offset 1. The end point of this line string is determined by the starting offset of the second line string, 5 in this instance. Because the vertices are two-dimensional, the coordinates for the end point of the first line string are at ordinates 5 and 6. The third triplet indicates that the second subelement line string is made up of a circular arc with ordinates starting at offset 5. The end point of this line string is determined by the starting offset of the next element or the current length of the SDO_ORDINATES array, if this is the last element. ■ SDO_ORDINATES = (6,10, 10,1, 14,10, 10,14, 6,10). Example 2–9 shows a SQL statement that inserts the geometry illustrated in Figure 2–6 into the database. Example 2–9 SQL Statement to Insert a Compound Polygon INSERT INTO cola_markets VALUES( 12, 'compound_polygon', SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1005,2, 1,2,1, 5,2,2), -- compound polygon SDO_ORDINATE_ARRAY(6,10, 10,1, 14,10, 10,14, 6,10) ) ); 2.7.5 Point Figure 2–7 illustrates a point-only geometry at coordinates (12,14). Geometry Examples 2-26 Oracle Spatial Developer's Guide Figure 2–7 Point-Only Geometry In the SDO_GEOMETRY definition of the geometry illustrated in Figure 2–7: ■ SDO_GTYPE = 2001. The 2 indicates two-dimensional, and the 1 indicates a single point. ■ SDO_SRID = NULL. ■ SDO_POINT = SDO_POINT_TYPE(12, 14, NULL). The SDO_POINT attribute is defined using the SDO_POINT_TYPE object type, because this is a point-only geometry. For more information about the SDO_POINT attribute, see Section 2.2.3. ■ SDO_ELEM_INFO and SDO_ORDINATES are both NULL, as required if the SDO_POINT attribute is specified. Example 2–10 shows a SQL statement that inserts the geometry illustrated in Figure 2–7 into the database. Example 2–10 SQL Statement to Insert a Point-Only Geometry INSERT INTO cola_markets VALUES( 90, 'point_only', SDO_GEOMETRY( 2001, NULL, SDO_POINT_TYPE(12, 14, NULL), NULL, NULL)); You can search for point-only geometries based on the X, Y, and Z values in the SDO_ POINT_TYPE specification. Example 2–11 is a query that asks for all points whose first coordinate (the X value) is 12, and it finds the point that was inserted in Example 2–10. Example 2–11 Query for Point-Only Geometry Based on a Coordinate Value SELECT * from cola_markets c WHERE c.shape.SDO_POINT.X = 12; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (12,14) Geometry Examples Spatial Data Types and Metadata 2-27 MKT_ID NAME ---------- -------------------------------- SHAPE(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDINATES) -------------------------------------------------------------------------------- 90 point_only SDO_GEOMETRY(2001, NULL, SDO_POINT_TYPE(12, 14, NULL), NULL, NULL) 2.7.6 Oriented Point An oriented point is a special type of point geometry that includes coordinates representing the locations of the point and a virtual end point, to indicate an orientation vector that can be used for rotating a symbol at the point or extending a label from the point. The main use for an oriented point is in map visualization and display applications that include symbols, such as a shield symbol to indicate a highway. To specify an oriented point: ■ Use an SDO_GTYPE value (explained in Section 2.2.1) for a point or multipoint geometry. ■ Specify a null value for the SDO_POINT attribute. ■ In the SDO_ELEM_INFO array (explained in Section 2.2.4), specify an additional triplet, with the second and third values (SDO_ETYPE and SDO_ INTERPRETATION) as 1 and 0. For example, a triplet of 3,1,0 indicates that the point is an oriented point, with the third number in the SDO_ORDINATES array being the first coordinate, or x-axis value, of the end point reflecting the orientation vector for any symbol or label. ■ In the SDO_ORDINATES array (explained in Section 2.2.5), specify the coordinates of the end point for the orientation vector from the point, with values between -1 and 1. The orientation start point is assumed to be (0,0), and it is translated to the location of the physical point to which it corresponds. Figure 2–8 illustrates an oriented point geometry at coordinates (12,14), with an orientation vector of approximately 34 degrees (counterclockwise from the x-axis), reflecting the orientation coordinates 0.3,0.2. (To have an orientation that more precisely matches a specific angle, refer to the cotangent or tangent values in the tables in a trigonometry textbook.) The orientation vector in this example goes from (0,0) to (0.3,0.2) and extends onward. Assuming i=0.3 and j=0.2, the angle in radians can be calculated as follows: angle in radians = arctan (j/i). The angle is then applied to the physical point associated with the orientation vector. Geometry Examples 2-28 Oracle Spatial Developer's Guide Figure 2–8 Oriented Point Geometry In the SDO_GEOMETRY definition of the geometry illustrated in Figure 2–8: ■ SDO_GTYPE = 2001. The 2 indicates two-dimensional, and the 1 indicates a single point. ■ SDO_SRID = NULL. ■ SDO_POINT = NULL. ■ SDO_ELEM_INFO = (1,1,1, 3,1,0). The final 1,0 in 3,1,0 indicates that this is an oriented point. ■ SDO_ORDINATES = (12,14, 0.3,0.2). The 12,14 identifies the physical coordinates of the point; and the 0.3,0.2 identifies the x and y coordinates (assuming 12,14 as the origin) of the end point of the orientation vector. The resulting orientation vector slopes upward at about a 34-degree angle. Example 2–12 shows a SQL statement that inserts the geometry illustrated in Figure 2–8 into the database. Example 2–12 SQL Statement to Insert an Oriented Point Geometry INSERT INTO cola_markets VALUES( 91, 'oriented_point', SDO_GEOMETRY( 2001, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1,1, 3,1,0), SDO_ORDINATE_ARRAY(12,14, 0.3,0.2))); The following guidelines apply to the definition of an oriented point: ■ The numbers defining the orientation vector must be between -1 and 1. (In Example 2–12, these numbers are 0.3 and 0.2.) ■ Multipoint oriented points are allowed (see Example 2–13), but the orientation information must follow the point being oriented. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (12,14, 0.3,0.2) Geometry Examples Spatial Data Types and Metadata 2-29 The following considerations apply to the dimensionality of the orientation vector for an oriented point: ■ A two-dimensional point has a two-dimensional orientation vector. ■ A two-dimensional point with an LRS measure (SDO_GTYPE=3301) has a two-dimensional orientation vector. ■ A three-dimensional point (SDO_GTYPE=3001) has a three-dimensional orientation vector. ■ A three-dimensional point with an LRS measure (SDO_GTYPE=4401) has a three-dimensional orientation vector. ■ A four-dimensional point (SDO_GTYPE=4001) has a three-dimensional orientation vector. Example 2–13 shows a SQL statement that inserts an oriented multipoint geometry into the database. The multipoint geometry contains two points, at coordinates (12,14) and (12, 10), with the two points having different orientation vectors. The statement is similar to the one in Example 2–12, but in Example 2–13 the second point has an orientation vector pointing down and to the left at 45 degrees (or, 135 degrees clockwise from the x-axis), reflecting the orientation coordinates -1,-1. Example 2–13 SQL Statement to Insert an Oriented Multipoint Geometry -- Oriented multipoint: 2 points, different orientations INSERT INTO cola_markets VALUES( 92, 'oriented_multipoint', SDO_GEOMETRY( 2005, -- Multipoint NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1,1, 3,1,0, 5,1,1, 7,1,0), SDO_ORDINATE_ARRAY(12,14, 0.3,0.2, 12,10, -1,-1))); 2.7.7 Type 0 (Zero) Element Type 0 (zero) elements are used to model geometry types that are not supported by Oracle Spatial, such as curves and splines. A type 0 element has an SDO_ETYPE value of 0. (See Section 2.2.4 for information about the SDO_ETYPE.) Type 0 elements are not indexed by Oracle Spatial, and they are ignored by Spatial functions and procedures. Geometries with type 0 elements must contain at least one nonzero element, that is, an element with an SDO_ETYPE value that is not 0. The nonzero element should be an approximation of the unsupported geometry, and therefore it must have both: ■ An SDO_ETYPE value associated with a geometry type supported by Spatial ■ An SDO_INTERPRETATION value that is valid for the SDO_ETYPE value (see Table 2–2) (The SDO_INTERPRETATION value for the type 0 element can be any numeric value, and applications are responsible for determining the validity and significance of the value.) The nonzero element is indexed by Spatial, and it will be returned by the spatial index. The SDO_GTYPE value for a geometry containing a type 0 element must be set to the value for the geometry type of the nonzero element. Geometry Examples 2-30 Oracle Spatial Developer's Guide Figure 2–9 shows a geometry with two elements: a curve (unsupported geometry) and a rectangle (the nonzero element) that approximates the curve. The curve looks like the letter S, and the rectangle is represented by the dashed line. Figure 2–9 Geometry with Type 0 (Zero) Element In the example shown in Figure 2–9: ■ The SDO_GTYPE value for the geometry is 2003 (for a two-dimensional polygon). ■ The SDO_ELEM_INFO array contains two triplets for this compound line string. For example, the triplets might be {(1,0,57), (11,1003,3)}. That is: In this example: ■ The type 0 element has an SDO_ETYPE value of 0. ■ The nonzero element (rectangle) has an SDO_ETYPE value of 1003, indicating an exterior polygon ring. ■ The nonzero element has an SDO_STARTING_OFFSET value of 11 because ordinate x6 is the eleventh ordinate in the geometry. ■ The type 0 element has an SDO_INTERPRETATION value whose significance is application-specific. In this example, the SDO_INTERPRETATION value is 57. ■ The nonzero element has an SDO_INTERPRETATION value that is valid for the SDO_ETYPE of 1003. In this example, the SDO_INTERPRETATION value is 3, indicating a rectangle defined by two points (lower-left and upper-right). Example 2–14 shows a SQL statement that inserts the geometry with a type 0 element (similar to the geometry illustrated in Figure 2–9) into the database. In the SDO_ ORDINATE_ARRAY structure, the curve is defined by points (6,6), (12,6), (9,8), (6,10), and (12,10), and the rectangle is defined by points (6,4) and (12,12). Example 2–14 SQL Statement to Insert a Geometry with a Type 0 Element INSERT INTO cola_markets VALUES( 13, 'type_zero_element_geom', SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, Ordinate Starting Offset (SDO_STARTING_OFFSET) Element Type (SDO_ETYPE) Interpretation (SDO_INTERPRETATION) 1057 11 1003 3 x1,y1 x2,y2 x3,y3 x4,y4 x5,y5 x6,y6 x7,y7 Geometry Examples Spatial Data Types and Metadata 2-31 NULL, SDO_ELEM_INFO_ARRAY(1,0,57, 11,1003,3), -- 1st is type 0 element SDO_ORDINATE_ARRAY(6,6, 12,6, 9,8, 6,10, 12,10, 6,4, 12,12) ) ); 2.7.8 Several Two-Dimensional Geometry Types Example 2–15 creates a table and inserts various two-dimensional geometries, including multipoints (point clusters), multipolygons, and collections. At the end, it calls the SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT function to validate the inserted geometries. Note that some geometries are deliberately invalid, and their descriptions include the string INVALID. Example 2–15 SQL Statements to Insert Various Two-Dimensional Geometries CREATE TABLE t1 ( i NUMBER, d VARCHAR2(50), g SDO_GEOMETRY ); INSERT INTO t1 (i, d, g) VALUES ( 1, 'Point', sdo_geometry (2001, null, null, sdo_elem_info_array (1,1,1), sdo_ordinate_array (10,5)) ); INSERT INTO t1 (i, d, g) VALUES ( 2, 'Line segment', sdo_geometry (2002, null, null, sdo_elem_info_array (1,2,1), sdo_ordinate_array (10,10, 20,10)) ); INSERT INTO t1 (i, d, g) VALUES ( 3, 'Arc segment', sdo_geometry (2002, null, null, sdo_elem_info_array (1,2,2), sdo_ordinate_array (10,15, 15,20, 20,15)) ); INSERT INTO t1 (i, d, g) VALUES ( 4, 'Line string', sdo_geometry (2002, null, null, sdo_elem_info_array (1,2,1), sdo_ordinate_array (10,25, 20,30, 25,25, 30,30)) ); INSERT INTO t1 (i, d, g) VALUES ( 5, 'Arc string', sdo_geometry (2002, null, null, sdo_elem_info_array (1,2,2), sdo_ordinate_array (10,35, 15,40, 20,35, 25,30, 30,35)) ); INSERT INTO t1 (i, d, g) VALUES ( 6, 'Compound line string', Geometry Examples 2-32 Oracle Spatial Developer's Guide sdo_geometry (2002, null, null, sdo_elem_info_array (1,4,3, 1,2,1, 3,2,2, 7,2,1), sdo_ordinate_array (10,45, 20,45, 23,48, 20,51, 10,51)) ); INSERT INTO t1 (i, d, g) VALUES ( 7, 'Closed line string', sdo_geometry (2002, null, null, sdo_elem_info_array (1,2,1), sdo_ordinate_array (10,55, 15,55, 20,60, 10,60, 10,55)) ); INSERT INTO t1 (i, d, g) VALUES ( 8, 'Closed arc string', sdo_geometry (2002, null, null, sdo_elem_info_array (1,2,2), sdo_ordinate_array (15,65, 10,68, 15,70, 20,68, 15,65)) ); INSERT INTO t1 (i, d, g) VALUES ( 9, 'Closed mixed line', sdo_geometry (2002, null, null, sdo_elem_info_array (1,4,2, 1,2,1, 7,2,2), sdo_ordinate_array (10,78, 10,75, 20,75, 20,78, 15,80, 10,78)) ); INSERT INTO t1 (i, d, g) VALUES ( 10, 'Self-crossing line', sdo_geometry (2002, null, null, sdo_elem_info_array (1,2,1), sdo_ordinate_array (10,85, 20,90, 20,85, 10,90, 10,85)) ); INSERT INTO t1 (i, d, g) VALUES ( 11, 'Polygon', sdo_geometry (2003, null, null, sdo_elem_info_array (1,1003,1), sdo_ordinate_array (10,105, 15,105, 20,110, 10,110, 10,105)) ); INSERT INTO t1 (i, d, g) VALUES ( 12, 'Arc polygon', sdo_geometry (2003, null, null, sdo_elem_info_array (1,1003,2), sdo_ordinate_array (15,115, 20,118, 15,120, 10,118, 15,115)) ); INSERT INTO t1 (i, d, g) VALUES ( 13, 'Compound polygon', sdo_geometry (2003, null, null, sdo_elem_info_array (1,1005,2, 1,2,1, 7,2,2), sdo_ordinate_array (10,128, 10,125, 20,125, 20,128, 15,130, 10,128)) ); INSERT INTO t1 (i, d, g) VALUES ( 14, 'Rectangle', sdo_geometry (2003, null, null, sdo_elem_info_array (1,1003,3), sdo_ordinate_array (10,135, 20,140)) ); Geometry Examples Spatial Data Types and Metadata 2-33 INSERT INTO t1 (i, d, g) VALUES ( 15, 'Circle', sdo_geometry (2003, null, null, sdo_elem_info_array (1,1003,4), sdo_ordinate_array (15,145, 10,150, 20,150)) ); INSERT INTO t1 (i, d, g) VALUES ( 16, 'Point cluster', sdo_geometry (2005, null, null, sdo_elem_info_array (1,1,3), sdo_ordinate_array (50,5, 55,7, 60,5)) ); INSERT INTO t1 (i, d, g) VALUES ( 17, 'Multipoint', sdo_geometry (2005, null, null, sdo_elem_info_array (1,1,1, 3,1,1, 5,1,1), sdo_ordinate_array (65,5, 70,7, 75,5)) ); INSERT INTO t1 (i, d, g) VALUES ( 18, 'Multiline', sdo_geometry (2006, null, null, sdo_elem_info_array (1,2,1, 5,2,1), sdo_ordinate_array (50,15, 55,15, 60,15, 65,15)) ); INSERT INTO t1 (i, d, g) VALUES ( 19, 'Multiline - crossing', sdo_geometry (2006, null, null, sdo_elem_info_array (1,2,1, 5,2,1), sdo_ordinate_array (50,22, 60,22, 55,20, 55,25)) ); INSERT INTO t1 (i, d, g) VALUES ( 20, 'Multiarc', sdo_geometry (2006, null, null, sdo_elem_info_array (1,2,2, 7,2,2), sdo_ordinate_array (50,35, 55,40, 60,35, 65,35, 70,30, 75,35)) ); INSERT INTO t1 (i, d, g) VALUES ( 21, 'Multiline - closed', sdo_geometry (2006, null, null, sdo_elem_info_array (1,2,1, 9,2,1), sdo_ordinate_array (50,55, 50,60, 55,58, 50,55, 56,58, 60,55, 60,60, 56,58)) ); INSERT INTO t1 (i, d, g) VALUES ( 22, 'Multiarc - touching', sdo_geometry (2006, null, null, sdo_elem_info_array (1,2,2, 7,2,2), sdo_ordinate_array (50,65, 50,70, 55,68, 55,68, 60,65, 60,70)) ); INSERT INTO t1 (i, d, g) VALUES ( 23, 'Multipolygon - disjoint', Geometry Examples 2-34 Oracle Spatial Developer's Guide sdo_geometry (2007, null, null, sdo_elem_info_array (1,1003,1, 11,1003,3), sdo_ordinate_array (50,105, 55,105, 60,110, 50,110, 50,105, 62,108, 65,112)) ); INSERT INTO t1 (i, d, g) VALUES ( 24, 'Multipolygon - touching', sdo_geometry (2007, null, null, sdo_elem_info_array (1,1003,3, 5,1003,3), sdo_ordinate_array (50,115, 55,120, 55,120, 58,122)) ); INSERT INTO t1 (i, d, g) VALUES ( 25, 'Multipolygon - tangent * INVALID 13351', sdo_geometry (2007, null, null, sdo_elem_info_array (1,1003,3, 5,1003,3), sdo_ordinate_array (50,125, 55,130, 55,128, 60,132)) ); INSERT INTO t1 (i, d, g) VALUES ( 26, 'Multipolygon - multi-touch', sdo_geometry (2007, null, null, sdo_elem_info_array (1,1003,1, 17,1003,1), sdo_ordinate_array (50,95, 55,95, 53,96, 55,97, 53,98, 55,99, 50,99, 50,95, 55,100, 55,95, 60,95, 60,100, 55,100)) ); INSERT INTO t1 (i, d, g) VALUES ( 27, 'Polygon with void', sdo_geometry (2003, null, null, sdo_elem_info_array (1,1003,3, 5,2003,3), sdo_ordinate_array (50,135, 60,140, 51,136, 59,139)) ); INSERT INTO t1 (i, d, g) VALUES ( 28, 'Polygon with void - reverse', sdo_geometry (2003, null, null, sdo_elem_info_array (1,2003,3, 5,1003,3), sdo_ordinate_array (51,146, 59,149, 50,145, 60,150)) ); INSERT INTO t1 (i, d, g) VALUES ( 29, 'Crescent (straight lines) * INVALID 13349', sdo_geometry (2003, null, null, sdo_elem_info_array (1,1003,1), sdo_ordinate_array (10,175, 10,165, 20,165, 15,170, 25,170, 20,165, 30,165, 30,175, 10,175)) ); INSERT INTO t1 (i, d, g) VALUES ( 30, 'Crescent (arcs) * INVALID 13349', sdo_geometry (2003, null, null, sdo_elem_info_array (1,1003,2), sdo_ordinate_array (14,180, 10,184, 14,188, 18,184, 14,180, 16,182, 14,184, 12,182, 14,180)) ); INSERT INTO t1 (i, d, g) VALUES ( 31, 'Heterogeneous collection', sdo_geometry (2004, null, null, sdo_elem_info_array (1,1,1, 3,2,1, 7,1003,1), Geometry Examples Spatial Data Types and Metadata 2-35 sdo_ordinate_array (10,5, 10,10, 20,10, 10,105, 15,105, 20,110, 10,110, 10,105)) ); INSERT INTO t1 (i, d, g) VALUES ( 32, 'Polygon+void+island touch', sdo_geometry (2007, null, null, sdo_elem_info_array (1,1003,1, 11,2003,1, 31,1003,1), sdo_ordinate_array (50,168, 50,160, 55,160, 55,168, 50,168, 51,167, 54,167, 54,161, 51,161, 51,162, 52,163, 51,164, 51,165, 51,166, 51,167, 52,166, 52,162, 53,162, 53,166, 52,166)) ); COMMIT; SELECT i, d, SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT (g, 0.5) FROM t1; 2.7.9 Three-Dimensional Geometry Types Example 2–16 creates several tables (POINTS3D, LINES3D, and POLYGONS3D), and inserts three-dimensional objects into each table as appropriate (points into POINTS3D; lines into LINES3D; and polygons, surfaces, and solids into POLYGONS3D). Example 2–17 then creates the metadata and spatial indexes for the tables. For information about support for three-dimensional geometries, see Section 1.11. Example 2–16 SQL Statements to Insert Three-Dimensional Geometries create table points3d(id number, geometry sdo_geometry); insert into points3d values(1, sdo_geometry(3001,null, sdo_point_type(0,0,0), null, null)); insert into points3d values(2, sdo_geometry(3001,null, sdo_point_type(1,1,1), null, null)); insert into points3d values(3, sdo_geometry(3001,null, sdo_point_type(0,1,1), null, null)); insert into points3d values(4, sdo_geometry(3001,null, sdo_point_type(0,0,1), null, null)); insert into points3d values(5, sdo_geometry(3001,null, sdo_point_type(1,1,0), null, null)); insert into points3d values(6, sdo_geometry(3001,null, sdo_point_type(1,0,1), null, null)); insert into points3d values(7, sdo_geometry(3001,null, sdo_point_type(1,0,0), null, null)); insert into points3d values(8, sdo_geometry(3001,null, sdo_point_type(0,1,0), null, null)); insert into points3d values(9, sdo_geometry(3005,null, null, sdo_elem_info_array(1,1,1, 4,1,1), sdo_ordinate_array(1,1,1, 0,0,0))); create table lines3d(id number, geometry sdo_geometry); insert into lines3d values(1, sdo_geometry(3002,null, null, sdo_elem_info_array(1,2,1), sdo_ordinate_array(1,1,1, 0,0,0))); insert into lines3d values(2, sdo_geometry(3002,null, null, sdo_elem_info_array(1,2,1), sdo_ordinate_array(1,0,1, 0,1,0))); insert into lines3d values(2, sdo_geometry(3002,null, null, sdo_elem_info_array(1,2,1), sdo_ordinate_array(0,1,1, 1,0,0))); insert into lines3d values(3, sdo_geometry(3002,null, null, Geometry Examples 2-36 Oracle Spatial Developer's Guide sdo_elem_info_array(1,2,1), sdo_ordinate_array(0,1,1, 1,0,0))); insert into lines3d values(4, sdo_geometry(3002,null, null, sdo_elem_info_array(1,2,1), sdo_ordinate_array(0,1,0, 1,0,1))); create table polygons3d(id number, geometry sdo_geometry); -- Simple Polygon -- All points have to be on the same plane. insert into polygons3d values(1, SDO_Geometry (3003,NULL,NULL , SDO_Elem_Info_Array(1,1003,1), SDO_Ordinate_Array(0.5,0.0,0.0, 0.5,1.0,0.0, 0.0,1.0,1.0, 0.0,0.0,1.0, 0.5,0.0,0.0 ))); insert into polygons3d values(2, SDO_Geometry (3003,NULL,NULL , SDO_Elem_Info_Array(1,1003,1), SDO_Ordinate_Array(6.0,6.0,6.0, 5.0,6.0,10.0, 3.0,4.0,8.0, 4.0,4.0,4.0, 6.0,6.0,6.0 ))); insert into polygons3d values(3, SDO_Geometry (3007,NULL,NULL , SDO_Elem_Info_Array(1,1003,1,16,1003,1), SDO_Ordinate_Array(6.0,6.0,6.0, 5.0,6.0,10.0, 3.0,4.0,8.0, 4.0,4.0,4.0, 6.0,6.0,6.0, 0.5,0.0,0.0, 0.5,1.0,0.0, 0.0,1.0,1.0, 0.0,0.0,1.0, 0.5,0.0,0.0 ))); -- Polygon with a Hole (same rules as 2D) plus all points on the same plane insert into polygons3d values(4, SDO_Geometry (3003,NULL,NULL , SDO_Elem_Info_Array(1,1003,1,16,2003,1), SDO_Ordinate_Array(0.5,0.0,0.0, 0.5,1.0,0.0, 0.0,1.0,1.0, 0.0,0.0,1.0, 0.5,0.0,0.0, 0.25,0.5,0.5, 0.15,0.5,0.7, 0.15,0.6,0.7, 0.25,0.6,0.5, 0.25,0.5,0.5 ))); -- Surface with 2 3D polygons (on same plane) insert into polygons3d values(5, SDO_Geometry (3003,NULL,NULL , Geometry Examples Spatial Data Types and Metadata 2-37 SDO_Elem_Info_Array(1,1006,2,1,1003,1,16,1003,1), SDO_Ordinate_Array(0.5,0.0,0.0, 0.5,1.0,0.0, 0.0,1.0,0.0, 0.0,0.0,0.0, 0.5,0.0,0.0, 1.5,0.0,0.0, 2.5,1.0,0.0, 1.5,2.0,0.0, 0.5,2.0,0.0, 0.5,0.0,0.0, 1.5,0.0,0.0 ))); -- Surface with 2 3D polygons (on two planes) insert into polygons3d values(5, SDO_Geometry(3003,NULL,NULL , SDO_Elem_Info_Array(1,1006,2,1,1003,3,7,1003,3), SDO_Ordinate_Array(2,2,2, 4,4,2, 2,2,2, 4,2,4 ))); -- Surface with 2 3D polygons -- First polygon has one ext and one int. insert into polygons3d values(6, SDO_Geometry (3003,NULL,NULL , SDO_Elem_Info_Array(1,1006,2,1,1003,1,16,2003,1,31,1003,1), SDO_Ordinate_Array(0.5,0.0,0.0, 0.5,1.0,0.0, 0.0,1.0,1.0, 0.0,0.0,1.0, 0.5,0.0,0.0, 0.25,0.5,0.5, 0.15,0.5,0.7, 0.15,0.6,0.7, 0.25,0.6,0.5, 0.25,0.5,0.5, 1.5,0.0,0.0, 2.5,1.0,0.0, 1.5,2.0,0.0, 0.5,2.0,0.0, 0.5,0.0,0.0, 1.5,0.0,0.0 ))); --3D Surface with 3 3D polygons insert into polygons3d values(7, SDO_Geometry (3003,NULL,NULL , SDO_Elem_Info_Array(1,1006,3,1,1003,1,16,1003,1,34,1003,1), SDO_Ordinate_Array(0.5,0.0,0.0, 0.5,1.0,0.0, 0.0,1.0,1.0, 0.0,0.0,1.0, 0.5,0.0,0.0, 1.5,0.0,0.0, 2.5,1.0,0.0, 1.5,2.0,0.0, 0.5,2.0,0.0, 0.5,0.0,0.0, 1.5,0.0,0.0, 1.5,0.0,0.0, Geometry Examples 2-38 Oracle Spatial Developer's Guide 2.5,0.0,0.0, 2.5,1.0,0.0, 1.5,0.0,0.0 ))); -- 3D surface with 3 3D polygons insert into polygons3d values(8, SDO_Geometry (3003,NULL,NULL , SDO_Elem_Info_Array(1,1006,3,1,1003,1,16,2003,1,31,1003,1,49,1003,1), SDO_Ordinate_Array(0.5,0.0,0.0, 0.5,1.0,0.0, 0.0,1.0,1.0, 0.0,0.0,1.0, 0.5,0.0,0.0, 0.25,0.5,0.5, 0.15,0.5,0.7, 0.15,0.6,0.7, 0.25,0.6,0.5, 0.25,0.5,0.5, 1.5,0.0,0.0, 2.5,1.0,0.0, 1.5,2.0,0.0, 0.5,2.0,0.0, 0.5,0.0,0.0, 1.5,0.0,0.0, 0.5,1.0,0.0, 0.5,2.0,0.0, 0.0,2.0,0.0, 0.0,1.0,0.0, 0.5,1.0,0.0 ))); -- Simple 3D polygon insert into polygons3d values(9, SDO_Geometry (3003,NULL,NULL , SDO_Elem_Info_Array(1,1003,1), SDO_Ordinate_Array(0.0,-4.0,1.0, 4.0,-4.0,1.0, 5.0,-3.0,1.0, 5.0,0.0,1.0, 3.0,1.0,1.0, -1.0,1.0,1.0, -3.0,0.5,1.0, 0.0,0.0,1.0, -6.0,-2.0,1.0, -6.0,-3.5,1.0, -2.0,-3.5,1.0, 0.0,-4.0,1.0 ))); -- SOLID with 6 polygons insert into polygons3d values(10, SDO_Geometry (3008,NULL,NULL , SDO_Elem_Info_ Array(1,1007,1,1,1006,6,1,1003,1,16,1003,1,31,1003,1,46,1003,1,61,1003,1,76,1003,1 ), SDO_Ordinate_Array(1.0,0.0,-1.0, 1.0,1.0,-1.0, 1.0,1.0,1.0, 1.0,0.0,1.0, 1.0,0.0,-1.0, 1.0,0.0,1.0, 0.0,0.0,1.0, Geometry Examples Spatial Data Types and Metadata 2-39 0.0,0.0,-1.0, 1.0,0.0,-1.0, 1.0,0.0,1.0, 0.0,1.0,1.0, 0.0,1.0,-1.0, 0.0,0.0,-1.0, 0.0,0.0,1.0, 0.0,1.0,1.0, 1.0,1.0,-1.0, 0.0,1.0,-1.0, 0.0,1.0,1.0, 1.0,1.0,1.0, 1.0,1.0,-1.0, 1.0,1.0,1.0, 0.0,1.0,1.0, 0.0,0.0,1.0, 1.0,0.0,1.0, 1.0,1.0,1.0, 1.0,1.0,-1.0, 1.0,0.0,-1.0, 0.0,0.0,-1.0, 0.0,1.0,-1.0, 1.0,1.0,-1.0 ))); -- Simple SOLID with 6 polygons -- All polygons are described using the optimized rectangle representation. insert into polygons3d values(11, SDO_Geometry (3008,NULL,NULL , SDO_Elem_Info_ Array(1,1007,1,1,1006,6,1,1003,3,7,1003,3,13,1003,3,19,1003,3,25,1003,3,31,1003,3) , SDO_Ordinate_Array(1.0,0.0,-1.0, 1.0,1.0,1.0, 1.0,0.0,1.0, 0.0,0.0,-1.0, 0.0,1.0,1.0, 0.0,0.0,-1.0, 0.0,1.0,-1.0, 1.0,1.0,1.0, 0.0,0.0,1.0, 1.0,1.0,1.0, 1.0,1.0,-1.0, 0.0,0.0,-1.0 ))); -- Multi-Solid -- Both solids use optimized representation. insert into polygons3d values(12, SDO_Geometry (3009,NULL,NULL , SDO_Elem_Info_Array(1,1007,3,7,1007,3), SDO_Ordinate_Array(-2.0,1.0,3.0, -3.0,-1.0,0.0, 0.0,0.0,0.0, 1.0,1.0,1.0 ))); -- Multi-Solid - like multi-polygon in 2D -- disjoint solids insert into polygons3d values(13, SDO_Geometry (3009,NULL,NULL , SDO_Elem_Info_ Array(1,1007,1,1,1006,6,1,1003,1,16,1003,1,31,1003,1,46,1003,1,61,1003,1,76,1003,1 ,91,1007,1,91,1006,7,91,1003,1,106,1003,1,121,1003,1,136,1003,1,151,1003,1,166,100 3,1,184,1003,1), Geometry Examples 2-40 Oracle Spatial Developer's Guide SDO_Ordinate_Array(1.0,0.0,4.0, 1.0,1.0,4.0, 1.0,1.0,6.0, 1.0,0.0,6.0, 1.0,0.0,4.0, 1.0,0.0,6.0, 0.0,0.0,6.0, 0.0,0.0,4.0, 1.0,0.0,4.0, 1.0,0.0,6.0, 0.0,1.0,6.0, 0.0,1.0,4.0, 0.0,0.0,4.0, 0.0,0.0,6.0, 0.0,1.0,6.0, 1.0,1.0,4.0, 0.0,1.0,4.0, 0.0,1.0,6.0, 1.0,1.0,6.0, 1.0,1.0,4.0, 1.0,1.0,6.0, 0.0,1.0,6.0, 0.0,0.0,6.0, 1.0,0.0,6.0, 1.0,1.0,6.0, 1.0,1.0,4.0, 1.0,0.0,4.0, 0.0,0.0,4.0, 0.0,1.0,4.0, 1.0,1.0,4.0, 2.0,0.0,3.0, 2.0,0.0,0.0, 4.0,2.0,0.0, 4.0,2.0,3.0, 2.0,0.0,3.0, 4.5,-2.0,3.0, 4.5,-2.0,0.0, 2.0,0.0,0.0, 2.0,0.0,3.0, 4.5,-2.0,3.0, 4.5,-2.0,3.0, -2.0,-2.0,3.0, -2.0,-2.0,0.0, 4.5,-2.0,0.0, 4.5,-2.0,3.0, -2.0,-2.0,3.0, -2.0,2.0,3.0, -2.0,2.0,0.0, -2.0,-2.0,0.0, -2.0,-2.0,3.0, 4.0,2.0,3.0, 4.0,2.0,0.0, -2.0,2.0,0.0, -2.0,2.0,3.0, 4.0,2.0,3.0, 2.0,0.0,3.0, 4.0,2.0,3.0, -2.0,2.0,3.0, -2.0,-2.0,3.0, 4.5,-2.0,3.0, Geometry Examples Spatial Data Types and Metadata 2-41 2.0,0.0,3.0, 2.0,0.0,0.0, 4.5,-2.0,0.0, -2.0,-2.0,0.0, -2.0,2.0,0.0, 4.0,2.0,0.0, 2.0,0.0,0.0 ))); -- SOLID with a hole -- etype = 1007 exterior solid -- etype = 2007 is interior solid -- All polygons of etype=2007 are described as 2003's. insert into polygons3d values(14, SDO_Geometry (3008,NULL,NULL , SDO_Elem_Info_ Array(1,1007,1,1,1006,7,1,1003,1,16,1003,1,31,1003,1,46,1003,1,61,1003,1,76,1003,1 ,94,1003,1,112,2006,6,112,2003,1,127,2003,1,142,2003,1,157,2003,1,172,2003,1,187,2 003,1), SDO_Ordinate_Array(2.0,0.0,3.0, 2.0,0.0,0.0, 4.0,2.0,0.0, 4.0,2.0,3.0, 2.0,0.0,3.0, 4.5,-2.0,3.0, 4.5,-2.0,0.0, 2.0,0.0,0.0, 2.0,0.0,3.0, 4.5,-2.0,3.0, 4.5,-2.0,3.0, -2.0,-2.0,3.0, -2.0,-2.0,0.0, 4.5,-2.0,0.0, 4.5,-2.0,3.0, -2.0,-2.0,3.0, -2.0,2.0,3.0, -2.0,2.0,0.0, -2.0,-2.0,0.0, -2.0,-2.0,3.0, 4.0,2.0,3.0, 4.0,2.0,0.0, -2.0,2.0,0.0, -2.0,2.0,3.0, 4.0,2.0,3.0, 2.0,0.0,3.0, 4.0,2.0,3.0, -2.0,2.0,3.0, -2.0,-2.0,3.0, 4.5,-2.0,3.0, 2.0,0.0,3.0, 2.0,0.0,0.0, 4.5,-2.0,0.0, -2.0,-2.0,0.0, -2.0,2.0,0.0, 4.0,2.0,0.0, 2.0,0.0,0.0, 1.0,1.0,2.5, -1.0,1.0,2.5, -1.0,1.0,0.5, 1.0,1.0,0.5, Geometry Examples 2-42 Oracle Spatial Developer's Guide 1.0,1.0,2.5, -1.0,1.0,2.5, -1.0,-1.0,2.5, -1.0,-1.0,0.5, -1.0,1.0,0.5, -1.0,1.0,2.5, -1.0,-1.0,2.5, 1.0,-1.0,2.5, 1.0,-1.0,0.5, -1.0,-1.0,0.5, -1.0,-1.0,2.5, 1.0,-1.0,2.5, 1.0,1.0,2.5, 1.0,1.0,0.5, 1.0,-1.0,0.5, 1.0,-1.0,2.5, -1.0,-1.0,2.5, -1.0,1.0,2.5, 1.0,1.0,2.5, 1.0,-1.0,2.5, -1.0,-1.0,2.5, 1.0,1.0,0.5, -1.0,1.0,0.5, -1.0,-1.0,0.5, 1.0,-1.0,0.5, 1.0,1.0,0.5 ))); -- Gtype = SOLID -- The elements make up one composite solid (non-disjoint solids) like a cube -- on a cube on a cube. -- This is made up of two solid elements. -- Each solid element here is a simple solid. insert into polygons3d values(15, SDO_Geometry (3008,NULL,NULL , SDO_Elem_Info_ Array(1,1008,2,1,1007,1,1,1006,6,1,1003,1,16,1003,1,31,1003,1,46,1003,1,61,1003,1, 76,1003,1,91,1007,1,91,1006,7,91,1003,1,106,1003,1,121,1003,1,136,1003,1,151,1003, 1,166,1003,1,184,1003,1), SDO_Ordinate_Array(-2.0,1.0,3.0, -2.0,1.0,0.0, -3.0,1.0,0.0, -3.0,1.0,3.0, -2.0,1.0,3.0, -3.0,1.0,3.0, -3.0,1.0,0.0, -3.0,-1.0,0.0, -3.0,-1.0,3.0, -3.0,1.0,3.0, -3.0,-1.0,3.0, -3.0,-1.0,0.0, -2.0,-1.0,0.0, -2.0,-1.0,3.0, -3.0,-1.0,3.0, -2.0,-1.0,3.0, -2.0,-1.0,0.0, -2.0,1.0,0.0, -2.0,1.0,3.0, -2.0,-1.0,3.0, -2.0,-1.0,3.0, -2.0,1.0,3.0, Geometry Examples Spatial Data Types and Metadata 2-43 -3.0,1.0,3.0, -3.0,-1.0,3.0, -2.0,-1.0,3.0, -2.0,1.0,0.0, -2.0,-1.0,0.0, -3.0,-1.0,0.0, -3.0,1.0,0.0, -2.0,1.0,0.0, 2.0,0.0,3.0, 2.0,0.0,0.0, 4.0,2.0,0.0, 4.0,2.0,3.0, 2.0,0.0,3.0, 4.5,-2.0,3.0, 4.5,-2.0,0.0, 2.0,0.0,0.0, 2.0,0.0,3.0, 4.5,-2.0,3.0, 4.5,-2.0,3.0, -2.0,-2.0,3.0, -2.0,-2.0,0.0, 4.5,-2.0,0.0, 4.5,-2.0,3.0, -2.0,-2.0,3.0, -2.0,2.0,3.0, -2.0,2.0,0.0, -2.0,-2.0,0.0, -2.0,-2.0,3.0, 4.0,2.0,3.0, 4.0,2.0,0.0, -2.0,2.0,0.0, -2.0,2.0,3.0, 4.0,2.0,3.0, 2.0,0.0,3.0, 4.0,2.0,3.0, -2.0,2.0,3.0, -2.0,-2.0,3.0, 4.5,-2.0,3.0, 2.0,0.0,3.0, 2.0,0.0,0.0, 4.5,-2.0,0.0, -2.0,-2.0,0.0, -2.0,2.0,0.0, 4.0,2.0,0.0, 2.0,0.0,0.0 ))); Example 2–17 updates the USER_SDO_GEOM_METADATA view with the necessary information about the tables created in Example 2–16 (POINTS3D, LINES3D, and POLYGONS3D), and it creates a spatial index on the geometry column (named GEOMETRY) in each table. The indexes are created with the PARAMETERS ('sdo_ indx_dims=3') clause, to ensure that all three dimensions are considered in operations that are supported on three-dimensional geometries. Example 2–17 Updating Metadata and Creating Indexes for 3-Dimensional Geometries INSERT INTO user_sdo_geom_metadata VALUES('POINTS3D', 'GEOMETRY', sdo_dim_array( sdo_dim_element('X', -100,100, 0.000005), sdo_dim_element('Y', -100,100, 0.000005), sdo_dim_element('Z', -100,100, 0.000005)), NULL); Geometry Metadata Views 2-44 Oracle Spatial Developer's Guide CREATE INDEX points3d_sidx on points3d(geometry) INDEXTYPE IS mdsys.spatial_index PARAMETERS ('sdo_indx_dims=3'); INSERT INTO user_sdo_geom_metadata VALUES('LINES3D', 'GEOMETRY', sdo_dim_array( sdo_dim_element('X', -100,100, 0.000005), sdo_dim_element('Y', -100,100, 0.000005), sdo_dim_element('Z', -100,100, 0.000005)), NULL); CREATE INDEX lines3d_sidx on lines3d(geometry) INDEXTYPE IS mdsys.spatial_index PARAMETERS ('sdo_indx_dims=3'); INSERT INTO user_sdo_geom_metadata VALUES('POLYGONS3D', 'GEOMETRY', sdo_dim_array( sdo_dim_element('X', -100,100, 0.000005), sdo_dim_element('Y', -100,100, 0.000005), sdo_dim_element('Z', -100,100, 0.000005)), NULL); CREATE INDEX polygons3d_sidx on polygons3d(geometry) INDEXTYPE IS mdsys.spatial_index PARAMETERS ('sdo_indx_dims=3'); 2.8 Geometry Metadata Views The geometry metadata describing the dimensions, lower and upper bounds, and tolerance in each dimension is stored in a global table owned by MDSYS (which users should never directly update). Each Spatial user has the following views available in the schema associated with that user: ■ USER_SDO_GEOM_METADATA contains metadata information for all spatial tables owned by the user (schema). This is the only view that you can update, and it is the one in which Spatial users must insert metadata related to spatial tables. ■ ALL_SDO_GEOM_METADATA contains metadata information for all spatial tables on which the user has SELECT permission. Spatial users are responsible for populating these views. For each spatial column, you must insert an appropriate row into the USER_SDO_GEOM_METADATA view. Oracle Spatial ensures that the ALL_SDO_GEOM_METADATA view is also updated to reflect the rows that you insert into USER_SDO_GEOM_METADATA. Each metadata view has the following definition: ( TABLE_NAME VARCHAR2(32), COLUMN_NAME VARCHAR2(32), DIMINFO SDO_DIM_ARRAY, SRID NUMBER ); In addition, the ALL_SDO_GEOM_METADATA view has an OWNER column identifying the schema that owns the table specified in TABLE_NAME. The following considerations apply to schema, table, and column names that are stored in any Oracle Spatial metadata views: ■ The name must contain only letters, numbers, and underscores. For example, the name cannot contain a space ( ), an apostrophe ('), a quotation mark ("), or a comma (,). Geometry Metadata Views Spatial Data Types and Metadata 2-45 ■ All letters in the names are converted to uppercase before the names are stored in geometry metadata views or before the tables are accessed. This conversion also applies to any schema name specified with the table name. 2.8.1 TABLE_NAME The TABLE_NAME column contains the name of a feature table, such as COLA_ MARKETS, that has a column of type SDO_GEOMETRY. The table name is stored in the spatial metadata views in all uppercase characters. The table name cannot contain spaces or mixed-case letters in a quoted string when inserted into the USER_SDO_GEOM_METADATA view, and it cannot be in a quoted string when used in a query (unless it is in all uppercase characters). The spatial feature table cannot be an index-organized table if you plan to create a spatial index on the spatial column. 2.8.2 COLUMN_NAME The COLUMN_NAME column contains the name of the column of type SDO_ GEOMETRY. For the COLA_MARKETS table, this column is called SHAPE. The column name is stored in the spatial metadata views in all uppercase characters. The column name cannot contain spaces or mixed-case letters in a quoted string when inserted into the USER_SDO_GEOM_METADATA view, and it cannot be in a quoted string when used in a query (unless it is in all uppercase characters). 2.8.3 DIMINFO The DIMINFO column is a varying length array of an object type, ordered by dimension, and has one entry for each dimension. The SDO_DIM_ARRAY type is defined as follows: Create Type SDO_DIM_ARRAY as VARRAY(4) of SDO_DIM_ELEMENT; The SDO_DIM_ELEMENT type is defined as: Create Type SDO_DIM_ELEMENT as OBJECT ( SDO_DIMNAME VARCHAR2(64), SDO_LB NUMBER, SDO_UB NUMBER, SDO_TOLERANCE NUMBER); The SDO_DIM_ARRAY instance is of size n if there are n dimensions. That is, DIMINFO contains 2 SDO_DIM_ELEMENT instances for two-dimensional geometries, 3 instances for three-dimensional geometries, and 4 instances for four-dimensional geometries. Each SDO_DIM_ELEMENT instance in the array must have valid (not null) values for the SDO_LB, SDO_UB, and SDO_TOLERANCE attributes. For an explanation of tolerance and how to determine the appropriate SDO_ TOLERANCE value, see Section 1.5.5, especially Section 1.5.5.1. Note: The number of dimensions reflected in the DIMINFO information must match the number of dimensions of each geometry object in the layer. Spatial Index-Related Structures 2-46 Oracle Spatial Developer's Guide Spatial assumes that the varying length array is ordered by dimension. The DIMINFO varying length array must be ordered by dimension in the same way the ordinates for the points in SDO_ORDINATES varying length array are ordered. For example, if the SDO_ORDINATES varying length array contains {X1, Y1, ..., Xn, Yn}, then the first DIMINFO entry must define the X dimension and the second DIMINFO entry must define the Y dimension. Example 2–1 in Section 2.1 shows the use of the SDO_GEOMETRY and SDO_DIM_ ARRAY types. This example demonstrates how geometry objects (hypothetical market areas for colas) are represented, and how the COLA_MARKETS feature table and the USER_SDO_GEOM_METADATA view are populated with the data for those objects. 2.8.4 SRID The SRID column should contain either of the following: the SRID value for the coordinate system for all geometries in the column, or NULL if no specific coordinate system should be associated with the geometries. (For information about coordinate systems, see Chapter 6.) 2.9 Spatial Index-Related Structures This section describes the structure of the tables containing the spatial index data and metadata. Concepts and usage notes for spatial indexing are explained in Section 1.7. The spatial index data and metadata are stored in tables that are created and maintained by the Spatial indexing routines. These tables are created in the schema of the owner of the feature (underlying) table that has a spatial index created on a column of type SDO_GEOMETRY. 2.9.1 Spatial Index Views There are two sets of spatial index metadata views for each schema (user): xxx_SDO_ INDEX_INFO and xxx_SDO_INDEX_METADATA, where xxx can be USER or ALL. These views are read-only to users; they are created and maintained by the Spatial indexing routines. 2.9.1.1 xxx_SDO_INDEX_INFO Views The following views contain basic information about spatial indexes: ■ USER_SDO_INDEX_INFO contains index information for all spatial tables owned by the user. ■ ALL_SDO_INDEX_INFO contains index information for all spatial tables on which the user has SELECT permission. The USER_SDO_INDEX_INFO and ALL_SDO_INDEX_INFO views contain the same columns, as shown Table 2–8, except that the USER_SDO_INDEX_INFO view does not contain the SDO_INDEX_OWNER column. (The columns are listed in their order in the view definition.) Table 2–8 Columns in the xxx_SDO_INDEX_INFO Views Column Name Data Type Purpose SDO_INDEX_OWNER VARCHAR 2 Owner of the index (ALL_SDO_INDEX_INFO view only). INDEX_NAME VARCHAR 2 Name of the index. Spatial Index-Related Structures Spatial Data Types and Metadata 2-47 2.9.1.2 xxx_SDO_INDEX_METADATA Views The following views contain detailed information about spatial index metadata: ■ USER_SDO_INDEX_METADATA contains index information for all spatial tables owned by the user. ■ ALL_SDO_INDEX_METADATA contains index information for all spatial tables on which the user has SELECT permission. The USER_SDO_INDEX_METADATA and ALL_SDO_INDEX_METADATA views contain the same columns, as shown Table 2–9. (The columns are listed in their order in the view definition.) TABLE_NAME VARCHAR 2 Name of the table containing the column on which this index is built. COLUMN_NAME VARCHAR 2 Name of the column on which this index is built. SDO_INDEX_TYPE VARCHAR 2 Contains RTREE (for an R-tree index). SDO_INDEX_TABLE VARCHAR 2 Name of the spatial index table (described in Section 2.9.2). SDO_INDEX_STATUS VARCHAR 2 (Deprecated; reserved for Oracle use.) Table 2–9 Columns in the xxx_SDO_INDEX_METADATA Views Column Name Data Type Purpose SDO_INDEX_OWNER VARCHAR2 Owner of the index. SDO_INDEX_TYPE VARCHAR2 Contains RTREE (for an R-tree index). SDO_LEVEL NUMBER (No longer relevant; applies to a deprecated feature.) SDO_NUMTILES NUMBER (No longer relevant; applies to a deprecated feature.) SDO_MAXLEVEL NUMBER (No longer relevant; applies to a deprecated feature.) SDO_COMMIT_ INTERVAL NUMBER (No longer relevant; applies to a deprecated feature.) SDO_INDEX_TABLE VARCHAR2 Name of the spatial index table (described in Section 2.9.2). SDO_INDEX_NAME VARCHAR2 Name of the index. SDO_INDEX_PRIMARY NUMBER Indicates if this is a primary or secondary index. 1 = primary, 2 = secondary. SDO_TSNAME VARCHAR2 Schema name of the SDO_INDEX_TABLE. SDO_COLUMN_NAME VARCHAR2 Name of the column on which this index is built. SDO_RTREE_HEIGHT NUMBER Height of the R-tree. SDO_RTREE_NUM_ NODES NUMBER Number of nodes in the R-tree. Table 2–8 (Cont.) Columns in the xxx_SDO_INDEX_INFO Views Column Name Data Type Purpose Spatial Index-Related Structures 2-48 Oracle Spatial Developer's Guide SDO_RTREE_ DIMENSIONALITY NUMBER Number of dimensions used internally by Spatial. This may be different from the number of dimensions indexed, which is controlled by the sdo_indx_dims keyword in the CREATE INDEX or ALTER INDEX statement, and which is stored in the SDO_INDEX_DIMS column in this view. For example, for an index on geodetic data, the SDO_RTREE_DIMENSIONALITY value is 3, but the SDO_INDEX_DIMS value is 2. SDO_RTREE_FANOUT NUMBER Maximum number of children in each R-tree node. SDO_RTREE_ROOT VARCHAR2 Rowid corresponding to the root node of the R-tree in the index table. SDO_RTREE_SEQ_NAME VARCHAR2 Sequence name associated with the R-tree. SDO_FIXED_META RAW If applicable, this column contains the metadata portion of the SDO_GROUPCODE or SDO_ CODE for a fixed-level index. SDO_TABLESPACE VARCHAR2 Same as in the SQL CREATE TABLE statement. Tablespace in which to create the SDOINDEX table. SDO_INITIAL_EXTENT VARCHAR2 Same as in the SQL CREATE TABLE statement. SDO_NEXT_EXTENT VARCHAR2 Same as in the SQL CREATE TABLE statement. SDO_PCTINCREASE NUMBER Same as in the SQL CREATE TABLE statement. SDO_MIN_EXTENTS NUMBER Same as in the SQL CREATE TABLE statement. SDO_MAX_EXTENTS NUMBER Same as in the SQL CREATE TABLE statement. SDO_INDEX_DIMS NUMBER Number of dimensions of the geometry objects in the column on which this index is built, as determined by the value of the sdo_indx_dims keyword in the CREATE INDEX or ALTER INDEX statement. SDO_LAYER_GTYPE VARCHAR2 Contains DEFAULT if the layer can contain both point and polygon data, or a value from the Geometry Type column of Table 2–1 in Section 2.2.1. SDO_RTREE_PCTFREE NUMBER Minimum percentage of slots in each index tree node to be left empty when an R-tree index is created. SDO_INDEX_PARTITION VARCHAR2 For a partitioned index, name of the index partition. SDO_PARTITIONED NUMBER Contains 0 if the index is not partitioned or 1 if the index is partitioned. SDO_RTREE_QUALITY NUMBER Quality score for an index. See the information about R-tree quality in Section 1.7.2. SDO_INDEX_VERSION NUMBER Internal version number of the index. SDO_INDEX_GEODETIC VARCHAR2 Contains TRUE if the index is geodetic and FALSE if the index is not geodetic. SDO_INDEX_STATUS VARCHAR2 (Deprecated; reserved for Oracle use.) Table 2–9 (Cont.) Columns in the xxx_SDO_INDEX_METADATA Views Column Name Data Type Purpose Unit of Measurement Support Spatial Data Types and Metadata 2-49 2.9.2 Spatial Index Table Definition For an R-tree index, a spatial index table (each SDO_INDEX_TABLE entry as described in Table 2–9 in Section 2.9.1.2) contains the columns shown in Table 2–10. 2.9.3 R-Tree Index Sequence Object Each R-tree spatial index table has an associated sequence object (SDO_RTREE_SEQ_ NAME in the USER_SDO_INDEX_METADATA view, described in Table 2–9 in Section 2.9.1.2). The sequence is used to ensure that simultaneous updates can be performed to the index by multiple concurrent users. The sequence name is the index table name with the letter S replacing the letter T before the underscore (for example, the sequence object MDRS_5C01$ is associated with the index table MDRT_5C01$). 2.10 Unit of Measurement Support Geometry functions that involve measurement allow an optional unit parameter to specify the unit of measurement for a specified distance or area, if a georeferenced coordinate system (SDO_SRID value) is associated with the input geometry or geometries. The unit parameter is not valid for geometries with a null SDO_SRID value (that is, an orthogonal Cartesian system). For information about support for coordinate systems, see Chapter 6. SDO_NL_INDEX_TABLE VARCHAR2 Name of a separate index table (with a name in the form MDNT_...$) for nonleaf nodes of the index. For more information, see the description of the sdo_non_leaf_tbl parameter for the CREATE INDEX statement in Chapter 18. SDO_DML_BATCH_SIZE NUMBER Number of index updates to be processed in each batch of updates after a commit operation. For more information, see the description of the sdo_ dml_batch_size parameter for the CREATE INDEX statement in Chapter 18. SDO_RTREE_EXT_XPND NUMBER (Reserved for future use.) SDO_ROOT_MBR SDO_ GEOMETRY Minimum bounding rectangle of the maximum extent of the spatial layer. This is greater than or equal to the MBR of the current extent, and is reset to reflect the current extent when the index is rebuilt. Table 2–10 Columns in an R-Tree Spatial Index Data Table Column Name Data Type Purpose NODE_ID NUMBER Unique ID number for this node of the tree. NODE_LEVEL NUMBER Level of the node in the tree. Leaf nodes (nodes whose entries point to data items in the base table) are at level 1, their parent nodes are at level 2, and so on. INFO BLOB Other information in a node. Includes an array of pairs (maximum of fanout value, or number of children for such pairs in each R-tree node), where child_rowid is the rowid of a child node, or the rowid of a data item from the base table. Table 2–9 (Cont.) Columns in the xxx_SDO_INDEX_METADATA Views Column Name Data Type Purpose Unit of Measurement Support 2-50 Oracle Spatial Developer's Guide The default unit of measure is the one associated with the georeferenced coordinate system. The unit of measure for most coordinate systems is the meter, and in these cases the default unit for distances is meter and the default unit for areas is square meter. By using the unit parameter, however, you can have Spatial automatically convert and return results that are more meaningful to application users, for example, displaying the distance to a restaurant in miles. The unit parameter must be enclosed in single quotation marks and contain the string unit= and a valid UNIT_OF_MEAS_NAME value from the SDO_UNITS_OF_ MEASURE table (described in Section 6.7.27). For example, 'unit=KM' in the following example (using data and definitions from Example 6–17 in Section 6.13) specifies kilometers as the unit of measurement: SELECT c.name, SDO_GEOM.SDO_LENGTH(c.shape, m.diminfo, 'unit=KM') FROM cola_markets_cs c, user_sdo_geom_metadata m WHERE m.table_name = 'COLA_MARKETS_CS' AND m.column_name = 'SHAPE'; Spatial uses the information in the SDO_UNITS_OF_MEASURE table (described in Section 6.7.27) to determine which unit names are valid and what ratios to use in comparing or converting between different units. For convenience, you can also use the following legacy views to see the angle, area, and distance units of measure: ■ MDSYS.SDO_ANGLE_UNITS (described in Section 6.8.2) ■ MDSYS.SSDO_AREA_UNITS (described in Section 6.8.3) ■ MDSYS.SSDO_DIST_UNITS (described in Section 6.8.5) 2.10.1 Creating a User-Defined Unit of Measurement If the area and distance units of measurement supplied by Oracle are not sufficient for your needs, you can create user-defined area and distance units. (You cannot create a user-defined angle unit.) To do so, you must connect to the database as a user that has been granted the DBA role, and insert a row for each desired unit to the SDO_UNITS_ OF_MEASURE table (described in Section 6.7.27) Table 2–11 lists the columns in the SDO_UNITS_OF_MEASURE table and the requirements and recommendations for each if you are inserting a row for a user-defined unit of measurement. Table 2–11 SDO_UNITS_OF_MEASURE Table Entries for User-Defined Unit Column Name Description UOM_ID Any unit of measure ID number not currently used for an Oracle-supplied unit or another user-defined unit. Example: 1000001 UNIT_OF_MEAS_ NAME Name of the user-defined unit of measurement. Example: HALF_METER SHORT_NAME Optional short name (if any) of the unit of measurement. UNIT_OF_MEAS_ TYPE Type of measure for which the unit is used. Must be either area (for an area unit) or length (for a distance unit). TARGET_UOM_ID Optional, but for support purposes you should enter one of the following: 10008 for an area unit (10008 = UOM_ID for SQ_METER) or 10032 for a distance unit (10032 = UOM_ID for METER). Unit of Measurement Support Spatial Data Types and Metadata 2-51 Example 2–18 creates a user-defined distance unit named HALF_METER, and uses it in a query to find all customers within 400,000 half-meters (200 kilometers) of a specified store. Example 2–18 Creating and Using a User-Defined Unit of Measurement -- Distance unit: HALF_METER -- FACTOR_B specifies how many meters = one of this unit. INSERT INTO MDSYS.SDO_UNITS_OF_MEASURE (UOM_ID, UNIT_OF_MEAS_NAME, UNIT_OF_MEAS_TYPE, TARGET_UOM_ID, FACTOR_B, FACTOR_C, INFORMATION_SOURCE, DATA_SOURCE, IS_LEGACY) VALUES (100001, 'HALF_METER', 'length', 100001, .5, 1, 'User-defined half meter', 'USER_DEFINED', 'FALSE'); . . . -- Find all the customers within 400,000 half-meters of store_id = 101 SELECT /*+ordered*/ c.customer_id, c.first_name, c.last_name FROM stores s, customers c WHERE s.store_id = 101 AND sdo_within_distance (c.cust_geo_location, s.store_geo_location, 'distance = 400000 unit = HALF_METER') = 'TRUE'; CUSTOMER_ID FIRST_NAME LAST_NAME ----------- ------------------------------ ------------------------------ 1005 Carla Rodriguez 1004 Thomas Williams 1003 Marian Chang FACTOR_B For a value that can be expressed as a floating point number, specify how many square meters (for an area unit) or meters (for a distance unit) are equal to one of the user-defined unit. For example, for a unit defined as one-half of a standard meter, specify: .5 For a value that cannot be expressed as a simple floating point number, specify the dividend for the expression FACTOR_B/FACTOR_C that determines how many square meters (for an area unit) or meters (for a distance unit) are equal to one of the user-defined unit. FACTOR_C For a value that can be expressed as a floating point number, specify 1. For a value that cannot be expressed as a simple floating point number, specify the divisor for the expression FACTOR_B/FACTOR_C that determines how many square meters (for an area unit) or meters (for a distance unit) are equal to one of the user-defined unit. INFORMATION_ SOURCE Specify the following: USER_DEFINED DATA_SOURCE A phrase briefly describing the unit. Example: User-defined half meter IS_LEGACY Specify the following: FALSE. LEGACY_CODE (Do not use this for a user-defined unit.) Table 2–11 (Cont.) SDO_UNITS_OF_MEASURE Table Entries for User-Defined Unit Column Name Description Unit of Measurement Support 2-52 Oracle Spatial Developer's Guide 1001 Alexandra Nichols 3 SQL Multimedia Type Support 3-1 3 SQL Multimedia Type Support This chapter explains the support within Oracle Spatial for the use of the ST_xxx types specified in ISO 13249-3, Information technology - Database languages - SQL Multimedia and Application Packages - Part 3: Spatial. This chapter contains the following major sections: ■ Section 3.1, "ST_GEOMETRY and SDO_GEOMETRY Interoperability" ■ Section 3.2, "Tolerance Value with SQL Multimedia Types" ■ Section 3.3, "Avoiding Name Conflicts" ■ Section 3.4, "Annotation Text Type and Views" 3.1 ST_GEOMETRY and SDO_GEOMETRY Interoperability The SQL Multimedia ST_GEOMETRY root type, including its subtypes, and the Oracle Spatial SDO_GEOMETRY type (described in Section 2.2) are essentially interoperable. The ST_GEOMETRY subtypes are: ■ ST_CIRCULARSTRING ■ ST_COMPOUNDCURVE ■ ST_CURVE ■ ST_CURVEPOLYGON ■ ST_GEOMCOLLECTION ■ ST_LINESTRING ■ ST_MULTICURVE ■ ST_MULTILINESTRING ■ ST_MULTIPOINT ■ ST_MULTIPOLYGON ■ ST_MULTISURFACE ■ ST_POINT ■ ST_POLYGON ■ ST_SURFACE The ST_GEOMETRY type has an additional constructor method (that is, in addition to the constructors defined in the ISO standard) for creating an instance of the type using an SDO_GEOMETRY object. This constructor has the following format: ST_GEOMETRY and SDO_GEOMETRY Interoperability 3-2 Oracle Spatial Developer's Guide ST_GEOMETRY(geom SDO_GEOMETRY); Example 3–1 creates a table using the ST_GEOMETRY type for a spatial column instead of the SDO_GEOMETRY type, and it uses the ST_GEOMETRY constructor to specify the SHAPE column value when inserting a row into that table. Example 3–1 Using the ST_GEOMETRY Type for a Spatial Column CREATE TABLE cola_markets ( mkt_id NUMBER PRIMARY KEY, name VARCHAR2(32), shape ST_GEOMETRY); INSERT INTO cola_markets VALUES( 1, 'cola_a', ST_GEOMETRY( SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), -- one rectangle (1003 = exterior) SDO_ORDINATE_ARRAY(1,1, 5,7) -- only 2 points needed to -- define rectangle (lower left and upper right) with -- Cartesian-coordinate data ) ) ); If you create a table with a spatial column of type ST_GEOMETRY, you should add its information to the USER_SDO_GEOM_METADATA view and create a spatial index on the ST_GEOMETRY column, just as you would for spatial data defined using the SDO_GEOMETRY type. After you have performed these operations, you can use Oracle Spatial operators (described in Chapter 19) in the ST_GEOMETRY data. In addition to the operators defined in the standard, you can use the SDO_NN and SDO_ WITHIN_DISTANCE operators. Example 3–2 performs many of the same basic operations as in Example 2–1 in Section 2.1, but it uses the ST_GEOMETRY type instead of the SDO_GEOMETRY type for the spatial column. Example 3–2 Creating, Indexing, Storing, and Querying ST_GEOMETRY Data CREATE TABLE cola_markets ( mkt_id NUMBER PRIMARY KEY, name VARCHAR2(32), shape ST_GEOMETRY); INSERT INTO cola_markets VALUES( 1, 'cola_a', ST_GEOMETRY( SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), -- one rectangle (1003 = exterior) SDO_ORDINATE_ARRAY(1,1, 5,7) -- only 2 points needed to -- define rectangle (lower left and upper right) with -- Cartesian-coordinate data ST_GEOMETRY and SDO_GEOMETRY Interoperability SQL Multimedia Type Support 3-3 ) ) ); INSERT INTO cola_markets VALUES( 2, 'cola_b', ST_GEOMETRY( SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,1), -- one polygon (exterior polygon ring) SDO_ORDINATE_ARRAY(5,1, 8,1, 8,6, 5,7, 5,1) ) ) ); INSERT INTO cola_markets VALUES( 3, 'cola_c', ST_GEOMETRY( SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,1), -- one polygon (exterior polygon ring) SDO_ORDINATE_ARRAY(3,3, 6,3, 6,5, 4,5, 3,3) ) ) ); INSERT INTO cola_markets VALUES( 4, 'cola_d', ST_GEOMETRY( SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,4), -- one circle SDO_ORDINATE_ARRAY(8,7, 10,9, 8,11) ) ) ); --------------------------------------------------------------------------- -- UPDATE METADATA VIEW -- --------------------------------------------------------------------------- -- Update the USER_SDO_GEOM_METADATA view. This is required before -- the spatial index can be created. Do this only once for each layer -- (that is, table-column combination; here: cola_markets and shape). INSERT INTO user_sdo_geom_metadata (TABLE_NAME, COLUMN_NAME, DIMINFO, SRID) VALUES ( ST_GEOMETRY and SDO_GEOMETRY Interoperability 3-4 Oracle Spatial Developer's Guide 'cola_markets', 'shape', SDO_DIM_ARRAY( -- 20X20 grid SDO_DIM_ELEMENT('X', 0, 20, 0.005), SDO_DIM_ELEMENT('Y', 0, 20, 0.005) ), NULL -- SRID ); ------------------------------------------------------------------- -- CREATE THE SPATIAL INDEX -- ------------------------------------------------------------------- CREATE INDEX cola_spatial_idx ON cola_markets(shape) INDEXTYPE IS MDSYS.SPATIAL_INDEX; --------------------------- -- SDO_NN and SDO_WITHIN_DISTANCE -------------------------- -- SDO_NN operator. SELECT /*+ INDEX(c cola_spatial_idx) */ c.mkt_id, c.name FROM cola_markets c WHERE SDO_NN(c.shape, sdo_geometry(2001, NULL, sdo_point_type(10,7,NULL), NULL, NULL), 'sdo_num_res=2') = 'TRUE'; -- SDO_NN_DISTANCE ancillary operator SELECT /*+ INDEX(c cola_spatial_idx) */ c.mkt_id, c.name, SDO_NN_DISTANCE(1) dist FROM cola_markets c WHERE SDO_NN(c.shape, sdo_geometry(2001, NULL, sdo_point_type(10,7,NULL), NULL, NULL), 'sdo_num_res=2', 1) = 'TRUE' ORDER BY dist; -- SDO_WITHIN_DISTANCE operator (two examples) SELECT c.name FROM cola_markets c WHERE SDO_WITHIN_DISTANCE(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(4,6, 8,8)), 'distance=10') = 'TRUE'; -- What geometries are within a distance of 10 from a query window -- (here, a rectangle with lower-left, upper-right coordinates 4,6, 8,8)? -- But exclude geoms with MBRs with both sides < 4.1, i.e., cola_c and cola_d. SELECT c.name FROM cola_markets c WHERE SDO_WITHIN_DISTANCE(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(4,6, 8,8)), 'distance=10 min_resolution=4.1') = 'TRUE'; ------------------------------------- -- Some ST_GEOMETRY member functions ------------------------------------- SELECT c.shape.GET_WKB() FROM cola_markets c WHERE c.name = 'cola_b'; ST_GEOMETRY and SDO_GEOMETRY Interoperability SQL Multimedia Type Support 3-5 SELECT c.shape.GET_WKT() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_COORDDIM() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_ISVALID() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_SRID() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_SRID(8307) FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_ISEMPTY() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_ENVELOPE() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_BOUNDARY() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_GEOMETRYTYPE() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_ISSIMPLE() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_DIMENSION() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_CONVEXHULL() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_CENTROID() FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_GETTOLERANCE() FROM cola_markets c WHERE c.name = 'cola_b'; -- Some member functions that require a parameter DECLARE cola_a_geom ST_GEOMETRY; cola_b_geom ST_GEOMETRY; cola_c_geom ST_GEOMETRY; cola_d_geom ST_GEOMETRY; returned_geom ST_GEOMETRY; returned_number NUMBER; BEGIN -- Populate geometry variables with cola market shapes. SELECT c.shape INTO cola_a_geom FROM cola_markets c WHERE c.name = 'cola_a'; SELECT c.shape INTO cola_b_geom FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape INTO cola_c_geom FROM cola_markets c WHERE c.name = 'cola_c'; ST_GEOMETRY and SDO_GEOMETRY Interoperability 3-6 Oracle Spatial Developer's Guide SELECT c.shape INTO cola_d_geom FROM cola_markets c WHERE c.name = 'cola_d'; SELECT c.shape.ST_EQUALS(cola_a_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Is cola_b equal to cola_a?: ' || returned_number); SELECT c.shape.ST_SYMMETRICDIFFERENCE(cola_a_geom) INTO returned_geom FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_DISTANCE(cola_d_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Distance between cola_b equal to cola_d: ' || returned_ number); SELECT c.shape.ST_INTERSECTS(cola_a_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Does cola_b intersect cola_a?: ' || returned_number); SELECT c.shape.ST_CROSS(cola_a_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Does cola_b cross cola_a?: ' || returned_number); SELECT c.shape.ST_DISJOINT(cola_a_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Is cola_b disjoint with cola_a?: ' || returned_number); SELECT c.shape.ST_TOUCH(cola_a_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Does cola_b touch cola_a?: ' || returned_number); SELECT c.shape.ST_WITHIN(cola_a_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Is cola_b within cola_a?: ' || returned_number); SELECT c.shape.ST_OVERLAP(cola_a_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Does cola_b overlap cola_a?: ' || returned_number); SELECT c.shape.ST_CONTAINS(cola_a_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Does cola_b contain cola_a?: ' || returned_number); SELECT c.shape.ST_INTERSECTION(cola_a_geom) INTO returned_geom FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_DIFFERENCE(cola_a_geom) INTO returned_geom FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_UNION(cola_a_geom) INTO returned_geom FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_SYMDIFFERENCE(cola_a_geom) INTO returned_geom FROM cola_markets c WHERE c.name = 'cola_b'; SELECT c.shape.ST_TOUCHES(cola_a_geom) INTO returned_number FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Does cola_b touch cola_a?: ' || returned_number); SELECT c.shape.ST_CROSSES(cola_a_geom) INTO returned_number Annotation Text Type and Views SQL Multimedia Type Support 3-7 FROM cola_markets c WHERE c.name = 'cola_b'; DBMS_OUTPUT.PUT_LINE('Does cola_b cross cola_a?: ' || returned_number); END; / 3.2 Tolerance Value with SQL Multimedia Types Because the SQL Multimedia standard does not define how tolerance is to be used with the ST_ xxx, Spatial uses a default value of 0.005 in all the member methods of the ST_GEOMETRY type. If you want to specify a different tolerance value to be used with ST_GEOMETRY member functions, override the default by inserting the desired value into the SDO_ST_TOLERANCE table. The SDO_ST_TOLERANCE table is a global temporary table that should have a single row specifying the tolerance to be used with ST_GEOMETRY member methods. This table has a single column, defined as (tolerance NUMBER). For all Spatial operators that use a spatial index, Spatial uses the tolerance value specified for the spatial column in the USER_SDO_GEOM_METADATA view. 3.3 Avoiding Name Conflicts Some third-party vendors support their own version of ST_xxx types on Oracle. For example, a vendor might create its own version of the ST_GEOMETRY type. To avoid possible conflicts between third-party names and Oracle-supplied names, any third-party implementation of ST_xxx types on Oracle should use a schema prefix. For example, this will ensure that if someone specifies a column type as just ST_ GEOMETRY, the column will be created with the Oracle implementation of the ST_ GEOMETRY type. 3.4 Annotation Text Type and Views Oracle Spatial supports annotation text as specified in the OpenGIS Implementation Specification for Geographic information - Simple feature access - Part 1: Common architecture, which defines annotation text as "simply placed text that can carry either geographically-related or ad-hoc data and process-related information as displayable text. This text may be used for display in editors or in simpler maps. It is usually lacking in full cartographic quality, but may act as an approximation to such text as needed by any application." The ST_ANNOTATION_TEXT object type can be used to store annotation text. This type has a constructor for inserting annotation text into a table, as explained in Section 3.4.1. The USER_ANNOTATION_TEXT_METADATA and ALL_ANNOTATION_TEXT_ METADATA views store metadata related to annotation text, as explained in Section 3.4.2. 3.4.1 Using the ST_ANNOTATION_TEXT Constructor An annotation text object contains an array of objects, where each object consists of a text label, the point at which to start rendering the text label, a leader line (typically from the text label to the associated point on the map), and optionally extra attribute information. A single annotation text object may typically contain all the text labels for a map. Annotation Text Type and Views 3-8 Oracle Spatial Developer's Guide Each text label object has the following definition: Name Null? Type ----------------------------------------- -------- ---------------------------- PRIVATEVALUE VARCHAR2(4000) PRIVATELOCATION MDSYS.SDO_GEOMETRY PRIVATELEADERLINE MDSYS.SDO_GEOMETRY PRIVATETEXTATTRIBUTES VARCHAR2(4000) To insert the annotation for a single point, use the ST_ANNOTATION_TEXT constructor. This constructor specifies the information for a single point using an array, as shown in Example 3–3, which creates a table with a column of type ST_ ANNOTATION_TEXT and inserts one row, using the ST_ANNOTATION_TEXT constructor in the INSERT statement. Example 3–3 Using the ST_ANNOTATION_TEXT Constructor CREATE TABLE my_annotations (id NUMBER, textobj ST_ANNOTATION_TEXT); INSERT INTO my_annotations VALUES (2, ST_ANNOTATION_TEXT( ST_ANNOTATIONTEXTELEMENT_ARRAY( ST_ANNOT_TEXTELEMENT_ARRAY( ST_ANNOTATIONTEXTELEMENT( 'Sample Label 2', SDO_GEOMETRY(2001,null,sdo_point_type(10,10,null),null,null), SDO_GEOMETRY(2002,null,null, SDO_ELEM_INFO_ARRAY(1,2,1), SDO_ORDINATE_ARRAY(5,10, 10,10)), NULL))))); In the ST_ANNOTATION_TEXT constructor in Example 3–3, the ST_ ANNOTATIONTEXTELEMENT subelement specifies the following: ■ The text for the label, in this case Sample Label 2 ■ A point geometry specifying where to start rendering the label, in this case location (10,10) ■ A line string geometry specifying the start and end points of the leader line between the point of interest and the text label, in this case a line between locations (5,10) and (10,10) ■ No text display attribute information (NULL), which means that the information TEXT_ATTRIBUTES column of the annotation text metadata views is used (see Table 3–1 in Section 3.4.2) 3.4.2 Annotation Text Metadata Views The annotation text metadata is stored in a global table owned by MDSYS (which users should never directly update). Each Spatial user has the following views available in the schema associated with that user: ■ USER_ANNOTATION_TEXT_METADATA contains metadata information for all annotation text in tables owned by the user (schema). This is the only view that you can update, and it is the one in which Spatial users must insert metadata related to spatial tables. ■ ALL_ANNOTATION_TEXT_METADATA contains metadata information for all annotation text in tables on which the user has SELECT permission. Annotation Text Type and Views SQL Multimedia Type Support 3-9 Spatial users are responsible for populating these views. For each annotation text object, you must insert an appropriate row into the USER_ANNOTATION_TEXT_ METADATA view. Oracle Spatial ensures that the ALL_ANNOTATION_TEXT_ METADATA view is also updated to reflect the rows that you insert into USER_ ANNOTATION_TEXT_METADATA. The USER_ANNOTATION_TEXT_METADATA and ALL_ANNOTATION_TEXT_ METADATA views contain the same columns, as shown Table 3–1, except that the USER_ANNOTATION_TEXT_METADATA view does not contain the OWNER column. (The columns are listed in their order in the view definition.) Table 3–1 Columns in the Annotation Text Metadata Views Column Name Data Type Purpose OWNER VARCHAR2(32) Owner of the table specified in the TABLE_NAME column (ALL_ ANNOTATION_TEXT_METADATA view only). TABLE_NAME VARCHAR2(32) Name of the table containing the column of type ST_ANNOTATION_ TEXT. COLUMN_NAME VARCHAR2(1024) Name of the column of type ST_ANNOTATION_TEXT. TEXT_EXPRESSION VARCHAR2(4000) A value that can be used if text is not specified for a label. As explained in the OpenGIS specification: "Text to place is first derived from the contents of VALUE in the current element, if VALUE is not null. Otherwise, text is derived from the first non-null preceding element VALUE. If all preceding elements have null VALUE fields, VALUE is derived from the TEXT_EXPRESSION in the metadata table." TEXT_ATTRIBUTES VARCHAR2(4000) Default text display attributes (font family and size, horizontal and vertical spacing, and so on) for the label text style and layout, unless overridden in the PRIVATETEXTATTRIBUTES attribute of the ST_ ANNOTATION_TEXT constructor (described in Section 3.4.1). Use the format specified in the "XML for Text Attributes" section of the OpenGIS specification. Annotation Text Type and Views 3-10 Oracle Spatial Developer's Guide 4 Loading Spatial Data 4-1 4 Loading Spatial Data This chapter describes how to load spatial data into a database, including storing the data in a table with a column of type SDO_GEOMETRY. After you have loaded spatial data, you can create a spatial index for it and perform queries on it, as described in Chapter 5. The process of loading data can be classified into two categories: ■ Bulk loading of data (see Section 4.1) This process is used to load large volumes of data into the database and uses the SQL*Loader utility to load the data. ■ Transactional insert operations (see Section 4.2) This process is typically used to insert relatively small amounts of data into the database using the INSERT statement in SQL. Recommendations for loading and validating spatial data are described in Section 4.3. 4.1 Bulk Loading Bulk loading can import large amounts of data into an Oracle database. Bulk loading is accomplished with the SQL*Loader utility. (For information about SQL*Loader, see Oracle Database Utilities.) 4.1.1 Bulk Loading SDO_GEOMETRY Objects Example 4–1 is the SQL*Loader control file for loading four geometries. When this control file is used with SQL*Loader, it loads the same cola market geometries that are inserted using SQL statements in Example 2–1 in Section 2.1. Example 4–1 Control File for a Bulk Load of Cola Market Geometries LOAD DATA INFILE * TRUNCATE CONTINUEIF NEXT(1:1) = '#' INTO TABLE COLA_MARKETS FIELDS TERMINATED BY '|' TRAILING NULLCOLS ( mkt_id INTEGER EXTERNAL, name CHAR, shape COLUMN OBJECT ( SDO_GTYPE INTEGER EXTERNAL, SDO_ELEM_INFO VARRAY TERMINATED BY '|/' Bulk Loading 4-2 Oracle Spatial Developer's Guide (elements FLOAT EXTERNAL), SDO_ORDINATES VARRAY TERMINATED BY '|/' (ordinates FLOAT EXTERNAL) ) ) begindata 1|cola_a| #2003|1|1003|3|/ #1|1|5|7|/ 2|cola_b| #2003|1|1003|1|/ #5|1|8|1|8|6|5|7|5|1|/ 3|cola_c| #2003|1|1003|1|/ #3|3|6|3|6|5|4|5|3|3|/ 4|cola_d| #2003|1|1003|4|/ #8|7|10|9|8|11|/ Notes on Example 4–1: ■ The EXTERNAL keyword in the definition mkt_id INTEGER EXTERNAL means that each value to be inserted into the MKT_ID column (1, 2, 3, and 4 in this example) is an integer in human-readable form, not binary format. ■ In the data after begindata, each MKT_ID value is preceded by one space, because the CONTINUEIF NEXT(1:1) = '#' specification causes the first position of each data line to be ignored unless it is the number sign (#) continuation character. Example 4–2 assumes that a table named POLY_4PT was created as follows: CREATE TABLE POLY_4PT (GID VARCHAR2(32), GEOMETRY SDO_GEOMETRY); Assume that the ASCII data consists of a file with delimited columns and separate rows fixed by the limits of the table with the following format: geometry rows: GID, GEOMETRY The coordinates in the GEOMETRY column represent polygons. Example 4–2 shows the control file for loading the data. Example 4–2 Control File for a Bulk Load of Polygons LOAD DATA INFILE * TRUNCATE CONTINUEIF NEXT(1:1) = '#' INTO TABLE POLY_4PT FIELDS TERMINATED BY '|' TRAILING NULLCOLS ( GID INTEGER EXTERNAL, GEOMETRY COLUMN OBJECT ( SDO_GTYPE INTEGER EXTERNAL, SDO_ELEM_INFO VARRAY TERMINATED BY '|/' (elements FLOAT EXTERNAL), SDO_ORDINATES VARRAY TERMINATED BY '|/' (ordinates FLOAT EXTERNAL) ) ) Transactional Insert Operations Using SQL Loading Spatial Data 4-3 begindata 1|2003|1|1003|1|/ #-122.4215|37.7862|-122.422|37.7869|-122.421|37.789|-122.42|37.7866| #-122.4215|37.7862|/ 2|2003|1|1003|1|/ #-122.4019|37.8052|-122.4027|37.8055|-122.4031|37.806|-122.4012|37.8052| #-122.4019|37.8052|/ 3|2003|1|1003|1|/ #-122.426|37.803|-122.4242|37.8053|-122.42355|37.8044|-122.4235|37.8025| #-122.426|37.803|/ 4.1.2 Bulk Loading Point-Only Data in SDO_GEOMETRY Objects Example 4–3 shows a control file for loading a table with point data. Example 4–3 Control File for a Bulk Load of Point-Only Data LOAD DATA INFILE * TRUNCATE CONTINUEIF NEXT(1:1) = '#' INTO TABLE POINT FIELDS TERMINATED BY '|' TRAILING NULLCOLS ( GID INTEGER EXTERNAL, GEOMETRY COLUMN OBJECT ( SDO_GTYPE INTEGER EXTERNAL, SDO_POINT COLUMN OBJECT (X FLOAT EXTERNAL, Y FLOAT EXTERNAL) ) ) BEGINDATA 1| 200 1| -122.4215| 37.7862| 2| 200 1| -122.4019| 37.8052| 3| 200 1| -122.426| 37.803| 4| 200 1| -122.4171| 37.8034| 5| 200 1| -122.416151| 37.8027228| 4.2 Transactional Insert Operations Using SQL Oracle Spatial uses standard Oracle tables that can be accessed or loaded with standard SQL syntax. This section contains examples of transactional insertions into columns of type SDO_GEOMETRY. This process is typically used to add relatively small amounts of data into the database. Recommendations for Loading and Validating Spatial Data 4-4 Oracle Spatial Developer's Guide The INSERT statement in Oracle SQL has a limit of 999 arguments. Therefore, you cannot create a variable-length array of more than 999 elements using the SDO_ GEOMETRY constructor inside a transactional INSERT statement; however, you can insert a geometry using a host variable, and the host variable can be built using the SDO_GEOMETRY constructor with more than 999 values in the SDO_ORDINATE_ ARRAY specification. (The host variable is an OCI, PL/SQL, or Java program variable.) To perform transactional insertions of geometries, you can create a procedure to insert a geometry, and then invoke that procedure on each geometry to be inserted. Example 4–4 creates a procedure to perform the insert operation. Example 4–4 Procedure to Perform a Transactional Insert Operation CREATE OR REPLACE PROCEDURE INSERT_GEOM(GEOM SDO_GEOMETRY) IS BEGIN INSERT INTO TEST_1 VALUES (GEOM); COMMIT; END; / Using the procedure created in Example 4–4, you can insert data by using a PL/SQL block, such as the one in Example 4–5, which loads a geometry into the variable named geom and then invokes the INSERT_GEOM procedure to insert that geometry. Example 4–5 PL/SQL Block Invoking a Procedure to Insert a Geometry DECLARE geom SDO_geometry := SDO_geometry (2003, null, null, SDO_elem_info_array (1,1003,3), SDO_ordinate_array (-109,37,-102,40)); BEGIN INSERT_GEOM(geom); COMMIT; END; / For additional examples with various geometry types, see the following: ■ Rectangle: Example 2–6 in Section 2.7.1 ■ Polygon with a hole: Example 2–7 in Section 2.7.2 ■ Compound line string: Example 2–8 in Section 2.7.3 ■ Compound polygon: Example 2–9 in Section 2.7.4 ■ Point: Example 2–10 and Example 2–11 in Section 2.7.5 ■ Oriented point: Example 2–12 in Section 2.7.6 ■ Type 0 (zero) element: Example 2–14 in Section 2.7.7 4.3 Recommendations for Loading and Validating Spatial Data The recommended procedure for loading and validating spatial data is as follows: 1. Load the data, using a method described in Section 4.1 or Section 4.2. Recommendations for Loading and Validating Spatial Data Loading Spatial Data 4-5 2. Use the SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT function or the SDO_GEOM.VALIDATE_LAYER_WITH_CONTEXT procedure on all spatial data loaded into the database. 3. For any geometries with the wrong orientation or an invalid ETYPE or GTYPE value, use SDO_MIGRATE.TO_CURRENT on these invalid geometries to fix them. 4. For any geometries that are invalid for other reasons, use SDO_UTIL.RECTIFY_ GEOMETRY to fix these geometries. For detailed information about using any of these subprograms, see the usage notes in its reference information section. Recommendations for Loading and Validating Spatial Data 4-6 Oracle Spatial Developer's Guide 5 Indexing and Querying Spatial Data 5-1 5 Indexing and Querying Spatial Data After you have loaded spatial data (discussed in Chapter 4), you should create a spatial index on it to enable efficient query performance using the data. This chapter describes how to: ■ Create a spatial index (see Section 5.1) ■ Query spatial data efficiently, based on an understanding of the Oracle Spatial query model and primary and secondary filtering (see Section 5.2) 5.1 Creating a Spatial Index Once data has been loaded into the spatial tables through either bulk or transactional loading, a spatial index (that is, a spatial R-tree index) must be created on each geometry column in the tables for efficient access to the data. For example, the following statement creates a spatial index named territory_idx using default values for all parameters: CREATE INDEX territory_idx ON territories (territory_geom) INDEXTYPE IS MDSYS.SPATIAL_INDEX; For detailed information about options for creating a spatial index, see the documentation for the CREATE INDEX statement in Chapter 18. If the index creation does not complete for any reason, the index is invalid and must be deleted with the DROP INDEX [FORCE] statement. Within each geometry column to be indexed, all the geometries must have the same SDO_SRID value. Spatial indexes can be built on two, three, or four dimensions of data. The default number of dimensions is two, but if the data has more than two dimensions, you can use the sdo_indx_dims parameter keyword to specify the number of dimensions on which to build the index. (For information about support for three-dimensional geometries, see Section 1.11. For an explanation of support for various combinations of dimensionality in query elements, see Section 5.2.3.) If you are not using the automatic undo management feature or the PGA memory management feature, or both, of Oracle Database, see Section 5.1.7 for information about initialization parameter values that you may need to set. Both automatic undo management and PGA memory management are enabled by default, and their use is highly recommended. The tablespace specified with the tablespace keyword in the CREATE INDEX statement (or the default tablespace if the tablespace keyword is not specified) is used to hold both the index data table and some transient tables that are created for Creating a Spatial Index 5-2 Oracle Spatial Developer's Guide internal computations. If you specify WORK_TABLESPACE as the tablespace, the transient tables are stored in the work tablespace. For large tables (over 1 million rows), a temporary tablespace may be needed to perform internal sorting operations. The recommended size for this temporary tablespace is 100*n bytes, where n is the number of rows in the table, up to a maximum requirement of 1 gigabyte of temporary tablespace. To estimate the space that will be needed to create a spatial index, use the SDO_ TUNE.ESTIMATE_RTREE_INDEX_SIZE function, described in Chapter 31. 5.1.1 Constraining Data to a Geometry Type When you create or rebuild a spatial index, you can ensure that all geometries that are in the table or that are inserted later are of a specified geometry type. To constrain the data to a geometry type in this way, use the layer_gtype keyword in the PARAMETERS clause of the CREATE INDEX or ALTER INDEX REBUILD statement, and specify a value from the Geometry Type column of Table 2–1 in Section 2.2.1. For example, to constrain spatial data in a layer to polygons: CREATE INDEX cola_spatial_idx ON cola_markets(shape) INDEXTYPE IS MDSYS.SPATIAL_INDEX PARAMETERS ('layer_gtype=POLYGON'); The geometry types in Table 2–1 are considered as a hierarchy when data is checked: ■ The MULTI forms include the regular form also. For example, specifying 'layer_ gtype=MULTIPOINT' allows the layer to include both POINT and MULTIPOINT geometries. ■ COLLECTION allows the layer to include all types of geometries. 5.1.2 Creating a Cross-Schema Index You can create a spatial index on a table that is not in your schema. Assume that user B wants to create a spatial index on column GEOMETRY in table T1 under user A's schema. Follow these steps: 1. Connect to the database as a privileged user (for example, as SYSTEM), and execute the following statement: GRANT create table, create sequence to B; 2. Connect as a privileged user or as user A (or have user A connect), and execute the following statement: GRANT select, index on A.T1 to B; 3. Connect as user B and execute a statement such as the following: CREATE INDEX t1_spatial_idx on A.T1(geometry) INDEXTYPE IS mdsys.spatial_index; 5.1.3 Using Partitioned Spatial Indexes You can create a partitioned spatial index on a partitioned table. This section describes usage considerations specific to Oracle Spatial. For a detailed explanation of partitioned tables and partitioned indexes, see Oracle Database Administrator's Guide. A partitioned spatial index can provide the following benefits: Creating a Spatial Index Indexing and Querying Spatial Data 5-3 ■ Reduced response times for long-running queries, because partitioning reduces disk I/O operations ■ Reduced response times for concurrent queries, because I/O operations run concurrently on each partition ■ Easier index maintenance, because of partition-level create and rebuild operations Indexes on partitions can be rebuilt without affecting the queries on other partitions, and storage parameters for each local index can be changed independent of other partitions. ■ Parallel query on multiple partition searching The degree of parallelism is the value from the DEGREE column in the row for the index in the USER_INDEXES view (that is, the value specified or defaulted for the PARALLEL keyword with the CREATE INDEX, ALTER INDEX, or ALTER INDEX REBUILD statement). ■ Improved query processing in multiprocessor system environments In a multiprocessor system environment, if a spatial operator is invoked on a table with partitioned spatial index and if multiple partitions are involved in the query, multiple processors can be used to evaluate the query. The number of processors used is determined by the degree of parallelism and the number of partitions used in evaluating the query. The following restrictions apply to spatial index partitioning: ■ The partition key for spatial tables must be a scalar value, and must not be a spatial column. ■ Only range partitioning is supported on the underlying table. All other kinds of partitioning are not currently supported for partitioned spatial indexes. To create a partitioned spatial index, you must specify the LOCAL keyword. (If you do not specify the LOCAL keyword, a nonpartitioned spatial index is created on the data in all table partitions.) The following example creates a partitioned spatial index: CREATE INDEX counties_idx ON counties(geometry) INDEXTYPE IS MDSYS.SPATIAL_INDEX LOCAL; In this example, the default values are used for the number and placement of index partitions, namely: ■ Index partitioning is based on the underlying table partitioning. For each table partition, a corresponding index partition is created. ■ Each index partition is placed in the default tablespace. If you do specify parameters for individual partitions, the following considerations apply: ■ The storage characteristics for each partition can be the same or different for each partition. If they are different, it may enable parallel I/O (if the tablespaces are on different disks) and may improve performance. ■ The sdo_indx_dims value must be the same for all partitions. ■ The layer_gtype parameter value (see Section 5.1.1) used for each partition may be different. To override the default partitioning values, use a CREATE INDEX statement with the following general format: CREATE INDEX ON () Creating a Spatial Index 5-4 Oracle Spatial Developer's Guide INDEXTYPE IS MDSYS.SPATIAL_INDEX [PARAMETERS (', ')] LOCAL [( PARTITION PARAMETERS (', ') [, PARTITION PARAMETERS (', ')] )] Queries can operate on partitioned tables to perform the query on only one partition. For example: SELECT * FROM counties PARTITION(p1) WHERE ...; Querying on a selected partition may speed up the query and also improve overall throughput when multiple queries operate on different partitions concurrently. When queries use a partitioned spatial index, the semantics (meaning or behavior) of spatial operators and functions is the same with partitioned and nonpartitioned indexes, except in the case of SDO_NN (nearest neighbor). With SDO_NN, the requested number of geometries is returned for each partition that is affected by the query. For example, if you request the 5 closest restaurants to a point and the spatial index has 4 partitions, SDO_NN returns up to 20 (5*4) geometries. In this case, you must use the ROWNUM pseudocolumn (here, WHERE ROWNUM <=5) to return the 5 closest restaurants. See the description of the SDO_NN operator in Chapter 19 for more information. For a cross-schema query when a table has a partitioned spatial index, the user must be granted SELECT privilege on both the spatial table and the index table (MDRT_xxx) for the spatial index that was created on the spatial table. For more information and an example, see "Cross-Schema Invocation of SDO_JOIN" in the Usage Notes for the SDO_JOIN operator in Chapter 19. 5.1.3.1 Creating a Local Partitioned Spatial Index If you want to create a local partitioned spatial index, Oracle recommends that you use the procedure in this section instead of using the PARALLEL keyword, to avoid having to start over if the creation of any partition’s index fails for any reason (for example, because the tablespace is full). Follow these steps: 1. Create a local spatial index and specify the UNUSABLE keyword. For example: CREATE INDEX sp_idx ON my_table (location) INDEXTYPE IS mdsys.spatial_index PARAMETERS (‘tablespace=tb_name work_tablespace=work_tb_name’) LOCAL UNUSABLE; This statement executes quickly and creates metadata associated with the index. 2. Create scripts with ALTER INDEX REBUILD statements, but without the PARALLEL keyword. For example, if you have 100 partitions and 10 processors, create 10 scripts with 10 ALTER INDEX statements such as the following: ALTER INDEX sp_idx REBUILD PARTITION ip1; ALTER INDEX sp_idx REBUILD PARTITION ip2; . . . ALTER INDEX sp_idx REBUILD PARTITION ip10; 3. Run all the scripts at the same time, so that each processor works on the index for a single partition, but all the processors are busy working on their own set of ALTER INDEX statements. Creating a Spatial Index Indexing and Querying Spatial Data 5-5 If any of the ALTER INDEX statements fails, you do not need to rebuild any partitions for which the operation has successfully completed. 5.1.4 Exchanging Partitions Including Indexes You can use the ALTER TABLE statement with the EXCHANGE PARTITION ... INCLUDING INDEXES clause to exchange a spatial table partition and its index partition with a corresponding table and its index. For information about exchanging partitions, see the description of the ALTER TABLE statement in Oracle Database SQL Language Reference. This feature can help you to operate more efficiently in a number of situations, such as: ■ Bringing data into a partitioned table and avoiding the cost of index re-creation. ■ Managing and creating partitioned indexes. For example, the data could be divided into multiple tables. The index for each table could be built one after the other to minimize the memory and tablespace resources needed during index creation. Alternately, the indexes could be created in parallel in multiple sessions. The tables (along with the indexes) could then be exchanged with the partitions of the original data table. ■ Managing offline insert operations. New data can be stored in a temporary table and periodically exchanged with a new partition (for example, in a database with historical data). To exchange partitions including indexes with spatial data and indexes, the two spatial indexes (one on the partition, the other on the table) must have the same dimensionality (sdo_indx_dims value). If the indexes do not have the same dimensionality, an error is raised. The table data is exchanged, but the indexes are not exchanged and the indexes are marked as failed. To use the indexes, you must rebuild them 5.1.5 Export and Import Considerations with Spatial Indexes and Data If you use the Export utility to export tables with spatial data, the behavior of the operation depends on whether or not the spatial data has been spatially indexed: ■ If the spatial data has not been spatially indexed, the table data is exported. However, you must update the USER_SDO_GEOM_METADATA view with the appropriate information on the target system. ■ If the spatial data has been spatially indexed, the table data is exported, the appropriate information is inserted into the USER_SDO_GEOM_METADATA view on the target system, and the spatial index is built on the target system. However, if the insertion into the USER_SDO_GEOM_METADATA view fails (for example, if there is already a USER_SDO_GEOM_METADATA entry for the spatial layer), the spatial index is not built. If you use the Import utility to import data that has been spatially indexed, the following considerations apply: ■ If the index on the exported data was created with a TABLESPACE clause and if the specified tablespace does not exist in the database at import time, the index is not built. (This is different from the behavior with other Oracle indexes, where the index is created in the user's default tablespace if the tablespace specified for the original index does not exist at import time.) ■ If the import operation must be done by a privileged database user, and if the FROMUSER and TOUSER format is used, the TOUSER user must be granted the Creating a Spatial Index 5-6 Oracle Spatial Developer's Guide CREATE TABLE and CREATE SEQUENCE privileges before the import operation, as shown in the following example (and enter the password for the SYSTEM account when prompted): sqlplus system SQL> grant CREATE TABLE, CREATE SEQUENCE to CHRIS; SQL> exit; imp system file=spatl_data.dmp fromuser=SCOTT touser=CHRIS For information about using the Export and Import utilities, see Oracle Database Utilities. 5.1.6 Distributed Transactions and Spatial Index Consistency In a distributed transaction, different branches of the transaction can execute in different sessions. The branches can detach from their current session and migrate to another within the transaction scope. To maintain the consistency of Spatial indexes in distributed transactions, you must follow the usage guidelines in this section. When the first insert, update, or delete operation on a spatial table (one with a spatial index) is performed in a distributed transaction, all subsequent insert, update, or delete operations on the table, as well as any prepare to commit operation (the first branch to prepare a commit), in the transaction should happen in the same session as the first operation. The branches performing these subsequent operations will first have to connect to the session in which the first operation was performed. For more information about distributed transactions, see Oracle Database Administrator's Guide. 5.1.7 Rollback Segments and Sort Area Size This section applies only if you (or the database administrator) are not using the automatic undo management feature or the PGA memory management feature, or both, of Oracle Database. Automatic memory management and PGA memory management are enabled by default, and their use is highly recommended. For explanations of these features, see: ■ The section about automatic undo management and undo segments in Oracle Database Concepts ■ The section about PGA memory management in Oracle Database Concepts If you are not using automatic undo management and if the rollback segment is not large enough, an attempt to create a spatial index will fail. The rollback segment should be 100*n bytes, where n is the number of rows of data to be indexed. For example, if the table contains 1 million (1,000,000) rows, the rollback segment size should be 100,000,000 (100 million) bytes. To ensure an adequate rollback segment, or if you have tried to create a spatial index and received an error that a rollback segment cannot be extended, review (or have a DBA review) the size and structure of the rollback segments. Create a public rollback segment of the appropriate size, and place that rollback segment online. In addition, ensure that any small inappropriate rollback segments are placed offline during large spatial index operations. If you are not using the PGA memory management feature, the system parameter SORT_AREA_SIZE affects the amount of time required to create the index. The SORT_ AREA_SIZE value is the maximum amount, in bytes, of memory to use for a sort operation. The optimal value depends on the database size, but a good guideline is to make it at least 1 million bytes when you create a spatial index. To change the SORT_ Querying Spatial Data Indexing and Querying Spatial Data 5-7 AREA_SIZE value, use the ALTER SESSION statement. For example, to change the value to 20 million bytes: ALTER SESSION SET SORT_AREA_SIZE = 20000000; 5.2 Querying Spatial Data This section describes how the structures of a Spatial layer are used to resolve spatial queries and spatial joins. Spatial uses a two-tier query model with primary and secondary filter operations to resolve spatial queries and spatial joins, as explained in Section 1.6. The term two-tier indicates that two distinct operations are performed to resolve queries. If both operations are performed, the exact result set is returned. You cannot append a database link (dblink) name to the name of a spatial table in a query if a spatial index is defined on that table. 5.2.1 Spatial Query In a spatial R-tree index, each geometry is represented by its minimum bounding rectangle (MBR), as explained in Section 1.7.1. Consider the following layer containing several objects in Figure 5–1. Each object is labeled with its geometry name (geom_1 for the line string, geom_2 for the four-sided polygon, geom_3 for the triangular polygon, and geom_4 for the ellipse), and the MBR around each object is represented by a dashed line. Figure 5–1 Geometries with MBRs A typical spatial query is to request all objects that lie within a query window, that is, a defined fence or window. A dynamic query window refers to a rectangular area that is not defined in the database, but that must be defined before it is used. Figure 5–2 shows the same geometries as in Figure 5–1, but adds a query window represented by the heavy dotted-line box. geom_2 geom_3 geom_4 geom_1 Querying Spatial Data 5-8 Oracle Spatial Developer's Guide Figure 5–2 Layer with a Query Window In Figure 5–2, the query window covers parts of geometries geom_1 and geom_2, as well as part of the MBR for geom_3 but none of the actual geom_3 geometry. The query window does not cover any part of the geom_4 geometry or its MBR. 5.2.1.1 Primary Filter Operator The SDO_FILTER operator, described in Chapter 19, implements the primary filter portion of the two-step process involved in the Oracle Spatial query processing model. The primary filter uses the index data to determine only if a set of candidate object pairs may interact. Specifically, the primary filter checks to see if the MBRs of the candidate objects interact, not whether the objects themselves interact. The SDO_ FILTER operator syntax is as follows: SDO_FILTER(geometry1 SDO_GEOMETRY, geometry2 SDO_GEOMETRY, param VARCHAR2) In the preceding syntax: ■ geometry1 is a column of type SDO_GEOMETRY in a table. This column must be spatially indexed. ■ geometry2 is an object of type SDO_GEOMETRY. This object may or may not come from a table. If it comes from a table, it may or may not be spatially indexed. ■ param is an optional string of type VARCHAR2. It can specify either or both of the min_resolution and max_resolution keywords. The following examples perform a primary filter operation only (with no secondary filter operation). They will return all the geometries shown in Figure 5–2 that have an MBR that interacts with the query window. The result of the following examples are geometries geom_1, geom_2, and geom_3. Example 5–1 performs a primary filter operation without inserting the query window into a table. The window will be indexed in memory and performance will be very good. Example 5–1 Primary Filter with a Temporary Query Window SELECT A.Feature_ID FROM TARGET A WHERE sdo_filter(A.shape, SDO_geometry(2003,NULL,NULL, SDO_elem_info_array(1,1003,3), SDO_ordinate_array(x1,y1, x2,y2)) ) = 'TRUE'; geom_2 geom_3 geom_4 geom_1 Query Window Querying Spatial Data Indexing and Querying Spatial Data 5-9 In Example 5–1, (x1,y1) and (x2,y2) are the lower-left and upper-right corners of the query window. In Example 5–2, a transient instance of type SDO_GEOMETRY was constructed for the query window instead of specifying the window parameters in the query itself. Example 5–2 Primary Filter with a Transient Instance of the Query Window SELECT A.Feature_ID FROM TARGET A WHERE sdo_filter(A.shape, :theWindow) = 'TRUE'; Example 5–3 assumes the query window was inserted into a table called WINDOWS, with an ID of WINS_1. Example 5–3 Primary Filter with a Stored Query Window SELECT A.Feature_ID FROM TARGET A, WINDOWS B WHERE B.ID = 'WINS_1' AND sdo_filter(A.shape, B.shape) = 'TRUE'; If the B.SHAPE column is not spatially indexed, the SDO_FILTER operator indexes the query window in memory and performance is very good. 5.2.1.2 Primary and Secondary Filter Operator The SDO_RELATE operator, described in Chapter 19, performs both the primary and secondary filter stages when processing a query. The secondary filter ensures that only candidate objects that actually interact are selected. This operator can be used only if a spatial index has been created on two dimensions of data. The syntax of the SDO_ RELATE operator is as follows: SDO_RELATE(geometry1 SDO_GEOMETRY, geometry2 SDO_GEOMETRY, param VARCHAR2) In the preceding syntax: ■ geometry1 is a column of type SDO_GEOMETRY in a table. This column must be spatially indexed. ■ geometry2 is an object of type SDO_GEOMETRY. This object may or may not come from a table. If it comes from a table, it may or may not be spatially indexed. ■ param is a quoted string with the mask keyword and a valid mask value, and optionally either or both of the min_resolution and max_resolution keywords, as explained in the documentation for the SDO_RELATE operator in Chapter 19. The following examples perform both primary and secondary filter operations. They return all the geometries in Figure 5–2 that lie within or overlap the query window. The result of these examples is objects geom_1 and geom_2. Example 5–4 performs both primary and secondary filter operations without inserting the query window into a table. The window will be indexed in memory and performance will be very good. Example 5–4 Secondary Filter Using a Temporary Query Window SELECT A.Feature_ID FROM TARGET A WHERE sdo_relate(A.shape, SDO_geometry(2003,NULL,NULL, SDO_elem_info_array(1,1003,3), Querying Spatial Data 5-10 Oracle Spatial Developer's Guide SDO_ordinate_array(x1,y1, x2,y2)), 'mask=anyinteract') = 'TRUE'; In Example 5–4, (x1,y1) and (x2,y2) are the lower-left and upper-right corners of the query window. Example 5–5 assumes the query window was inserted into a table called WINDOWS, with an ID value of WINS_1. Example 5–5 Secondary Filter Using a Stored Query Window SELECT A.Feature_ID FROM TARGET A, WINDOWS B WHERE B.ID = 'WINS_1' AND sdo_relate(A.shape, B.shape, 'mask=anyinteract') = 'TRUE'; If the B.SHAPE column is not spatially indexed, the SDO_RELATE operator indexes the query window in memory and performance is very good. 5.2.1.3 Within-Distance Operator The SDO_WITHIN_DISTANCE operator, described in Chapter 19, is used to determine the set of objects in a table that are within n distance units from a reference object. This operator can be used only if a spatial index has been created on two dimensions of data. The reference object may be a transient or persistent instance of SDO_GEOMETRY, such as a temporary query window or a permanent geometry stored in the database. The syntax of the operator is as follows: SDO_WITHIN_DISTANCE(geometry1 SDO_GEOMETRY, aGeom SDO_GEOMETRY, params VARCHAR2); In the preceding syntax: ■ geometry1 is a column of type SDO_GEOMETRY in a table. This column must be spatially indexed. ■ aGeom is an instance of type SDO_GEOMETRY. ■ params is a quoted string of keyword value pairs that determines the behavior of the operator. See the SDO_WITHIN_DISTANCE operator in Chapter 19 for a list of parameters. The following example selects any objects within 1.35 distance units from the query window: SELECT A.Feature_ID FROM TARGET A WHERE SDO_WITHIN_DISTANCE( A.shape, :theWindow, 'distance=1.35') = 'TRUE'; The distance units are based on the geometry coordinate system in use. If you are using a geodetic coordinate system, the units are meters. If no coordinate system is used, the units are the same as for the stored data. The SDO_WITHIN_DISTANCE operator is not suitable for performing spatial joins. That is, a query such as Find all parks that are within 10 distance units from coastlines will not be processed as an index-based spatial join of the COASTLINES and PARKS tables. Instead, it will be processed as a nested loop query in which each COASTLINES instance is in turn a reference object that is buffered, indexed, and evaluated against the PARKS table. Thus, the SDO_WITHIN_DISTANCE operation is performed n times if there are n rows in the COASTLINES table. Querying Spatial Data Indexing and Querying Spatial Data 5-11 For non-geodetic data, there is an efficient way to accomplish a spatial join that involves buffering all geometries of a layer. This method does not use the SDO_ WITHIN_DISTANCE operator. First, create a new table COSINE_BUFS as follows: CREATE TABLE cosine_bufs UNRECOVERABLE AS SELECT SDO_BUFFER (A.SHAPE, B.DIMINFO, 1.35) FROM COSINE A, USER_SDO_GEOM_METADATA B WHERE TABLE_NAME='COSINES' AND COLUMN_NAME='SHAPE'; Next, create a spatial index on the SHAPE column of COSINE_BUFS. Then you can perform the following query: SELECT /*+ ordered */ a.gid, b.gid FROM TABLE(SDO_JOIN('PARKS', 'SHAPE', 'COSINE_BUFS', 'SHAPE', 'mask=ANYINTERACT')) c, parks a, cosine_bufs b WHERE c.rowid1 = a.rowid AND c.rowid2 = b.rowid; 5.2.1.4 Nearest Neighbor Operator The SDO_NN operator, described in Chapter 19, is used to identify the nearest neighbors for a geometry. This operator can be used only if a spatial index has been created on two dimensions of data. The syntax of the operator is as follows: SDO_NN(geometry1 SDO_GEOMETRY, geometry2 SDO_GEOMETRY, param VARCHAR2 [, number NUMBER]); In the preceding syntax: ■ geometry1 is a column of type SDO_GEOMETRY in a table. This column must be spatially indexed. ■ geometry2 is an instance of type SDO_GEOMETRY. ■ param is a quoted string of keyword-value pairs that can determine the behavior of the operator, such as how many nearest neighbor geometries are returned. See the SDO_NN operator in Chapter 19 for information about this parameter. ■ number is the same number used in the call to SDO_NN_DISTANCE. Use this only if the SDO_NN_DISTANCE ancillary operator is included in the call to SDO_ NN. See the SDO_NN operator in Chapter 19 for information about this parameter. The following example finds the two objects from the SHAPE column in the COLA_ MARKETS table that are closest to a specified point (10,7). (Note the use of the optimizer hint in the SELECT statement, as explained in the Usage Notes for the SDO_ NN operator in Chapter 19.) SELECT /*+ INDEX(cola_markets cola_spatial_idx) */ c.mkt_id, c.name FROM cola_markets c WHERE SDO_NN(c.shape, SDO_geometry(2001, NULL, SDO_point_type(10,7,NULL), NULL, NULL), 'sdo_num_res=2') = 'TRUE'; 5.2.1.5 Spatial Functions Spatial also supplies functions for determining relationships between geometries, finding information about single geometries, changing geometries, and combining geometries. These functions all take into account two dimensions of source data. If the Querying Spatial Data 5-12 Oracle Spatial Developer's Guide output value of these functions is a geometry, the resulting geometry will have the same dimensionality as the input geometry, but only the first two dimensions will accurately reflect the result of the operation. 5.2.2 Spatial Join A spatial join is the same as a regular join except that the predicate involves a spatial operator. In Spatial, a spatial join takes place when you compare all geometries of one layer to all geometries of another layer. This is unlike a query window, which compares a single geometry to all geometries of a layer. Spatial joins can be used to answer questions such as Which highways cross national parks? The following table structures illustrate how the join would be accomplished for this example: PARKS( GID VARCHAR2(32), SHAPE SDO_GEOMETRY) HIGHWAYS( GID VARCHAR2(32), SHAPE SDO_GEOMETRY) To perform a spatial join, use the SDO_JOIN operator, which is described in Chapter 19. The following spatial join query, to list the GID column values of highways and parks where a highway interacts with a park, performs a primary filter operation only ('mask=FILTER'), and thus it returns only approximate results: SELECT /*+ ordered */ a.gid, b.gid FROM TABLE(SDO_JOIN('PARKS', 'SHAPE', 'HIGHWAYS', 'SHAPE', 'mask=FILTER')) c, parks a, highways b WHERE c.rowid1 = a.rowid AND c.rowid2 = b.rowid; The following spatial join query requests the same information as in the preceding example, but it performs both primary and secondary filter operations ('mask=ANYINTERACT'), and thus it returns exact results: SELECT /*+ ordered */ a.gid, b.gid FROM TABLE(SDO_JOIN('PARKS', 'SHAPE', 'HIGHWAYS', 'SHAPE', 'mask=ANYINTERACT')) c, parks a, highways b WHERE c.rowid1 = a.rowid AND c.rowid2 = b.rowid; 5.2.3 Data and Index Dimensionality, and Spatial Queries The elements of a spatial query can, in theory, have the following dimensionality: ■ The base table geometries (or geometry1 in Spatial operator formats) can have two, three, or more dimensions. ■ The spatial index created on the base table (or geometry1) can be two-dimensional or three-dimensional. ■ The query window (or geometry2 in Spatial operator formats) can have two, three, or more dimensions. Some combinations of dimensionality among the three elements are supported and some are not. Table 5–1 explains what happens with the possible combinations involving two and three dimensions. Querying Spatial Data Indexing and Querying Spatial Data 5-13 Table 5–1 Data and Index Dimensionality, and Query Support Base Table (geometry1) Dimensionality Spatial Index Dimensionality Query Window (geometry2) Dimensionality Query Result 2-dimensional 2-dimensional 2-dimensional Performs a two-dimensional query. 2-dimensional 2-dimensional 3-dimensional Supported if the query window has an appropriate SDO_ GTYPE value less than 3008. 2-dimensional 3-dimensional 2-dimensional Not supported: 3D index not permitted on 2D data. 2-dimensional 3-dimensional 3-dimensional Not supported: 3D index not permitted on 2D data. 3-dimensional 2-dimensional 2-dimensional Ignores the third (Z) dimension in each base geometry and performs a two-dimensional query. 3-dimensional 2-dimensional 3-dimensional Supported if the query window has an appropriate SDO_ GTYPE value less than 3008. 3-dimensional 3-dimensional 2-dimensional Converts the 2D query window to a 3D window with zero Z values and performs a three-dimensional query. 3-dimensional 3-dimensional 3-dimensional Performs a three-dimensional query. Querying Spatial Data 5-14 Oracle Spatial Developer's Guide 6 Coordinate Systems (Spatial Reference Systems) 6-1 6 Coordinate Systems (Spatial Reference Systems) This chapter describes in greater detail the Oracle Spatial coordinate system support, which was introduced in Section 1.5.4. You can store and manipulate SDO_ GEOMETRY objects in a variety of coordinate systems. For reference information about coordinate system transformation functions and procedures in the MDSYS.SDO_CS package, see Chapter 21. This chapter contains the following major sections: ■ Section 6.1, "Terms and Concepts" ■ Section 6.2, "Geodetic Coordinate Support" ■ Section 6.3, "Local Coordinate Support" ■ Section 6.4, "EPSG Model and Spatial" ■ Section 6.5, "Three-Dimensional Coordinate Reference System Support" ■ Section 6.6, "TFM_PLAN Object Type" ■ Section 6.7, "Coordinate Systems Data Structures" ■ Section 6.8, "Legacy Tables and Views" ■ Section 6.9, "Creating a User-Defined Coordinate Reference System" ■ Section 6.10, "Notes and Restrictions with Coordinate Systems Support" ■ Section 6.11, "U.S. National Grid Support" ■ Section 6.12, "Google Maps Considerations" ■ Section 6.13, "Example of Coordinate System Transformation" 6.1 Terms and Concepts This section explains important terms and concepts related to coordinate system support in Oracle Spatial. 6.1.1 Coordinate System (Spatial Reference System) A coordinate system (also called a spatial reference system) is a means of assigning coordinates to a location and establishing relationships between sets of such coordinates. It enables the interpretation of a set of coordinates as a representation of a position in a real world space. Geodetic Coordinate Support 6-2 Oracle Spatial Developer's Guide The term coordinate reference system has the same meaning as coordinate system for Spatial, and the terms are used interchangeably. European Petroleum Survey Group (EPSG) specifications and documentation typically use the term coordinate reference system. (EPSG has its own meaning for the term coordinate system, as noted in Section 6.7.11.) 6.1.2 Cartesian Coordinates Cartesian coordinates are coordinates that measure the position of a point from a defined origin along axes that are perpendicular in the represented two-dimensional or three-dimensional space. 6.1.3 Geodetic Coordinates (Geographic Coordinates) Geodetic coordinates (sometimes called geographic coordinates) are angular coordinates (longitude and latitude), closely related to spherical polar coordinates, and are defined relative to a particular Earth geodetic datum (described in Section 6.1.6). For more information about geodetic coordinate support, see Section 6.2. 6.1.4 Projected Coordinates Projected coordinates are planar Cartesian coordinates that result from performing a mathematical mapping from a point on the Earth’s surface to a plane. There are many such mathematical mappings, each used for a particular purpose. 6.1.5 Local Coordinates Local coordinates are Cartesian coordinates in a non-Earth (non-georeferenced) coordinate system. Section 6.3 describes local coordinate support in Spatial. 6.1.6 Geodetic Datum A geodetic datum (or datum) is a means of shifting and rotating an ellipsoid to represent the figure of the Earth, usually as an oblate spheroid, that approximates the surface of the Earth locally or globally, and is the reference for the system of geodetic coordinates. Each geodetic coordinate system is based on a datum. 6.1.7 Transformation Transformation is the conversion of coordinates from one coordinate system to another coordinate system. If the coordinate system is georeferenced, transformation can involve datum transformation: the conversion of geodetic coordinates from one geodetic datum to another geodetic datum, usually involving changes in the shape, orientation, and center position of the reference ellipsoid. 6.2 Geodetic Coordinate Support Effective with Oracle9i, Spatial provides a rational and complete treatment of geodetic coordinates. Before Oracle9i, Spatial computations were based solely on flat (Cartesian) coordinates, regardless of the coordinate system specified for the layer of geometries. Consequently, computations for data in geodetic coordinate systems were Geodetic Coordinate Support Coordinate Systems (Spatial Reference Systems) 6-3 inaccurate, because they always treated the coordinates as if they were on a flat surface, and they did not consider the curvature of the surface. Effective with release 9.2, ellipsoidal surface computations consider the curvatures of the Earth in the specified geodetic coordinate system and return correct, accurate results. In other words, Spatial queries return the right answers all the time. 6.2.1 Geodesy and Two-Dimensional Geometry A two-dimensional geometry is a surface geometry, but the important question is: What is the surface? A flat surface (plane) is accurately represented by Cartesian coordinates. However, Cartesian coordinates are not adequate for representing the surface of a solid. A commonly used surface for spatial geometry is the surface of the Earth, and the laws of geometry there are different than they are in a plane. For example, on the Earth’s surface there are no parallel lines: lines are geodesics, and all geodesics intersect. Thus, closed curved surface problems cannot be done accurately with Cartesian geometry. Spatial provides accurate results regardless of the coordinate system or the size of the area involved, without requiring that the data be projected to a flat surface. The results are accurate regardless of where on the Earth’s surface the query is focused, even in "special" areas such as the poles. Thus, you can store coordinates in any datum and projections that you choose, and you can perform accurate queries regardless of the coordinate system. 6.2.2 Choosing a Geodetic or Projected Coordinate System For applications that deal with the Earth’s surface, the data can be represented using a geodetic coordinate system or a projected plane coordinate system. In deciding which approach to take with the data, consider any needs related to accuracy and performance: ■ Accuracy For many spatial applications, the area is sufficiently small to allow adequate computations on Cartesian coordinates in a local projection. For example, the New Hampshire State Plane local projection provides adequate accuracy for most spatial applications that use data for that state. However, Cartesian computations on a plane projection will never give accurate results for a large area such as Canada or Scandinavia. For example, a query asking if Stockholm, Sweden and Helsinki, Finland are within a specified distance may return an incorrect result if the specified distance is close to the actual measured distance. Computations involving large areas or requiring very precise accuracy must account for the curvature of the Earth’s surface. ■ Performance Spherical computations use more computing resources than Cartesian computations. Some operations using geodetic coordinates may take longer to complete than the same operations using Cartesian coordinates. 6.2.3 Choosing Non-Ellipsoidal or Ellipsoidal Height This section discusses guidelines for choosing the appropriate type of height for three-dimensional data: non-ellipsoidal or ellipsoidal. Although ellipsoidal height is widely used and is the default for many GPS applications, and although ellipsoidal computations incur less performance overhead in many cases, there are applications for which a non-ellipsoidal height may be preferable or even necessary. Geodetic Coordinate Support 6-4 Oracle Spatial Developer's Guide Also, after any initial decision, you can change the reference height type, because transformations between different height datums are supported. 6.2.3.1 Non-Ellipsoidal Height Non-ellipsoidal height is measured from some point other than the reference ellipsoid. Some common non-ellipsoidal measurements of height are from ground level, mean sea level (MSL), or the reference geoid. ■ Ground level: Measuring height from the ground level is conceptually the simplest approach, and it is common in very local or informal applications. For example, when modeling a single building or a cluster of buildings, ground level may be adequate. Moreover, if you ever need to integrate local ground height with a global height datum, you can achieve this with a transformation (EPSG method 9616) adding a local constant reference height. If you need to model local terrain undulations, you can achieve this with a transformation using an offset matrix (EPSG method 9635), just as you can between the geoid and the ellipsoid. ■ Mean sea level (MSL): MSL is a common variation of sea level that provides conceptual simplicity, ignoring local variations and changes over time in sea level. It can also be extrapolated to areas covered by land. Height relative to MSL is useful for a variety of applications, such as those dealing with flooding risk, gravitational potential, and how thin the air is. MSL is commonly used for the heights of aircraft in flight. ■ Geoid: The geoid, the equipotential surface closest to MSL, provides the most precise measurements of height in terms of gravitational pull, factoring in such things as climate and tectonic changes. The geoid can deviate from MSL by approximately 2 meters (plus or minus). If an application is affected more by purely gravitational effects than by actual local sea level, you may want to use the geoid as the reference rather than MSL. To perform transformations between MSL, geoid, or ellipsoid, you can use EPSG method 9635 and the appropriate time-stamped offset matrix. Because most non-ellipsoidal height references are irregular and undulating surfaces, transformations between them are more complicated than with ellipsoidal heights. One approach is to use an offset grid file to define the transformation. This approach is implemented in EPSG method 9635. The grid file has to be acquired (often available publicly from government web sites). Moreover, because most such non-ellipsoidal height datums (including the geoid, sea level, and local terrain) change over time, the timestamp of an offset matrix may matter, even if not by much. (Of course, the same principle applies to ellipsoids as well, since they are not static in the long term. After all, they are intended to approximate the changing geoid, MSL, or terrain.) Regarding performance and memory usage with EPSG method 9635, at run time the grid must be loaded before the transformation of a dataset. This load operation temporarily increases the footprint in main memory and incurs one-time loading overhead. If an entire dataset is transformed, the overhead can be relatively insignificant; however, if frequent transformations are performed on single geometries, the cumulative overhead can become significant. 6.2.3.2 Ellipsoidal Height Ellipsoidal height is measured from a point on the reference ellipsoid. The ellipsoid is a convenient and relatively faithful approximation of the Earth. Although using an ellipsoid is more complex than using a sphere to represent the Earth, using an ellipsoid Geodetic Coordinate Support Coordinate Systems (Spatial Reference Systems) 6-5 is, for most applications, simpler than using a geoid or local heights (although with some sacrifice in precision). Moreover, geoidal and sea-level heights are often not well suited for mathematical analysis, because the undulating and irregular shapes would make certain computations prohibitively complex and expensive. GPS applications often assume ellipsoidal height as a reference and use it as the default. Because the ellipsoid is chosen to match the geoid (and similar sea level), ellipsoidal height tends not to deviate far from MSL height. For example, the geoid diverges from the NAD83 ellipsoid by only up to 50 meters. Other ellipsoids may be chosen to match a particular country even more closely. Even if different parties use different ellipsoids, a WKT can conveniently describe such differences. A simple datum transformation can efficiently and accurately perform transformations between ellipsoids. Because no offset matrix is involved, no loading overhead is required. Thus, interoperability is simplified with ellipsoidal height, although future requirements or analysis might necessitate the use of MSL, a geoid, or other non-ellipsoidal height datums. 6.2.4 Geodetic MBRs To create a query window for certain operations on geodetic data, use an MBR (minimum bounding rectangle) by specifying an SDO_ETYPE value of 1003 or 2003 (optimized rectangle) and an SDO_INTERPRETATION value of 3, as described in Table 2–2 in Section 2.2.4. A geodetic MBR can be used with the following operators: SDO_FILTER, SDO_RELATE with the ANYINTERACT mask, SDO_ANYINTERACT, and SDO_WITHIN_DISTANCE. Example 6–1 requests the names of all cola markets that are likely to interact spatially with a geodetic MBR. Example 6–1 Using a Geodetic MBR SELECT c.name FROM cola_markets_cs c WHERE SDO_FILTER(c.shape, SDO_GEOMETRY( 2003, 8307, -- SRID for WGS 84 longitude/latitude NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(6,5, 10,10)) ) = 'TRUE'; Example 6–1 produces the following output (assuming the data as defined in Example 6–17 in Section 6.13): NAME -------------------------------- cola_c cola_b cola_d The following considerations apply to the use of geodetic MBRs: ■ Do not use a geodetic MBR with spatial objects stored in the database. Use it only to construct a query window. ■ The lower-left Y coordinate (minY) must be less than the upper-right Y coordinate (maxY). If the lower-left X coordinate (minX) is greater than the upper-right X coordinate (maxX), the window is assumed to cross the date line meridian (that is, the meridian "opposite" the prime meridian, or both 180 and -180 longitude). For Geodetic Coordinate Support 6-6 Oracle Spatial Developer's Guide example, an MBR of (-10,10, -100, 20) with longitude/latitude data goes three-fourths of the way around the Earth (crossing the date line meridian), and goes from latitude lines 10 to 20. ■ When Spatial constructs the MBR internally for the query, lines along latitude lines are densified by adding points at one-degree intervals. This might affect results for objects within a few meters of the edge of the MBR (especially objects in the middle latitudes in both hemispheres). ■ When an optimized rectangle spans more than 119 degrees in longitude, it is internally divided into three rectangles; and as a result, these three rectangles share an edge that is the common boundary between them. If you validate the geometry of such an optimized rectangle, error code 13351 is returned because the internal rectangles have a shared edge. You can use such an optimized rectangle for queries with only the following: SDO_ANYINTERACT operator, SDO_ RELATE operator with the ANYINTERACT mask, or SDO_GEOM.RELATE function with the ANYINTERACT mask. (Any other queries on such an optimized rectangle may return incorrect results.) The following additional examples show special or unusual cases, to illustrate how a geodetic MBR is interpreted with longitude/latitude data: ■ (10,0, -110,20) crosses the date line meridian and goes most of the way around the world, and goes from the equator to latitude 20. ■ (10,-90, 40,90) is a band from the South Pole to the North Pole between longitudes 10 and 40. ■ (10,-90, 40,50) is a band from the South Pole to latitude 50 between longitudes 10 and 40. ■ (-180,-10, 180,5) is a band that wraps the equator from 10 degrees south to 5 degrees north. ■ (-180,-90, 180,90) is the whole Earth. ■ (-180,-90, 180,50) is the whole Earth below latitude 50. ■ (-180,50, 180,90) is the whole Earth above latitude 50. 6.2.5 Other Considerations and Requirements with Geodetic Data The following geometries are not permitted if a geodetic coordinate system is used or if any transformation is being performed (even if the transformation is from one projected coordinate system to another projected coordinate system): ■ Circles ■ Circular arcs Geodetic coordinate system support is provided only for geometries that consist of points or geodesics (lines on the ellipsoid). If you have geometries containing circles or circular arcs in a projected coordinate system, you can densify them using the SDO_ GEOM.SDO_ARC_DENSIFY function (documented in Chapter 24) before transforming them to geodetic coordinates, and then perform Spatial operations on the resulting geometries. The following size limits apply with geodetic data: ■ No polygon element can have an area larger than or equal to one-half the surface of the Earth. Moreover, if the result of a union of two polygons is greater than one-half the surface of the Earth, the operation will not produce a correct result. For example, if A union B results in a polygon that is greater than one-half of the Local Coordinate Support Coordinate Systems (Spatial Reference Systems) 6-7 area of the Earth, the operations A difference B, A intersection B, and A XOR B are not supported, and only a relate operation with the ANYINTERACT mask is supported between those two polygons. ■ In a line, the distance between two adjacent coordinates cannot be greater than or equal to one-half the perimeter (a great circle) of the Earth. If you need to work with larger elements, first break these elements into multiple smaller elements and work with them. For example, you cannot create a geometry representing the entire ocean surface of the Earth; however, you can create multiple geometries, each representing part of the overall ocean surface. To work with a line string that is greater than or equal to one-half the perimeter of the Earth, you can add one or more intermediate points on the line so that all adjacent coordinates are less than one-half the perimeter of the Earth. Tolerance is specified as meters for geodetic layers. If you use tolerance values that are typical for non-geodetic data, these values are interpreted as meters for geodetic data. For example, if you specify a tolerance value of 0.05 for geodetic data, this is interpreted as precise to 5 centimeters. If this value is more precise than your applications need, performance may be affected because of the internal computational steps taken to implement the specified precision. (For more information about tolerance, see Section 1.5.5.) For geodetic layers, you must specify the dimensional extents in the index metadata as -180,180 for longitude and -90,90 for latitude. The following statement (from Example 6–17 in Section 6.13) specifies these extents (with a 10-meter tolerance value in each dimension) for a geodetic data layer: INSERT INTO user_sdo_geom_metadata (TABLE_NAME, COLUMN_NAME, DIMINFO, SRID) VALUES ( 'cola_markets_cs', 'shape', SDO_DIM_ARRAY( SDO_DIM_ELEMENT('Longitude', -180, 180, 10), -- 10 meters tolerance SDO_DIM_ELEMENT('Latitude', -90, 90, 10) -- 10 meters tolerance ), 8307 -- SRID for 'Longitude / Latitude (WGS 84)' coordinate system ); See Section 6.10 for additional notes and restrictions relating to geodetic data. 6.3 Local Coordinate Support Spatial provides a level of support for local coordinate systems. Local coordinate systems are often used in CAD systems, and they can also be used in local surveys where the relationship between the surveyed site and the rest of the world is not important. Several local coordinate systems are predefined and included with Spatial in the SDO_ COORD_REF_SYS table (described in Section 6.7.9). These supplied local coordinate systems, whose names start with Non-Earth, define non-Earth Cartesian coordinate systems based on different units of measurement (Meter, Millimeter, Inch, and so on). In the current release, you cannot perform coordinate system transformation between local and Earth-based coordinate systems; and when transforming a geometry or layer of geometries between local coordinate systems, you can only to convert coordinates EPSG Model and Spatial 6-8 Oracle Spatial Developer's Guide in a local coordinate system from one unit of measurement to another (for example, inches to millimeters). However, you can perform all other Spatial operations (for example, using SDO_RELATE, SDO_WITHIN_DISTANCE, and other operators) with local coordinate systems. 6.4 EPSG Model and Spatial The Oracle Spatial coordinate system support is based on, but is not always identical to, the European Petroleum Survey Group (EPSG) data model and dataset. These are described in detail at http://www.epsg.org, and the download for the EPSG geodetic parameter dataset includes a "Readme" that contains an entity-relationship (E-R) diagram. The approach taken by Oracle Spatial provides the benefits of standardization, expanded support, and flexibility: ■ The EPSG model is a comprehensive and widely accepted standard for data representation, so users familiar with it can more easily understand Spatial storage and operations. ■ Support is provided for more coordinate systems and their associated datums, ellipsoids, and projections. For example, some of the EPSG geographic and projected coordinate systems had no counterpart among coordinate systems supported for previous Spatial releases. Their addition results in an expanded set of supported coordinate systems. ■ Data transformations are more flexible. Instead of there being only one possible Oracle-defined transformation path between a given source and target coordinate system, you can specify alternative paths to be used for a specific area of applicability (that is, use case) or as the systemwide default. The rest of this section describes this flexibility. For data transformations (that is, transforming data from one coordinate system to another), you can now control which transformation rules are to be applied. In previous releases, and in the current release by default, Spatial performs transformations based only on the specified source and target coordinate systems, using predetermined intermediate transformation steps. The assumption behind that default approach is that there is a single correct or preferable transformation chain. By default, then, Spatial applies certain transformation methods for each supported transformation between specific pairs of source and target coordinate systems. For example, there are over 500 supported transformations from specific coordinate systems to the WGS 84 (longitude/latitude) coordinate system, which has the EPSG SRID value of 4326. As one example, for a transformation from SRID 4605 to SRID 4326, Spatial can use the transformation method with the COORD_OP_ID value 1445, as indicated in the SDO_COORD_OPS table (described in Section 6.7.8), which contains one row for each transformation operation between coordinate systems. However, you can override the default transformation by specifying a different method (from the set of Oracle-supplied methods) for the transformation for any given source and target SRID combination. You can specify a transformation as the new systemwide default, or you can associate the transformation with a named use case that can be specified when transforming a layer of spatial geometries. (A use case is simply a name given to a usage scenario or area of applicability, such as Project XYZ or Mike's Favorite Transformations; there is no relationship between use cases and database users or schemas.) To specify a transformation as either the systemwide default or associated with a use case, use the SDO_CS.ADD_PREFERENCE_FOR_OP procedure. To remove a Three-Dimensional Coordinate Reference System Support Coordinate Systems (Spatial Reference Systems) 6-9 previously specified preference, use the SDO_CS.REVOKE_PREFERENCE_FOR_OP procedure. When it performs a coordinate system transformation, Spatial follows these general steps to determine the specific transformation to use: 1. If a use case has been specified, the transformation associated with that use case is applied. 2. If no use case has been specified and if a user-defined systemwide transformation has been created for the specified source and target coordinate system pair, that transformation is applied. 3. If no use case has been specified and if no user-defined transformation exists for the specified source and target coordinate system pair, the behavior depends on whether or not EPSG rules have been created, such as by the SDO_CS.CREATE_ OBVIOUS_EPSG_RULES procedure: ■ If the EPSG rules have been created and if an EPSG rule is defined for this transformation, the EPSG transformation is applied. ■ If the EPSG rules have not been created, or if they have been created but no EPSG rule is defined for this transformation, the Oracle Spatial default transformation is applied. 6.5 Three-Dimensional Coordinate Reference System Support The Oracle Spatial support for three-dimensional coordinate reference systems complies with the EPSG model (described in Section 6.4), which provides the following types of coordinate reference systems: ■ Geographic 2D ■ Projected 2D ■ Geographic 3D, which consists of Geographic 2D plus ellipsoidal height, with longitude, latitude, and height based on the same ellipsoid and datum ■ Compound, which consists of either Geographic 2D plus gravity-related height or Projected 2D plus gravity-related height Thus, there are two categories of three-dimensional coordinate reference systems: those based on ellipsoidal height (geographic 3D, described in Section 6.5.1) and those based on gravity-related height (compound, described in Section 6.5.2). Three-dimensional computations are more accurate than their two-dimensional equivalents, particularly when they are chained: For example, datum transformations internally always are performed in three dimensions, regardless of the dimensionality of the source and target CRS and geometries. When two-dimensional geometries are involved, one or more of the following can occur: 1. When the input or output geometries and CRS are two-dimensional, the (unspecified) input height defaults to zero (above the ellipsoid, depending on the CRS) for any internal three-dimensional computations. This is a potential source of inaccuracy, unless the height was intended to be exactly zero. (Data can be two-dimensional because height values were originally either unavailable or not considered important; this is different from representing data in two dimensions because heights are known to be exactly zero. 2. The transformation might then internally result in a non-zero height. Since the two-dimensional target CRS cannot accommodate the height value, the height value must be truncated, resulting in further inaccuracy. Three-Dimensional Coordinate Reference System Support 6-10 Oracle Spatial Developer's Guide 3. If further transformations are chained, the repeated truncation of height values can result in increasing inaccuracies. Note that an inaccurate input height can affect not only the output height of a transformation, but also the longitude and latitude. However, if the source and target CRS are three-dimensional, there is no repeated truncation of heights. Consequently, accuracy is increased, particularly for transformation chains. For an introduction to support in Spatial for three-dimensional geometries, see Section 1.11. 6.5.1 Geographic 3D Coordinate Reference Systems A geographic three-dimensional coordinate reference system is based on longitude and latitude, plus ellipsoidal height. The ellipsoidal height is the height relative to a reference ellipsoid, which is an approximation of the real Earth. All three dimensions of the CRS are based on the same ellipsoid. Using ellipsoidal heights enables Spatial to perform internal operations with great mathematical regularity and efficiency. Compound coordinate reference systems, on the other hand, require more complex transformations, often based on offset matrixes. Some of these matrixes have to be downloaded and configured. Furthermore, they might have a significant footprint, on disk and in main memory. The supported geographic 3D coordinate reference systems are listed in the SDO_ CRS_GEOGRAPHIC3D view, described in Section 6.7.16. 6.5.2 Compound Coordinate Reference Systems A compound three-dimensional coordinate reference system is based on a geographic or projected two-dimensional system, plus gravity-related height. Gravity-related height is the height as influenced by the Earth’s gravitational force, where the base height (zero) is often an equipotential surface, and might be defined as above or below "sea level." Gravity-related height is a more complex representation than ellipsoidal height, because of gravitational irregularities such as the following: ■ Orthometric height Orthometric height is also referred to as the height above the geoid. The geoid is an equipotential surface that most closely (but not exactly) matches mean sea level. An equipotential surface is a surface on which each point is at the same gravitational potential level. Such a surface tends to undulate slightly, because the Earth has regions of varying density. There are multiple equipotential surfaces, and these might not be parallel to each other due to the irregular density of the Earth. ■ Height relative to mean sea level, to sea level at a specific location, or to a vertical network warped to fit multiple tidal stations (for example, NGVD 29) Sea level is close to, but not identical to, the geoid. The sea level at a given location is often defined based on the "average sea level" at a specific port. The supported compound coordinate reference systems are listed in the SDO_CRS_ COMPOUND view, described in Section 6.7.12. You can create a customized compound coordinate reference system, which combines a horizontal CRS with a vertical CRS. (The horizontal CRS contains two dimensions, such as X and Y or longitude and latitude, and the vertical CRS contains the third Three-Dimensional Coordinate Reference System Support Coordinate Systems (Spatial Reference Systems) 6-11 dimension, such as Z or height or altitude.) Section 6.9.4 explains how to create a compound CRS. 6.5.3 Three-Dimensional Transformations Spatial supports three-dimensional coordinate transformations for SDO_GEOMETRY objects directly, and indirectly for point clouds and TINs. (For example, a point cloud must be transformed to a table with an SDO_GEOMETRY column.) The supported transformations include the following: ■ Three-dimensional datum transformations ■ Transformations between ellipsoidal and gravity-related height For three-dimensional datum transformations, the datum transformation between the two ellipsoids is essentially the same as for two-dimensional coordinate reference systems, except that the third dimension is considered instead of ignored. Because height values are not ignored, the accuracy of the results increases, especially for transformation chains. For transformations between ellipsoidal and gravity-related height, computations are complicated by the fact that equipotential and other gravity-related surfaces tend to undulate, compared to any ellipsoid and to each other. Transformations might be based on higher-degree polynomial functions or bilinear interpolation. In either case, a significant parameter matrix is required to define the transformation. For transforming between gravity-related and ellipsoidal height, the process usually involves a transformation, based on an offset matrix, between geoidal and ellipsoidal height. Depending on the source or target definition of the offset matrix, a common datum transformation might have to be appended or prefixed. Example 6–2 shows a three-dimensional datum transformation. Example 6–2 Three-Dimensional Datum Transformation set numwidth 9 CREATE TABLE source_geoms ( mkt_id NUMBER PRIMARY KEY, name VARCHAR2(32), GEOMETRY SDO_GEOMETRY); INSERT INTO source_geoms VALUES( 1, 'reference geom', SDO_GEOMETRY( 3001, 4985, SDO_POINT_TYPE( 4.0, 55.0, 1.0), NULL, NULL)); INSERT INTO USER_SDO_GEOM_METADATA VALUES ( 'source_geoms', 'GEOMETRY', SDO_DIM_ARRAY( SDO_DIM_ELEMENT('Longitude', -180, 180, 10), SDO_DIM_ELEMENT('Latitude', -90, 90, 10), Three-Dimensional Coordinate Reference System Support 6-12 Oracle Spatial Developer's Guide SDO_DIM_ELEMENT('Height', -1000,1000, 10)), 4985); commit; -------------------------------------------------------------------------------- CALL SDO_CS.TRANSFORM_LAYER( 'source_geoms', 'GEOMETRY', 'GEO_CS_4979', 4979); INSERT INTO USER_SDO_GEOM_METADATA VALUES ( 'GEO_CS_4979', 'GEOMETRY', SDO_DIM_ARRAY( SDO_DIM_ELEMENT('Longitude', -180, 180, 10), SDO_DIM_ELEMENT('Latitude', -90, 90, 10), SDO_DIM_ELEMENT('Height', -1000,1000, 10)), 4979); set lines 210; -------------------------------------------------------------------------------- CALL SDO_CS.TRANSFORM_LAYER( 'GEO_CS_4979', 'GEOMETRY', 'source_geoms2', 4985); INSERT INTO USER_SDO_GEOM_METADATA VALUES ( 'source_geoms2', 'GEOMETRY', SDO_DIM_ARRAY( SDO_DIM_ELEMENT('Longitude', -180, 180, 10), SDO_DIM_ELEMENT('Latitude', -90, 90, 10), SDO_DIM_ELEMENT('Height', -1000,1000, 10)), 4985); -------------------------------------------------------------------------------- DELETE FROM USER_SDO_GEOM_METADATA WHERE table_name = 'GEO_CS_4979'; DELETE FROM USER_SDO_GEOM_METADATA WHERE table_name = 'SOURCE_GEOMS'; DELETE FROM USER_SDO_GEOM_METADATA WHERE table_name = 'SOURCE_GEOMS2'; drop table GEO_CS_4979; drop table source_geoms; drop table source_geoms2; As a result of the transformation in Example 6–2, (4, 55, 1) is transformed to (4.0001539, 55.0000249, 4.218). Example 6–3 configures a transformation between geoidal and ellipsoidal height, using a Hawaii offset grid. Note that without the initial creation of a rule (using the SDO_CS.CREATE_PREF_CONCATENATED_OP procedure), the grid would not be used. Three-Dimensional Coordinate Reference System Support Coordinate Systems (Spatial Reference Systems) 6-13 Example 6–3 Transformation Between Geoidal And Ellipsoidal Height -- Create Sample operation: insert into mdsys.sdo_coord_ops ( COORD_OP_ID, COORD_OP_NAME, COORD_OP_TYPE, SOURCE_SRID, TARGET_SRID, COORD_TFM_VERSION, COORD_OP_VARIANT, COORD_OP_METHOD_ID, UOM_ID_SOURCE_OFFSETS, UOM_ID_TARGET_OFFSETS, INFORMATION_SOURCE, DATA_SOURCE, SHOW_OPERATION, IS_LEGACY, LEGACY_CODE, REVERSE_OP, IS_IMPLEMENTED_FORWARD, IS_IMPLEMENTED_REVERSE) values ( 1000000005, 'Test Bi-linear Interpolation', 'CONVERSION', null, null, null, null, 9635, null, null, 'Oracle', 'Oracle', 1, 'FALSE', null, 1, 1, 1); --Create sample parameters, pointing to the offset file --(in this case reusing values from an existing operation): insert into mdsys.sdo_coord_op_param_vals ( coord_op_id, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, PARAM_VALUE_FILE, PARAM_VALUE_XML, UOM_ID) ( select 1000000005, 9635, 8666, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, PARAM_VALUE_FILE, PARAM_VALUE_XML, Three-Dimensional Coordinate Reference System Support 6-14 Oracle Spatial Developer's Guide UOM_ID from mdsys.sdo_coord_op_param_vals where coord_op_id = 999998 and parameter_id = 8666); --Create a rule to use this operation between SRIDs 7406 and 4359: call sdo_cs.create_pref_concatenated_op( 300, 'CONCATENATED OPERATION', TFM_PLAN(SDO_TFM_CHAIN(7406, 1000000005, 4359)), NULL); -- Now, actually perform the transformation: set numformat 999999.99999999 -- Create the source table CREATE TABLE source_geoms ( mkt_id NUMBER PRIMARY KEY, name VARCHAR2(32), GEOMETRY SDO_GEOMETRY); INSERT INTO source_geoms VALUES( 1, 'reference geom', SDO_GEOMETRY( 3001, 7406, SDO_POINT_TYPE( -161, 18, 0), NULL, NULL)); INSERT INTO USER_SDO_GEOM_METADATA VALUES ( 'source_geoms', 'GEOMETRY', SDO_DIM_ARRAY( SDO_DIM_ELEMENT('Longitude', -180, 180, 10), SDO_DIM_ELEMENT('Latitude', -90, 90, 10), SDO_DIM_ELEMENT('Height', -100, 100, 10)), 7406); commit; SELECT GEOMETRY "Source" FROM source_geoms; -------------------------------------------------------------------------------- --Perform the transformation: CALL SDO_CS.TRANSFORM_LAYER( 'source_geoms', 'GEOMETRY', 'GEO_CS_4359', 4359); INSERT INTO USER_SDO_GEOM_METADATA VALUES ( Three-Dimensional Coordinate Reference System Support Coordinate Systems (Spatial Reference Systems) 6-15 'GEO_CS_4359', 'GEOMETRY', SDO_DIM_ARRAY( SDO_DIM_ELEMENT('Longitude', -180, 180, 10), SDO_DIM_ELEMENT('Latitude', -90, 90, 10), SDO_DIM_ELEMENT('Height', -100, 100, 10)), 4359); set lines 210; SELECT GEOMETRY "Target" FROM GEO_CS_4359; -------------------------------------------------------------------------------- --Transform back: CALL SDO_CS.TRANSFORM_LAYER( 'GEO_CS_4359', 'GEOMETRY', 'source_geoms2', 7406); INSERT INTO USER_SDO_GEOM_METADATA VALUES ( 'source_geoms2', 'GEOMETRY', SDO_DIM_ARRAY( SDO_DIM_ELEMENT('Longitude', -180, 180, 10), SDO_DIM_ELEMENT('Latitude', -90, 90, 10), SDO_DIM_ELEMENT('Height', -100, 100, 10)), 7406); SELECT GEOMETRY "Source2" FROM source_geoms2; -------------------------------------------------------------------------------- --Clean up (regarding the transformation): DELETE FROM USER_SDO_GEOM_METADATA WHERE table_name = 'GEO_CS_4359'; DELETE FROM USER_SDO_GEOM_METADATA WHERE table_name = 'SOURCE_GEOMS'; DELETE FROM USER_SDO_GEOM_METADATA WHERE table_name = 'SOURCE_GEOMS2'; drop table GEO_CS_4359; drop table source_geoms; drop table source_geoms2; --Clean up (regarding the rule): CALL sdo_cs.delete_op(300); delete from mdsys.sdo_coord_op_param_vals where coord_op_id = 1000000005; delete from mdsys.sdo_coord_ops where coord_op_id = 1000000005; COMMIT; With the configuration in Example 6–3: ■ Without the rule, (-161.00000000, 18.00000000, .00000000) is transformed to (-161.00127699, 18.00043360, 62.03196364), based simply on a datum transformation. ■ With the rule, (-161.00000000, 18.00000000, .00000000) is transformed to (-161.00000000, 18.00000000, 6.33070000). Three-Dimensional Coordinate Reference System Support 6-16 Oracle Spatial Developer's Guide 6.5.4 Cross-Dimensionality Transformations You cannot directly perform a cross-dimensionality transformation (for example, from a two-dimensional geometry to a three-dimensional geometry) using the SDO_ CS.TRANSFORM function or the SDO_CS.TRANSFORM_LAYER procedure. However, you can use the SDO_CS.MAKE_3D function to convert a two-dimensional geometry to a three-dimensional geometry, or the SDO_CS.MAKE_2D function to convert a three-dimensional geometry to a two-dimensional geometry; and you can use the resulting geometry to perform a transformation into a geometry with the desired number of dimensions. For example, transforming a two-dimensional geometry into a three-dimensional geometry involves using the SDO_CS.MAKE_3D function. This function does not itself perform any coordinate transformation, but simply adds a height value and sets the target SRID. You must choose an appropriate target SRID, which should be the three-dimensional equivalent of the source SRID. For example, three-dimensional WGS84 (4327) is the equivalent of two-dimensional WGS84 (4326). If necessary, modify height values of vertices in the returned geometry. There are many options for how to use the SDO_CS.MAKE_3D function, but the simplest is the following: 1. Transform from the two-dimensional source SRID to two-dimensional WGS84 (4326). 2. Call SDO_CS.MAKE_3D to convert the geometry to three-dimensional WGS84 (4327) 3. Transform from three-dimensional WGS84 (4327) to the three-dimensional target SRID. Example 6–4 transforms a two-dimensional point from SRID 27700 to two-dimensional SRID 4326, converts the result of the transformation to a three-dimensional point with SRID 4327, and transforms the converted point to three-dimensional SRID 4327. Example 6–4 Cross-Dimensionality Transformation SELECT SDO_CS.TRANSFORM( SDO_CS.MAKE_3D( SDO_CS.TRANSFORM( SDO_GEOMETRY( 2001, 27700, SDO_POINT_TYPE(577274.984, 69740.4923, NULL), NULL, NULL), 4326), height => 0, target_srid => 4327), 4327) "27700 > 4326 > 4327 > 4327" FROM DUAL; 27700 > 4326 > 4327 > 4327(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INF -------------------------------------------------------------------------------- SDO_GEOMETRY(3001, 4327, SDO_POINT_TYPE(.498364058, 50.5006366, 0), NULL, NULL) Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-17 6.6 TFM_PLAN Object Type The object type TFM_PLAN is used is by several SDO_CS package subprograms to specify a transformation plan. For example, to create a concatenated operation that consists of two operations specified by a parameter of type TFM_PLAN, use the SDO_ CS.CREATE_CONCATENATED_OP procedure. Oracle Spatial defines the object type TFM_PLAN as: CREATE TYPE tfm_plan AS OBJECT ( THE_PLAN SDO_TFM_CHAIN); The SDO_TFM_CHAIN type is defined as VARRAY(1048576) OF NUMBER. Within the SDO_TFM_CHAIN array: ■ The first element specifies the SRID of the source coordinate system. ■ Each pair of elements after the first element specifies an operation ID and the SRID of a target coordinate system. 6.7 Coordinate Systems Data Structures The coordinate systems functions and procedures use information provided in the tables and views supplied with Oracle Spatial. The tables and views are part of the MDSYS schema; however, public synonyms are defined, so you do not need to specify MDSYS. before the table or view name. The definitions and data in these tables and views are based on the EPSG data model and dataset, as explained in Section 6.4. The coordinate system tables fit into several general categories: ■ Coordinate system general information: SDO_COORD_SYS, SDO_COORD_REF_ SYS ■ Elements or aspects of a coordinate system definition: SDO_DATUMS, SDO_ ELLIPSOIDS, SDO_PRIME_MERIDIANS ■ Datum transformation support: SDO_COORD_OPS, SDO_COORD_OP_ METHODS, SDO_COORD_OP_PARAM_USE, SDO_COORD_OP_PARAM_VALS, SDO_COORD_OP_PARAMS, SDO_COORD_OP_PATHS, SDO_PREFERRED_ OPS_SYSTEM, SDO_PREFERRED_OPS_USER ■ Others related to coordinate system definition: SDO_COORD_AXES, SDO_ COORD_AXIS_NAMES, SDO_UNITS_OF_MEASURE Several views are provided that are identical to or subsets of coordinate system tables: ■ SDO_COORD_REF_SYSTEM, which contains the same columns as the SDO_ COORD_REF_SYS table. Use the SDO_COORD_REF_SYSTEM view instead of the COORD_REF_SYS table for any insert, update, or delete operations. ■ Subsets of SDO_DATUMS, selected according to the value in the DATUM_TYPE column: SDO_DATUM_ENGINEERING, SDO_DATUM_GEODETIC, SDO_ DATUM_VERTICAL. ■ Subsets of SDO_COORD_REF_SYS, selected according to the value in the COORD_REF_SYS_KIND column: SDO_CRS_COMPOUND, SDO_CRS_ ENGINEERING, SDO_CRS_GEOCENTRIC, SDO_CRS_GEOGRAPHIC2D, SDO_ CRS_GEOGRAPHIC3D, SDO_CRS_PROJECTED, SDO_CRS_VERTICAL. Most of the rest of this section explains these tables and views, in alphabetical order. (Many column descriptions are adapted or taken from EPSG descriptions.) Section 6.7.28 describes relationships among the tables and views, and it lists EPSG Coordinate Systems Data Structures 6-18 Oracle Spatial Developer's Guide table names and their corresponding Oracle Spatial names. Section 6.7.29 describes how to find information about EPSG-based coordinate systems, and it provides several examples. In addition to the tables and views in this section, Spatial provides several legacy tables whose definitions and data match those of certain Spatial system tables used in previous releases. Section 6.8 describes the legacy tables. 6.7.1 SDO_COORD_AXES Table The SDO_COORD_AXES table contains one row for each coordinate system axis definition. This table contains the columns shown in Table 6–1. 6.7.2 SDO_COORD_AXIS_NAMES Table The SDO_COORD_AXIS_NAMES table contains one row for each axis that can be used in a coordinate system definition. This table contains the columns shown in Table 6–2. Note: You should not modify or delete any Oracle-supplied information in any of the tables or views that are used for coordinate system support. If you want to create a user-defined coordinate system, see Section 6.9. Table 6–1 SDO_COORD_AXES Table Column Name Data Type Description COORD_SYS_ID NUMBER(10) ID number of the coordinate system to which this axis applies. COORD_AXIS_ NAME_ID NUMBER(10) ID number of a coordinate system axis name. Matches a value in the COORD_AXIS_NAME_ID column of the SDO_COORD_AXIS_NAMES table (described in Section 6.7.2). Example: 9901 (for Geodetic latitude) COORD_AXIS_ ORIENTATION VARCHAR2(24) The direction of orientation for the coordinate system axis. Example: east COORD_AXIS_ ABBREVIATION VARCHAR2(24) The abbreviation for the coordinate system axis orientation. Example: E UOM_ID NUMBER(10) ID number of the unit of measurement associated with the axis. Matches a value in the UOM_ID column of the SDO_UNITS_OF_MEASURE table (described in Section 6.7.27). ORDER NUMBER(5) Position of this axis within the coordinate system (1, 2, or 3). Table 6–2 SDO_COORD_AXIS_NAMES Table Column Name Data Type Description COORD_AXIS_ NAME_ID NUMBER(10) ID number of the coordinate axis name. Example: 9926 COORD_AXIS_ NAME VARCHAR2(80) Name of the coordinate axis. Example: Spherical latitude Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-19 6.7.3 SDO_COORD_OP_METHODS Table The SDO_COORD_OP_METHODS table contains one row for each coordinate systems transformation method. This table contains the columns shown in Table 6–3. 6.7.4 SDO_COORD_OP_PARAM_USE Table The SDO_COORD_OP_PARAM_USE table contains one row for each combination of transformation method and transformation operation parameter that is available for use. This table contains the columns shown in Table 6–4. Table 6–3 SDO_COORD_OP_METHODS Table Column Name Data Type Description COORD_OP_ METHOD_ID NUMBER(10) ID number of the coordinate system transformation method. Example: 9613 COORD_OP_ METHOD_NAME VARCHAR2(50) Name of the method. Example: NADCON LEGACY_NAME VARCHAR2(50) Name for this transformation method in the legacy WKT strings. This name might differ syntactically from the name used by EPSG. REVERSE_OP NUMBER(1) Contains 1 if reversal of the transformation (from the current target coordinate system to the source coordinate system) can be achieved by reversing the sign of each parameter value; contains 0 if a separate operation must be defined for reversal of the transformation. INFORMATION_ SOURCE VARCHAR2(254) Origin of this information. Example: US Coast and geodetic Survey - http://www.ngs.noaa.gov DATA_SOURCE VARCHAR2(40) Organization providing the data for this record. Example: EPSG IS_ IMPLEMENTED_ FORWARD NUMBER(1) Contains 1 if the forward operation is implemented; contains 0 if the forward operation is not implemented. IS_ IMPLEMENTED_ REVERSE NUMBER(1) Contains 1 if the reverse operation is implemented; contains 0 if the reverse operation is not implemented. Table 6–4 SDO_COORD_OP_PARAM_USE Table Column Name Data Type Description COORD_OP_ METHOD_ID NUMBER(10) ID number of the coordinate system transformation method. Matches a value in the COORD_OP_ METHOD_ID column of the COORD_OP_ METHODS table (described in Section 6.7.3). PARAMETER_ID NUMBER(10) ID number of the parameter for transformation operations. Matches a value in the PARAMETER_ID column of the SDO_COORD_OP_PARAMS table (described in Section 6.7.6). LEGACY_PARAM_ NAME VARCHAR2(80) Open GeoSpatial Consortium (OGC) name for the parameter. SORT_ORDER NUMBER(5) A number indicating the position of this parameter in the sequence of parameters for this method. Example: 2 for the second parameter Coordinate Systems Data Structures 6-20 Oracle Spatial Developer's Guide 6.7.5 SDO_COORD_OP_PARAM_VALS Table The SDO_COORD_OP_PARAM_VALS table contains information about parameter values for each coordinate system transformation method. This table contains the columns shown in Table 6–5. 6.7.6 SDO_COORD_OP_PARAMS Table The SDO_COORD_OP_PARAMS table contains one row for each available parameter for transformation operations. This table contains the columns shown in Table 6–6. PARAM_SIGN_ REVERSAL VARCHAR2(3) Yes if reversal of the transformation (from the current target coordinate system to the source coordinate system) can be achieved by reversing the sign of each parameter value; No if a separate operation must be defined for reversal of the transformation. Table 6–5 SDO_COORD_OP_PARAM_VALS Table Column Name Data Type Description COORD_OP_ID NUMBER(10) ID number of the coordinate transformation operation. Matches a value in the COORD_OP_ID column of the SDO_COORD_OPS table (described in Section 6.7.8). COORD_OP_ METHOD_ID NUMBER(10) Coordinate operation method ID. Must match a COORD_OP_METHOD_ID value in the SDO_ COORD_OP_METHODS table (see Section 6.7.3). PARAMETER_ID NUMBER(10) ID number of the parameter for transformation operations. Matches a value in the PARAMETER_ID column of the SDO_COORD_OP_PARAMS table (described in Section 6.7.6). PARAMETER_ VALUE FLOAT(49) Value of the parameter for this operation. PARAM_VALUE_ FILE_REF VARCHAR2(254) Name of the file (as specified in the original EPSG database) containing the value data, if a single value for the parameter is not sufficient. PARAM_VALUE_ FILE CLOB The ASCII content of the file specified in the PARAM_VALUE_FILE_REF column. Used only for grid file parameters (for NADCON, NTv2, and height transformations "Geographic3D to Geographic2D+GravityRelatedHeight"). PARAM_VALUE_ XML XMLTYPE An XML representation of the content of the file specified in the PARAM_VALUE_FILE_REF column. (Optional, and currently only used for documentation.) UOM_ID NUMBER(10) ID number of the unit of measurement associated with the operation. Matches a value in the UOM_ID column of the SDO_UNITS_OF_MEASURE table (described in Section 6.7.27). Table 6–4 (Cont.) SDO_COORD_OP_PARAM_USE Table Column Name Data Type Description Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-21 6.7.7 SDO_COORD_OP_PATHS Table The SDO_COORD_OP_PATHS table contains one row for each atomic step in a concatenated operation. This table contains the columns shown in Table 6–7. 6.7.8 SDO_COORD_OPS Table The SDO_COORD_OPS table contains one row for each transformation operation between coordinate systems. This table contains the columns shown in Table 6–8. Table 6–6 SDO_COORD_OP_PARAMS Table Column Name Data Type Description PARAMETER_ID NUMBER(10) ID number of the parameter. Example: 8608 PARAMETER_ NAME VARCHAR2(80) Name of the operation. Example: X-axis rotation INFORMATION_ SOURCE VARCHAR2(254) Origin of this information. Example: EPSG guidance note number 7. DATA_SOURCE VARCHAR2(40) Organization providing the data for this record. Example: EPSG Table 6–7 SDO_COORD_OP_PATHS Table Column Name Data Type Description CONCAT_ OPERATION_ID NUMBER(10) ID number of the concatenation operation. Must match a COORD_OP_ID value in the SDO_COORD_ OPS table (described in Section 6.7.8) for which the COORD_OP_TYPE value is CONCATENATION. SINGLE_ OPERATION_ID NUMBER(10) ID number of the single coordinate operation for this step (atomic operation) in a concatenated operation. Must match a COORD_OP_ID value in the SDO_ COORD_OPS table (described in Section 6.7.8). SINGLE_OP_ SOURCE_ID NUMBER(10) ID number of source coordinate reference system for the single coordinate operation for this step. Must match an SRID value in the SDO_COORD_REF_SYS table (described in Section 6.7.9). SINGLE_OP_ TARGET_ID NUMBER(10) ID number of target coordinate reference system for the single coordinate operation for this step. Must match an SRID value in the SDO_COORD_REF_SYS table (described in Section 6.7.9). OP_PATH_STEP NUMBER(5) Sequence number of this step (atomic operation) within this concatenated operation. Table 6–8 SDO_COORD_OPS Table Column Name Data Type Description COORD_OP_ID NUMBER(10) ID number of the coordinate transformation operation. Example: 101 COORD_OP_ NAME VARCHAR2(80) Name of the operation. Example: ED50 to WGS 84 (14) COORD_OP_TYPE VARCHAR2(24) Type of operation. One of the following: CONCATENATED OPERATION, CONVERSION, or TRANSFORMATION SOURCE_SRID NUMBER(10) SRID of the coordinate system from which to perform the transformation. Example: 4230 Coordinate Systems Data Structures 6-22 Oracle Spatial Developer's Guide TARGET_SRID NUMBER(10) SRID of the coordinate system into which to perform the transformation. Example: 4326 COORD_TFM_ VERSION VARCHAR2(24) Name assigned by EPSG to the coordinate transformation. Example: 5Nat-NSea90 COORD_OP_ VARIANT NUMBER(5) A variant of the more generic method specified in COORD_OP_METHOD_ID. Example: 14 COORD_OP_ METHOD_ID NUMBER(10) Coordinate operation method ID. Must match a COORD_OP_METHOD_ID value in the SDO_ COORD_OP_METHODS table (see Section 6.7.3). Several operations can use a method. Example: 9617 UOM_ID_ SOURCE_OFFSETS NUMBER(10) ID number of the unit of measurement for offsets in the source coordinate system. Matches a value in the UOM_ID column of the SDO_UNITS_OF_MEASURE table (described in Section 6.7.27). UOM_ID_ TARGET_OFFSETS NUMBER(10) ID number of the unit of measurement for offsets in the target coordinate system. Matches a value in the UOM_ID column of the SDO_UNITS_OF_MEASURE table (described in Section 6.7.27). INFORMATION_ SOURCE VARCHAR2(254) Origin of this information. Example: Institut de Geomatica; Barcelona DATA_SOURCE VARCHAR2(40) Organization providing the data for this record. Example: EPSG SHOW_ OPERATION NUMBER(3) (Not currently used.) IS_LEGACY VARCHAR2(5) TRUE if the operation was included in Oracle Spatial before release 10.2; FALSE if the operation is new in Oracle Spatial release 10.2. LEGACY_CODE NUMBER(10) For any EPSG coordinate transformation operation that has a semantically identical legacy (in Oracle Spatial before release 10.2) counterpart, the COORD_ OP_ID value of the legacy coordinate transformation operation. REVERSE_OP NUMBER(1) Contains 1 if reversal of the transformation (from the current target coordinate system to the source coordinate system) is defined as achievable by reversing the sign of each parameter value; contains 0 if a separate operation must be defined for reversal of the transformation. If REVERSE_OP contains 1, the operations that are actually implemented are indicated by the values for IS_IMPLEMENTED_ FORWARD and IS_IMPLEMENTED_REVERSE. IS_ IMPLEMENTED_ FORWARD NUMBER(1) Contains 1 if the forward operation is implemented; contains 0 if the forward operation is not implemented. IS_ IMPLEMENTED_ REVERSE NUMBER(1) Contains 1 if the reverse operation is implemented; contains 0 if the reverse operation is not implemented. Table 6–8 (Cont.) SDO_COORD_OPS Table Column Name Data Type Description Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-23 6.7.9 SDO_COORD_REF_SYS Table The SDO_COORD_REF_SYS table contains one row for each coordinate reference system. This table contains the columns shown in Table 6–9. (The SDO_COORD_REF_ SYS table is roughly patterned after the EPSG Coordinate Reference System table.) Note: If you need to perform an insert, update, or delete operation, you must perform it on the SDO_COORD_REF_SYSTEM view, which contains the same columns as the SDO_COORD_REF_SYS table. The SDO_COORD_REF_SYSTEM view is described in Section 6.7.10. Table 6–9 SDO_COORD_REF_SYS Table Column Name Data Type Description SRID NUMBER(10) ID number of the coordinate reference system. Example: 8307 COORD_REF_SYS_ NAME VARCHAR2(80) Name of the coordinate reference system. Example: Longitude / Latitude (WGS 84) COORD_REF_SYS_ KIND VARCHAR2(24) Category for the coordinate system. Example: GEOGRAPHIC2D COORD_SYS_ID NUMBER(10) ID number of the coordinate system used for the coordinate reference system. Must match a COORD_SYS_ID value in the SDO_COORD_SYS table (see Section 6.7.11). DATUM_ID NUMBER(10) ID number of the datum used for the coordinate reference system. Null for a projected coordinate system. For a geodetic coordinate system, must match a DATUM_ID value in the SDO_DATUMS table (see Section 6.7.22). Example: 10115 GEOG_CRS_ DATUM_ID NUMBER(10) ID number of the datum used for the coordinate reference system. For a projected coordinate system, must match the DATUM_ID value (in the SDO_ DATUMS table, described in Section 6.7.22) of the geodetic coordinate system on which the projected coordinate system is based. For a geodetic coordinate system, must match the DATUM_ID value. Example: 10115 SOURCE_GEOG_ SRID NUMBER(10) For a projected coordinate reference system, the ID number for the associated geodetic coordinate system. PROJECTION_ CONV_ID NUMBER(10) For a projected coordinate reference system, the COORD_OP_ID value of the conversion operation used to convert the projected coordinated system to and from the source geographic coordinate system. CMPD_HORIZ_ SRID NUMBER(10) (EPSG-assigned value; not used by Oracle Spatial. The EPSG description is: "For compound CRS only, the code of the horizontal component of the Compound CRS.") CMPD_VERT_ SRID NUMBER(10) (EPSG-assigned value; not used by Oracle Spatial. The EPSG description is: "For compound CRS only, the code of the vertical component of the Compound CRS.") INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition for the coordinate system (Oracle for all rows supplied by Oracle). Coordinate Systems Data Structures 6-24 Oracle Spatial Developer's Guide See also the information about the following views that are defined based on the value of the COORD_REF_SYS_KIND column: ■ SDO_CRS_COMPOUND (Section 6.7.12) ■ SDO_CRS_ENGINEERING (Section 6.7.13) ■ SDO_CRS_GEOCENTRIC (Section 6.7.14) ■ SDO_CRS_GEOGRAPHIC2D (Section 6.7.15) ■ SDO_CRS_GEOGRAPHIC3D (Section 6.7.16) ■ SDO_CRS_PROJECTED (Section 6.7.17) ■ SDO_CRS_VERTICAL (Section 6.7.18) 6.7.10 SDO_COORD_REF_SYSTEM View The SDO_COORD_REF_SYSTEM view contains the same columns as the SDO_ COORD_REF_SYS table, which is described in Section 6.7.9. However, the SDO_ COORD_REF_SYSTEM view has a trigger defined on it, so that any insert, update, or delete operations performed on the view cause all relevant Spatial system tables to have the appropriate operations performed on them. Therefore, if you need to perform an insert, update, or delete operation, you must perform it on the SDO_COORD_REF_SYSTEM view, not the SDO_COORD_REF_SYS table. DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). IS_LEGACY VARCHAR2(5) TRUE if the coordinate system definition was included in Oracle Spatial before release 10.2; FALSE if the coordinate system definition is new in Oracle Spatial release 10.2. LEGACY_CODE NUMBER(10) For any EPSG coordinate reference system that has a semantically identical legacy (in Oracle Spatial before release 10.2) counterpart, the SRID value of the legacy coordinate system. LEGACY_ WKTEXT VARCHAR2(2046) If IS_LEGACY is TRUE, contains the well-known text description of the coordinate system. Example: GEOGCS [ "Longitude / Latitude (WGS 84)", DATUM ["WGS 84", SPHEROID ["WGS 84", 6378137, 298.257223563]], PRIMEM [ "Greenwich", 0.000000 ], UNIT ["Decimal Degree", 0.01745329251994330]] LEGACY_CS_ BOUNDS SDO_GEOMETRY For a legacy coordinate system, the dimensional boundary (if any). IS_VALID VARCHAR2(5) TRUE if the EPSG record for the coordinate reference system is completely defined; FALSE if the EPSG record for the coordinate reference system is not completely defined. SUPPORTS_SDO_ GEOMETRY VARCHAR2(5) TRUE if the COORD_REF_SYS_KIND column contains ENGINEERING, GEOGRAPHIC2D, or PROJECTED CRS; FALSE if the COORD_REF_SYS_ KIND column contains any other value. Table 6–9 (Cont.) SDO_COORD_REF_SYS Table Column Name Data Type Description Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-25 6.7.11 SDO_COORD_SYS Table The SDO_COORD_SYS table contains rows with information about coordinate systems. This table contains the columns shown in Table 6–10. (The SDO_COORD_SYS table is roughly patterned after the EPSG Coordinate System table, where a coordinate system is described as "a pair of reusable axes.") 6.7.12 SDO_CRS_COMPOUND View The SDO_CRS_COMPOUND view contains selected information from the SDO_ COORD_REF_SYS table (described in Section 6.7.9) where the COORD_REF_SYS_ KIND column value is COMPOUND. (For an explanation of compound coordinate reference systems, see Section 6.5.2.) This view contains the columns shown in Table 6–11. 6.7.13 SDO_CRS_ENGINEERING View The SDO_CRS_ENGINEERING view contains selected information from the SDO_ COORD_REF_SYS table (described in Section 6.7.9) where the COORD_REF_SYS_ Table 6–10 SDO_COORD_SYS Table Column Name Data Type Description COORD_SYS_ID NUMBER(10) ID number of the coordinate system. Example: 6405 COORD_SYS_ NAME VARCHAR2(254) Name of the coordinate system. Example: Ellipsoidal 2D CS. Axes: latitude, longitude. Orientations: north, east. UoM: dec deg COORD_SYS_ TYPE VARCHAR2(24) Type of coordinate system. Example: ellipsoidal DIMENSION NUMBER(5) Number of dimensions represented by the coordinate system. INFORMATION_ SOURCE VARCHAR2(254) Origin of this information. DATA_SOURCE VARCHAR2(50) Organization providing the data for this record. Table 6–11 SDO_CRS_COMPOUND View Column Name Data Type Description SRID NUMBER(10) ID number of the coordinate reference system. COORD_REF_SYS_ NAME VARCHAR2(80) Name of the coordinate reference system. CMPD_HORIZ_ SRID NUMBER(10) (EPSG-assigned value; not used by Oracle Spatial. The EPSG description is: "For compound CRS only, the code of the horizontal component of the Compound CRS.") CMPD_VERT_ SRID NUMBER(10) (EPSG-assigned value; not used by Oracle Spatial. The EPSG description is: "For compound CRS only, the code of the vertical component of the Compound CRS.") INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition for the coordinate system (Oracle for all rows supplied by Oracle). DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). Coordinate Systems Data Structures 6-26 Oracle Spatial Developer's Guide KIND column value is ENGINEERING. This view contains the columns shown in Table 6–12. 6.7.14 SDO_CRS_GEOCENTRIC View The SDO_CRS_GEOCENTRIC view contains selected information from the SDO_ COORD_REF_SYS table (described in Section 6.7.9) where the COORD_REF_SYS_ KIND column value is GEOCENTRIC. This view contains the columns shown in Table 6–13. 6.7.15 SDO_CRS_GEOGRAPHIC2D View The SDO_CRS_GEOGRAPHIC2D view contains selected information from the SDO_ COORD_REF_SYS table (described in Section 6.7.9) where the COORD_REF_SYS_ KIND column value is GEOGRAPHIC2D. This view contains the columns shown in Table 6–14. Table 6–12 SDO_CRS_ENGINEERING View Column Name Data Type Description SRID NUMBER(10) ID number of the coordinate reference system. COORD_REF_SYS_ NAME VARCHAR2(80) Name of the coordinate reference system. COORD_SYS_ID NUMBER(10) ID number of the coordinate system used for the coordinate reference system. Must match a COORD_ SYS_ID value in the SDO_COORD_SYS table (see Section 6.7.11). DATUM_ID NUMBER(10) ID number of the datum used for the coordinate reference system. Must match a DATUM_ID value in the SDO_DATUMS table (see Section 6.7.22). INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition for the coordinate system (Oracle for all rows supplied by Oracle). DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). Table 6–13 SDO_CRS_GEOCENTRIC View Column Name Data Type Description SRID NUMBER(10) ID number of the coordinate reference system. COORD_REF_SYS_ NAME VARCHAR2(80) Name of the coordinate reference system. COORD_SYS_ID NUMBER(10) ID number of the coordinate system used for the coordinate reference system. Must match a COORD_ SYS_ID value in the SDO_COORD_SYS table (see Section 6.7.11). DATUM_ID NUMBER(10) ID number of the datum used for the coordinate reference system. Must match a DATUM_ID value in the SDO_DATUMS table (see Section 6.7.22). INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition for the coordinate system (Oracle for all rows supplied by Oracle). DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-27 6.7.16 SDO_CRS_GEOGRAPHIC3D View The SDO_CRS_GEOGRAPHIC3D view contains selected information from the SDO_ COORD_REF_SYS table (described in Section 6.7.9) where the COORD_REF_SYS_ KIND column value is GEOGRAPHIC3D. (For an explanation of geographic 3D coordinate reference systems, see Section 6.5.1.) This view contains the columns shown in Table 6–15. 6.7.17 SDO_CRS_PROJECTED View The SDO_CRS_PROJECTED view contains selected information from the SDO_ COORD_REF_SYS table (described in Section 6.7.9) where the COORD_REF_SYS_ KIND column value is PROJECTED. This view contains the columns shown in Table 6–16. Table 6–14 SDO_CRS_GEOGRAPHIC2D View Column Name Data Type Description SRID NUMBER(10) ID number of the coordinate reference system. COORD_REF_SYS_ NAME VARCHAR2(80) Name of the coordinate reference system. COORD_SYS_ID NUMBER(10) ID number of the coordinate system used for the coordinate reference system. Must match a COORD_ SYS_ID value in the SDO_COORD_SYS table (see Section 6.7.11). DATUM_ID NUMBER(10) ID number of the datum used for the coordinate reference system. Must match a DATUM_ID value in the SDO_DATUMS table (see Section 6.7.22). INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition for the coordinate system (Oracle for all rows supplied by Oracle). DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). Table 6–15 SDO_CRS_GEOGRAPHIC3D View Column Name Data Type Description SRID NUMBER(10) ID number of the coordinate reference system. COORD_REF_SYS_ NAME VARCHAR2(80) Name of the coordinate reference system. COORD_SYS_ID NUMBER(10) ID number of the coordinate system used for the coordinate reference system. Must match a COORD_SYS_ID value in the SDO_COORD_SYS table (see Section 6.7.11). DATUM_ID NUMBER(10) ID number of the datum used for the coordinate reference system. Must match a DATUM_ID value in the SDO_DATUMS table (see Section 6.7.22). INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition for the coordinate system (Oracle for all rows supplied by Oracle). DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). Coordinate Systems Data Structures 6-28 Oracle Spatial Developer's Guide 6.7.18 SDO_CRS_VERTICAL View The SDO_CRS_VERTICAL view contains selected information from the SDO_ COORD_REF_SYS table (described in Section 6.7.9) where the COORD_REF_SYS_ KIND column value is VERTICAL. This view contains the columns shown in Table 6–17. 6.7.19 SDO_DATUM_ENGINEERING View The SDO_DATUM_ENGINEERING view contains selected information from the SDO_DATUMS table (described in Section 6.7.22) where the DATUM_TYPE column value is ENGINEERING. This view contains the columns shown in Table 6–18. Table 6–16 SDO_CRS_PROJECTED View Column Name Data Type Description SRID NUMBER(10) ID number of the coordinate reference system. COORD_REF_SYS_ NAME VARCHAR2(80) Name of the coordinate reference system. COORD_SYS_ID NUMBER(10) ID number of the coordinate system used for the coordinate reference system. Must match a COORD_ SYS_ID value in the SDO_COORD_SYS table (see Section 6.7.11). SOURCE_GEOG_ SRID NUMBER(10) ID number for the associated geodetic coordinate system. PROJECTION_ CONV_ID NUMBER(10) COORD_OP_ID value of the conversion operation used to convert the projected coordinated system to and from the source geographic coordinate system. INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition for the coordinate system (Oracle for all rows supplied by Oracle). DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). Table 6–17 SDO_CRS_VERTICAL View Column Name Data Type Description SRID NUMBER(10) ID number of the coordinate reference system. COORD_REF_SYS_ NAME VARCHAR2(80) Name of the coordinate reference system. COORD_SYS_ID NUMBER(10) ID number of the coordinate system used for the coordinate reference system. Must match a COORD_ SYS_ID value in the SDO_COORD_SYS table (see Section 6.7.11). DATUM_ID NUMBER(10) ID number of the datum used for the coordinate reference system. Must match a DATUM_ID value in the SDO_DATUMS table (see Section 6.7.22). INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition for the coordinate system (Oracle for all rows supplied by Oracle). DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-29 6.7.20 SDO_DATUM_GEODETIC View The SDO_DATUM_GEODETIC view contains selected information from the SDO_ DATUMS table (described in Section 6.7.22) where the DATUM_TYPE column value is GEODETIC. This view contains the columns shown in Table 6–19. Table 6–18 SDO_DATUM_ENGINEERING View Column Name Data Type Description DATUM_ID NUMBER(10) ID number of the datum. DATUM_NAME VARCHAR2(80) Name of the datum. ELLIPSOID_ID NUMBER(10) ID number of the ellipsoid used in the datum definition. Must match an ELLIPSOID_ID value in the SDO_ELLIPSOIDS table (see Section 6.7.23). Example: 8045 PRIME_ MERIDIAN_ID NUMBER(10) ID number of the prime meridian used in the datum definition. Must match a PRIME_MERIDIAN_ID value in the SDO_PRIME_MERIDIANS table (see Section 6.7.26). Example: 8950 INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition of the datum. Example: Ordnance Survey of Great Britain. DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). SHIFT_X NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the x-axis. SHIFT_Y NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the y-axis. SHIFT_Z NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the z-axis. ROTATE_X NUMBER Number of arc-seconds of rotation about the x-axis. ROTATE_Y NUMBER Number of arc-seconds of rotation about the y-axis. ROTATE_Z NUMBER Number of arc-seconds of rotation about the z-axis. SCALE_ADJUST NUMBER A value to be used in adjusting the X, Y, and Z values after any shifting and rotation, according to the formula: 1.0 + (SCALE_ADJUST * 10-6) Table 6–19 SDO_DATUM_GEODETIC View Column Name Data Type Description DATUM_ID NUMBER(10) ID number of the datum. DATUM_NAME VARCHAR2(80) Name of the datum. ELLIPSOID_ID NUMBER(10) ID number of the ellipsoid used in the datum definition. Must match an ELLIPSOID_ID value in the SDO_ELLIPSOIDS table (see Section 6.7.23). Example: 8045 PRIME_ MERIDIAN_ID NUMBER(10) ID number of the prime meridian used in the datum definition. Must match a PRIME_MERIDIAN_ID value in the SDO_PRIME_MERIDIANS table (see Section 6.7.26). Example: 8950 INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition of the datum. Example: Ordnance Survey of Great Britain. Coordinate Systems Data Structures 6-30 Oracle Spatial Developer's Guide 6.7.21 SDO_DATUM_VERTICAL View The SDO_DATUM_VERTICAL view contains selected information from the SDO_ DATUMS table (described in Section 6.7.22) where the DATUM_TYPE column value is VERTICAL. This view contains the columns shown in Table 6–20. DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). SHIFT_X NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the x-axis. SHIFT_Y NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the y-axis. SHIFT_Z NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the z-axis. ROTATE_X NUMBER Number of arc-seconds of rotation about the x-axis. ROTATE_Y NUMBER Number of arc-seconds of rotation about the y-axis. ROTATE_Z NUMBER Number of arc-seconds of rotation about the z-axis. SCALE_ADJUST NUMBER A value to be used in adjusting the X, Y, and Z values after any shifting and rotation, according to the formula: 1.0 + (SCALE_ADJUST * 10-6) Table 6–20 SDO_DATUM_VERTICAL View Column Name Data Type Description DATUM_ID NUMBER(10) ID number of the datum. DATUM_NAME VARCHAR2(80) Name of the datum. ELLIPSOID_ID NUMBER(10) ID number of the ellipsoid used in the datum definition. Must match an ELLIPSOID_ID value in the SDO_ELLIPSOIDS table (see Section 6.7.23). Example: 8045 PRIME_ MERIDIAN_ID NUMBER(10) ID number of the prime meridian used in the datum definition. Must match a PRIME_MERIDIAN_ID value in the SDO_PRIME_MERIDIANS table (see Section 6.7.26). Example: 8950 INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition of the datum. Example: Ordnance Survey of Great Britain. DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). SHIFT_X NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the x-axis. SHIFT_Y NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the y-axis. SHIFT_Z NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the z-axis. Table 6–19 (Cont.) SDO_DATUM_GEODETIC View Column Name Data Type Description Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-31 6.7.22 SDO_DATUMS Table The SDO_DATUMS table contains one row for each datum. This table contains the columns shown in Table 6–21. ROTATE_X NUMBER Number of arc-seconds of rotation about the x-axis. ROTATE_Y NUMBER Number of arc-seconds of rotation about the y-axis. ROTATE_Z NUMBER Number of arc-seconds of rotation about the z-axis. SCALE_ADJUST NUMBER A value to be used in adjusting the X, Y, and Z values after any shifting and rotation, according to the formula: 1.0 + (SCALE_ADJUST * 10-6) Table 6–21 SDO_DATUMS Table Column Name Data Type Description DATUM_ID NUMBER(10) ID number of the datum. Example: 10115 DATUM_NAME VARCHAR2(80) Name of the datum. Example: WGS 84 DATUM_TYPE VARCHAR2(24) Type of the datum. Example: GEODETIC ELLIPSOID_ID NUMBER(10) ID number of the ellipsoid used in the datum definition. Must match an ELLIPSOID_ID value in the SDO_ELLIPSOIDS table (see Section 6.7.23). Example: 8045 PRIME_ MERIDIAN_ID NUMBER(10) ID number of the prime meridian used in the datum definition. Must match a PRIME_MERIDIAN_ID value in the SDO_PRIME_MERIDIANS table (see Section 6.7.26). Example: 8950 INFORMATION_ SOURCE VARCHAR2(254) Provider of the definition of the datum. Example: Ordnance Survey of Great Britain. DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). Example: EPSG SHIFT_X NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the x-axis. SHIFT_Y NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the y-axis. SHIFT_Z NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the z-axis. ROTATE_X NUMBER Number of arc-seconds of rotation about the x-axis. ROTATE_Y NUMBER Number of arc-seconds of rotation about the y-axis. ROTATE_Z NUMBER Number of arc-seconds of rotation about the z-axis. SCALE_ADJUST NUMBER A value to be used in adjusting the X, Y, and Z values after any shifting and rotation, according to the formula: 1.0 + (SCALE_ADJUST * 10-6) IS_LEGACY VARCHAR2(5) TRUE if the datum definition was included in Oracle Spatial before release 10.2; FALSE if the datum definition is new in Oracle Spatial release 10.2. Table 6–20 (Cont.) SDO_DATUM_VERTICAL View Column Name Data Type Description Coordinate Systems Data Structures 6-32 Oracle Spatial Developer's Guide See also the information about the following views that are defined based on the value of the DATUM_TYPE column: SDO_DATUM_ENGINEERING (Section 6.7.19), SDO_ DATUM_GEODETIC (Section 6.7.20), and SDO_DATUM_VERTICAL (Section 6.7.21). 6.7.23 SDO_ELLIPSOIDS Table The SDO_ELLIPSOIDS table contains one row for each ellipsoid. This table contains the columns shown in Table 6–22. 6.7.24 SDO_PREFERRED_OPS_SYSTEM Table The SDO_PREFERRED_OPS_SYSTEM table contains one row for each specification of the user-defined default preferred coordinate transformation operation for a source and target SRID combination. If you insert a row into the SDO_PREFERRED_OPS_ SYSTEM table, you are overriding the Oracle default operation for transformations between the specified source and target coordinate systems. The SDO_CS.CREATE_ LEGACY_CODE NUMBER(10) For any EPSG datum that has a semantically identical legacy (in Oracle Spatial before release 10.2) counterpart, the DATUM_ID value of the legacy datum. Table 6–22 SDO_ELLIPSOIDS Table Column Name Data Type Description ELLIPSOID_ID NUMBER ID number of the ellipsoid (spheroid). Example: 8045 ELLIPSOID_ NAME VARCHAR2(80) Name of the ellipsoid. Example: WGS 84 SEMI_MAJOR_ AXIS NUMBER Radius in meters along the semi-major axis (one-half of the long axis of the ellipsoid). UOM_ID NUMBER ID number of the unit of measurement for the ellipsoid. Matches a value in the UOM_ID column of the SDO_UNITS_OF_MEASURE table (described in Section 6.7.27). Example: 9001 INV_ FLATTENING NUMBER Inverse flattening of the ellipsoid. That is, 1/f, where f = (a-b)/a, and a is the semi-major axis and b is the semi-minor axis. SEMI_MINOR_ AXIS NUMBER Radius in meters along the semi-minor axis (one-half of the short axis of the ellipsoid). INFORMATION_ SOURCE VARCHAR2(254) Origin of this information. Example: Kort og Matrikelstyrelsen (KMS), Copenhagen. DATA_SOURCE VARCHAR2(40) Organization that supplied the data for this record (if not Oracle). Example: EPSG IS_LEGACY VARCHAR2(5) TRUE if the ellipsoid definition was included in Oracle Spatial before release 10.2; FALSE if the ellipsoid definition is new in Oracle Spatial release 10.2. LEGACY_CODE NUMBER For any EPSG ellipsoid that has a semantically identical legacy (in Oracle Spatial before release 10.2) counterpart, the ELLIPSOID_ID value of the legacy ellipsoid. Table 6–21 (Cont.) SDO_DATUMS Table Column Name Data Type Description Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-33 OBVIOUS_EPSG_RULES procedure inserts many rows into this table. The SDO_ CS.DELETE_ALL_EPSG_RULES procedure deletes all rows from this table if the use_ case parameter is null. This table contains the columns shown in Table 6–23. 6.7.25 SDO_PREFERRED_OPS_USER Table The SDO_PREFERRED_OPS_USER table contains one row for each specification of a user-defined source and target SRID and coordinate transformation operation. If you insert a row into the SDO_PREFERRED_OPS_USER table, you create a custom transformation between the source and target coordinate systems, and you can specify the name (the USE_CASE column value) of the transformation operation as the use_ case parameter value with several SDO_CS functions and procedures. If you specify a use case with the SDO_CS.DELETE_ALL_EPSG_RULES procedure, rows associated with that use case are deleted from this table. This table contains the columns shown in Table 6–24. 6.7.26 SDO_PRIME_MERIDIANS Table The SDO_PRIME_MERIDIANS table contains one row for each prime meridian that can be used in a datum specification. This table contains the columns shown in Table 6–25. Table 6–23 SDO_PREFERRED_OPS_SYSTEM Table Column Name Data Type Description SOURCE_SRID NUMBER(10) ID number of the coordinate system (spatial reference system) from which to perform coordinate transformation, using the operation specified by COORD_OP_ID as the default preferred method for transforming to the specified target SRID. COORD_OP_ID NUMBER(10) ID number of the coordinate transformation operation. Matches a value in the COORD_OP_ID column of the SDO_COORD_OPS table (described in Section 6.7.8). TARGET_SRID NUMBER(10) ID number of coordinate system (spatial reference system) into which to perform coordinate transformation using the operation specified by COORD_OP_ID. Table 6–24 SDO_PREFERRED_OPS_USER Table Column Name Data Type Description USE_CASE VARCHAR2(32) Name of this specification of a source and target SRID and coordinate transformation operation. SOURCE_SRID NUMBER(10) ID number of the coordinate system (spatial reference system) from which to perform the transformation. COORD_OP_ID NUMBER(10) ID number of the coordinate transformation operation. Matches a value in the COORD_OP_ID column of the SDO_COORD_OPS table (described in Section 6.7.8). TARGET_SRID NUMBER(10) ID number of the coordinate system (spatial reference system) into which to perform the transformation. Coordinate Systems Data Structures 6-34 Oracle Spatial Developer's Guide 6.7.27 SDO_UNITS_OF_MEASURE Table The SDO_UNITS_OF_MEASURE table contains one row for each unit of measurement. This table contains the columns shown in Table 6–26. Table 6–25 SDO_PRIME_MERIDIANS Table Column Name Data Type Description PRIME_MERIDIAN_ ID NUMBER(10) ID number of the prime meridian. Example: 8907 PRIME_MERIDIAN_ NAME VARCHAR2(80) Name of the prime meridian. Example: Bern GREENWICH_ LONGITUDE FLOAT(49) Longitude of the prime meridian as an offset from the Greenwich meridian. Example: 7.26225 UOM_ID NUMBER(10) ID number of the unit of measurement for the prime meridian. Matches a value in the UOM_ID column of the SDO_UNITS_OF_MEASURE table (described in Section 6.7.27). Example: 9110 for sexagesimal degree INFORMATION_ SOURCE VARCHAR2(254) Origin of this information. Example: Bundesamt fur Landestopographie DATA_SOURCE VARCHAR2(254) Organization that supplied the data for this record (if not Oracle). Example: EPSG Table 6–26 SDO_UNITS_OF_MEASURE Table Column Name Data Type Description UOM_ID NUMBER(10) ID number of the unit of measurement. Example: 10032 UNIT_OF_MEAS_ NAME VARCHAR2(2083) Name of the unit of measurement; can also be a URL or URI. Example: Meter SHORT_NAME VARCHAR2(80) Short name (if any) of the unit of measurement. Example: METER UNIT_OF_MEAS_ TYPE VARCHAR2(50) Type of measure for which the unit is used: angle for angle unit, area for area unit, length for distance unit, scale for scale unit, or volume for volume unit. TARGET_UOM_ID NUMBER(10) ID number of a target unit of measurement. Corresponds to the TARGET_UOM_CODE column in the EPSG Unit of Measure table, which has the following description: "Other UOM of the same type into which the current UOM can be converted using the formula (POSC); POSC factors A and D always equal zero for EPSG supplied units of measure." FACTOR_B NUMBER Corresponds to the FACTOR_B column in the EPSG Unit of Measure table, which has the following description: "A quantity in the target UOM (y) is obtained from a quantity in the current UOM (x) through the conversion: y = (B/C).x" In a user-defined unit of measurement, FACTOR_B is usually the number of square meters or meters equal to one of the unit. For information about user-defined units, see Section 2.10.1. Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-35 6.7.28 Relationships Among Coordinate System Tables and Views Because the definitions in Spatial system tables and views are based on the EPSG data model and dataset, the EPSG entity-relationship (E-R) diagram provides a good overview of the relationships among the Spatial coordinate system data structures. The EPSG E-R diagram is included in the following document: http://www.epsg.org/CurrentDB.html However, Oracle Spatial does not use the following from the EPSG E-R diagram: ■ Area of Use (yellow box in the upper center of the diagram) ■ Deprecation, Alias, and others represented by pink boxes in the lower right corner of the diagram In addition, Spatial changes the names of some tables to conform to its own naming conventions, and it does not use some tables, as shown in Table 6–27 FACTOR_C NUMBER Corresponds to the FACTOR_C column in the EPSG Unit of Measure table. For FACTOR_C in a user-defined unit of measurement, see Section 2.10.1. INFORMATION_ SOURCE VARCHAR2(254) Origin of this information. Example: ISO 1000. DATA_SOURCE VARCHAR2(40) Organization providing the data for this record. Example: EPSG IS_LEGACY VARCHAR2(5) TRUE if the unit of measurement definition was included in Oracle Spatial before release 10.2; FALSE if the unit of measurement definition is new in Oracle Spatial release 10.2. LEGACY_CODE NUMBER(10) For any EPSG unit of measure that has a semantically identical legacy (in Oracle Spatial before release 10.2) counterpart, the UOM_ID value of the legacy unit of measure. Table 6–27 EPSG Table Names and Oracle Spatial Names EPSG Name Oracle Name Coordinate System SDO_COORD_SYS Coordinate Axis SDO_COORD_AXES Coordinate Reference System SDO_COORD_REF_SYSTEM Area Of Use (Not used) Datum SDO_DATUMS Prime Meridian SDO_PRIME_MERIDIANS Ellipsoid SDO_ELLIPSOIDS Unit Of Measure SDO_UNITS_OF_MEASURE Coordinate Operation SDO_COORD_OPS Coord. Operation Parameter ValueCoord SDO_COORD_OP_PARAM_VALS Operation Parameter UsageCoord. SDO_COORD_OP_PARAM_USE Table 6–26 (Cont.) SDO_UNITS_OF_MEASURE Table Column Name Data Type Description Coordinate Systems Data Structures 6-36 Oracle Spatial Developer's Guide 6.7.29 Finding Information About EPSG-Based Coordinate Systems This section explains how to query the Spatial coordinate systems data structures for information about geodetic and projected EPSG-based coordinate systems. 6.7.29.1 Geodetic Coordinate Systems A human-readable summary of a CRS is the WKT string. For example: SQL> select wktext from cs_srs where srid = 4326; WKTEXT -------------------------------------------------------------------------------- GEOGCS [ "WGS 84", DATUM ["World Geodetic System 1984 (EPSG ID 6326)", SPHEROID ["WGS 84 (EPSG ID 7030)", 6378137, 298.257223563]], PRIMEM [ "Greenwich", 0.0000 00 ], UNIT ["Decimal Degree", 0.01745329251994328]] EPSG WKTs have been automatically generated by Spatial, for backward compatibility. Note that EPSG WKTs also contain numeric ID values (such as EPSG ID 6326 in the preceding example) for convenience. However, for more detailed information you should access the EPSG data stored in the coordinate systems data structures. The following example returns information about the ellipsoid, datum shift, rotation, and scale adjustment for SRID 4123: SQL> select ell.semi_major_axis, ell.inv_flattening, ell.semi_minor_axis, ell.uom_id, dat.shift_x, dat.shift_y, dat.shift_z, dat.rotate_x, dat.rotate_y, dat.rotate_z, dat.scale_adjust from sdo_coord_ref_system crs, sdo_datums dat, sdo_ellipsoids ell where crs.srid = 4123 and dat.datum_id = crs.datum_id and Operation Parameter SDO_COORD_OP_PARAMS Coordinate Operation Path SDO_COORD_OP_PATHS Coordinate Operation Method SDO_COORD_OP_METHODS Change (Not used) Deprecation (Not used) Supersession (Not used) Naming System (Not used) Alias (Not used) Any Entity (Not used) Table 6–27 (Cont.) EPSG Table Names and Oracle Spatial Names EPSG Name Oracle Name Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-37 ell.ellipsoid_id = dat.ellipsoid_id; SEMI_MAJOR_AXIS INV_FLATTENING SEMI_MINOR_AXIS UOM_ID SHIFT_X SHIFT_Y SHIFT_Z ROTATE_X ROTATE_Y ROTATE_Z SCALE_ADJUST --------------- -------------- --------------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ------------ 6378388 297 6356911.95 9001 -90.7 -106.1 -119.2 4.09 .218 -1.05 1.37 In the preceding example, the UOM_ID represents the unit of measure for SEMI_ MAJOR_AXIS (a) and SEMI_MINOR_AXIS (b). INV_FLATTENING is a/(a-b) and has no associated unit. Shifts are in meters, rotation angles are given in arc seconds, and scale adjustment in parts per million. To interpret the UOM_ID, you can query the units table, as shown in the following example: SQL> select UNIT_OF_MEAS_NAME from sdo_units_of_measure where UOM_ID = 9001; UNIT_OF_MEAS_NAME -------------------------------------------------------------------------------- metre Conversion factors for units of length are given relative to meters, as shown in the following example: SQL> select UNIT_OF_MEAS_NAME, FACTOR_B/FACTOR_C from sdo_units_of_measure where UOM_ID = 9002; UNIT_OF_MEAS_NAME -------------------------------------------------------------------------------- FACTOR_B/FACTOR_C ----------------- foot .3048 Conversion factors for units of angle are given relative to radians, as shown in the following example: SQL> select UNIT_OF_MEAS_NAME, FACTOR_B/FACTOR_C from sdo_units_of_measure where UOM_ID = 9102; UNIT_OF_MEAS_NAME -------------------------------------------------------------------------------- FACTOR_B/FACTOR_C ----------------- degree .017453293 6.7.29.2 Projected Coordinate Systems As mentioned in Section 6.7.29.1, the WKT is a human-readable summary of a CRS, but the actual EPSG data is stored in the Spatial coordinate systems data structures. The following example shows the WKT string for a projected coordinate system: SQL> select wktext from cs_srs where srid = 32040; WKTEXT -------------------------------------------------------------------------------- PROJCS["NAD27 / Texas South Central", GEOGCS [ "NAD27", DATUM ["North American D atum 1927 (EPSG ID 6267)", SPHEROID ["Clarke 1866 (EPSG ID 7008)", 6378206.4, 29 4.978698213905820761610537123195175418]], PRIMEM [ "Greenwich", 0.000000 ], UNIT Coordinate Systems Data Structures 6-38 Oracle Spatial Developer's Guide ["Decimal Degree", 0.01745329251994328]], PROJECTION ["Texas CS27 South Central zone (EPSG OP 14204)"], PARAMETER ["Latitude_Of_Origin", 27.8333333333333333333 3333333333333333333], PARAMETER ["Central_Meridian", -98.99999999999999999999999 999999999999987], PARAMETER ["Standard_Parallel_1", 28.3833333333333333333333333 3333333333333], PARAMETER ["Standard_Parallel_2", 30.283333333333333333333333333 33333333333], PARAMETER ["False_Easting", 2000000], PARAMETER ["False_Northing", 0], UNIT ["U.S. Foot", .3048006096012192024384048768097536195072]] To determine the base geographic CRS for a projected CRS, you can query the SDO_ COORD_REF_SYSTEM table, as in the following example: SQL> select SOURCE_GEOG_SRID from sdo_coord_ref_system where srid = 32040; SOURCE_GEOG_SRID ---------------- 4267 The following example returns the projection method for the projected CRS 32040: SQL> select m.coord_op_method_name from sdo_coord_ref_sys crs, sdo_coord_ops ops, sdo_coord_op_methods m where crs.srid = 32040 and ops.coord_op_id = crs.projection_conv_id and m.coord_op_method_id = ops.coord_op_method_id; COORD_OP_METHOD_NAME -------------------------------------------------- Lambert Conic Conformal (2SP) The following example returns the projection parameters for the projected CRS 32040: SQL> select params.parameter_name || ' = ' || vals.parameter_value || ' ' || uom.unit_of_meas_name "Projection parameters" from sdo_coord_ref_sys crs, sdo_coord_op_param_vals vals, sdo_units_of_measure uom, sdo_coord_op_params params where crs.srid = 32040 and vals.coord_op_id = crs.projection_conv_id and uom.uom_id = vals.uom_id and params.parameter_id = vals.parameter_id; Projection parameters -------------------------------------------------------------------------------- Latitude of false origin = 27.5 sexagesimal DMS Longitude of false origin = -99 sexagesimal DMS Latitude of 1st standard parallel = 28.23 sexagesimal DMS Latitude of 2nd standard parallel = 30.17 sexagesimal DMS Easting at false origin = 2000000 US survey foot Northing at false origin = 0 US survey foot Coordinate Systems Data Structures Coordinate Systems (Spatial Reference Systems) 6-39 The following example is essentially the same query as the preceding example, but it also converts the values to the base unit: SQL> select params.parameter_name || ' = ' || vals.parameter_value || ' ' || uom.unit_of_meas_name || ' = ' || sdo_cs.transform_to_base_unit(vals.parameter_value, vals.uom_id) || ' ' || decode( uom.unit_of_meas_type, 'area', 'square meters', 'angle', 'radians', 'length', 'meters', 'scale', '', '') "Projection parameters" from sdo_coord_ref_sys crs, sdo_coord_op_param_vals vals, sdo_units_of_measure uom, sdo_coord_op_params params where crs.srid = 32040 and vals.coord_op_id = crs.projection_conv_id and uom.uom_id = vals.uom_id and params.parameter_id = vals.parameter_id; Projection parameters ---------------------------------------------------------------------------------- ---------------------------------------------------------------------------------- ------ Latitude of false origin = 27.5 sexagesimal DMS = .485783308471754564814814814814814814815 radians Longitude of false origin = -99 sexagesimal DMS = -1.7278759594743845 radians Latitude of 1st standard parallel = 28.23 sexagesimal DMS = .495382619357723367592592592592592592593 radians Latitude of 2nd standard parallel = 30.17 sexagesimal DMS = .528543875145615595370370370370370370371 radians Easting at false origin = 2000000 US survey foot = 609601.219202438404876809753619507239014 meters Northing at false origin = 0 US survey foot = 0 meters The following example returns the projection unit of measure for the projected CRS 32040. (The projection unit might be different from the length unit used for the projection parameters.) SQL> select axes.coord_axis_abbreviation || ': ' || uom.unit_of_meas_name "Projection units" from sdo_coord_ref_sys crs, sdo_coord_axes axes, sdo_units_of_measure uom where crs.srid = 32040 and axes.coord_sys_id = crs.coord_sys_id and uom.uom_id = axes.uom_id; Projection units ------------------------------------------------------------------------------ X: US survey foot Y: US survey foot Legacy Tables and Views 6-40 Oracle Spatial Developer's Guide 6.8 Legacy Tables and Views In releases of Spatial before 10.2, the coordinate systems functions and procedures used information provided in the following tables, some of which have new names or are now views instead of tables: ■ MDSYS.CS_SRS (see Section 6.8.1) defined the valid coordinate systems. It associates each coordinate system with its well-known text description, which is in conformance with the standard published by the Open Geospatial Consortium (http://www.opengeospatial.org). ■ MDSYS.SDO_ANGLE_UNITS (see Section 6.8.2) defines the valid angle units. ■ MDSYS.SDO_AREA_UNITS (see Section 6.8.3) defines the valid area units. ■ MDSYS.SDO_DIST_UNITS (see Section 6.8.5) defines the valid distance units. ■ MDSYS.SDO_DATUMS_OLD_FORMAT and MDSYS.SDO_DATUMS_OLD_ SNAPSHOT (see Section 6.8.4) are based on the MDSYS.SDO_DATUMS table before release 10.2, which defined valid datums. ■ MDSYS.SDO_ELLIPSOIDS_OLD_FORMAT and MDSYS.SDO_ELLIPSOIDS_ OLD_SNAPSHOT (see Section 6.8.6) are based on the MDSYS.SDO_ELLIPSOIDS table before release 10.2, which defined valid ellipsoids. ■ MDSYS.SDO_PROJECTIONS_OLD_FORMAT and MDSYS.SDO_PROJECTIONS_ OLD_SNAPSHOT (see Section 6.8.7) are based on the MDSYS.SDO_ PROJECTIONS table before release 10.2, which defined the valid map projections. 6.8.1 MDSYS.CS_SRS Table The MDSYS.CS_SRS reference table contains over 4000 rows, one for each valid coordinate system. This table contains the columns shown in Table 6–28. Note: You should not modify or delete any Oracle-supplied information in these legacy tables. If you refer to a legacy table in a SQL statement, you must include the MDSYS. before the table name. Table 6–28 MDSYS.CS_SRS Table Column Name Data Type Description CS_NAME VARCHAR2(68) A well-known name, often mnemonic, by which a user can refer to the coordinate system. SRID NUMBER(38) The unique ID number (Spatial Reference ID) for a coordinate system. Currently, SRID values 1-999999 are reserved for use by Oracle Spatial, and values 1000000 (1 million) and higher are available for user-defined coordinate systems. AUTH_SRID NUMBER(38) An optional ID number that can be used to indicate how the entry was derived; it might be a foreign key into another coordinate table, for example. AUTH_ NAME VARCHAR2(256) An authority name for the coordinate system. Contains Oracle in the supplied table. Users can specify any value in any rows that they add. Legacy Tables and Views Coordinate Systems (Spatial Reference Systems) 6-41 6.8.1.1 Well-Known Text (WKT) The WKTEXT column of the MDSYS.CS_SRS table contains the well-known text (WKT) description of the SRS, as defined by the Open Geospatial Consortium. The following is the WKT EBNF syntax. ::= | ::= | ::= PROJCS [ "", , , {,}* ] ::= PROJECTION [ "" ] ::= PARAMETER [ "", ] ::= GEOGCS [ "", , , ] ::= DATUM [ "", {, , , , , , , } ] ::= SPHEROID ["", , ] ::= PRIMEM ["", ] ::= ::= ::= WKTEXT VARCHAR2(2046) The well-known text (WKT) description of the SRS, as defined by the Open Geospatial Consortium. For more information, see Section 6.8.1.1. CS_BOUNDS SDO_GEOMETRY An optional SDO_GEOMETRY object that is a polygon with WGS 84 longitude and latitude vertices, representing the spheroidal polygon description of the zone of validity for a projected coordinate system. Must be null for a geographic or non-Earth coordinate system. Is null in all supplied rows. Table 6–28 (Cont.) MDSYS.CS_SRS Table Column Name Data Type Description Legacy Tables and Views 6-42 Oracle Spatial Developer's Guide ::= ::= ::= UNIT [ "", ] ::= LOCAL_CS [ "", , , {, }* ] ::= LOCAL_DATUM [ "", {, , , , , , , } ] ::= ::= AXIS [ "", NORTH | SOUTH | EAST | WEST | UP | DOWN | OTHER ] Each specification is one of the following: ■ Standard_Parallel_1 (in decimal degrees) ■ Standard_Parallel_2 (in decimal degrees) ■ Central_Meridian (in decimal degrees) ■ Latitude_of_Origin (in decimal degrees) ■ Azimuth (in decimal degrees) ■ False_Easting (in the unit of the coordinate system; for example, meters) ■ False_Northing (in the unit of the coordinate system; for example, meters) ■ Perspective_Point_Height (in the unit of the coordinate system; for example, meters) ■ Landsat_Number (must be 1, 2, 3, 4, or 5) ■ Path_Number ■ Scale_Factor The default value for each specification is 0 (zero). That is, if a specification is needed for a projection but no value is specified in the WKT, Spatial uses a value of 0. The prime meridian (PRIMEM) is specified in decimal degrees of longitude. An example of the WKT for a geodetic (geographic) coordinate system is: 'GEOGCS [ "Longitude / Latitude (Old Hawaiian)", DATUM ["Old Hawaiian", SPHEROID Note: If the WKT uses European rather than US-American notation for datum rotation parameters, or if the transformation results do not seem correct, see Section 6.8.1.2. Legacy Tables and Views Coordinate Systems (Spatial Reference Systems) 6-43 ["Clarke 1866", 6378206.400000, 294.978698]], PRIMEM [ "Greenwich", 0.000000 ], UNIT ["Decimal Degree", 0.01745329251994330]]' The WKT definition of the coordinate system is hierarchically nested. The Old Hawaiian geographic coordinate system (GEOGCS) is composed of a named datum (DATUM), a prime meridian (PRIMEM), and a unit definition (UNIT). The datum is in turn composed of a named spheroid and its parameters of semi-major axis and inverse flattening. An example of the WKT for a projected coordinate system (a Wyoming State Plane) is: 'PROJCS["Wyoming 4901, Eastern Zone (1983, meters)", GEOGCS [ "GRS 80", DATUM ["GRS 80", SPHEROID ["GRS 80", 6378137.000000, 298.257222]], PRIMEM [ "Greenwich", 0.000000 ], UNIT ["Decimal Degree", 0.01745329251994330]], PROJECTION ["Transverse Mercator"], PARAMETER ["Scale_Factor", 0.999938], PARAMETER ["Central_Meridian", -105.166667], PARAMETER ["Latitude_Of_Origin", 40.500000], PARAMETER ["False_Easting", 200000.000000], UNIT ["Meter", 1.000000000000]]' The projected coordinate system contains a nested geographic coordinate system as its basis, as well as parameters that control the projection. Oracle Spatial supports all common geodetic datums and map projections. An example of the WKT for a local coordinate system is: LOCAL_CS [ "Non-Earth (Meter)", LOCAL_DATUM ["Local Datum", 0], UNIT ["Meter", 1.0], AXIS ["X", EAST], AXIS["Y", NORTH]] For more information about local coordinate systems, see Section 6.3. You can use the SDO_CS.VALIDATE_WKT function, described in Chapter 21, to validate the WKT of any coordinate system defined in the MDSYS.CS_SRS table. 6.8.1.2 US-American and European Notations for Datum Parameters The datum-related WKT parameters are a list of up to seven Bursa Wolf transformation parameters. Rotation parameters specify arc seconds, and shift parameters specify meters. Two different notations, US-American and European, are used for the three rotation parameters that are in general use, and these two notations use opposite signs. Spatial uses and expects the US-American notation. Therefore, if your WKT uses the European notation, you must convert it to the US-American notation by inverting the signs of the rotation parameters. If you do not know if a parameter set uses the US-American or European notation, perform the following test: 1. Select a single point for which you know the correct result. 2. Perform the transformation using the current WKT. 3. If the computed result does not match the known correct result, invert signs of the rotation parameters, perform the transformation, and check if the computed result matches the known correct result. 6.8.1.3 Procedures for Updating the Well-Known Text If you insert or delete a row in the SDO_COORD_REF_SYSTEM view (described in Section 6.7.10), Spatial automatically updates the WKTEXT column in the MDSYS.CS_ SRS table. (The format of the WKTEXT column is described in Section 6.8.1.1.) Legacy Tables and Views 6-44 Oracle Spatial Developer's Guide However, if you update an existing row in the SDO_COORD_REF_SYSTEM view, the well-known text (WKT) value is not automatically updated. In addition, information relating to coordinate reference systems is also stored in several other system tables, including SDO_DATUMS (described in Section 6.7.22), SDO_ELLIPSOIDS (described in Section 6.7.23), and SDO_PRIME_MERIDIANS (described in Section 6.7.26). If you add, delete, or modify information in these tables, the WKTEXT values in the MDSYS.CS_SRS table are not automatically updated. For example, if you update an ellipsoid flattening value in the SDO_ELLIPSOIDS table, the well-known text string for the associated coordinate system is not updated. However, you can manually update the WKTEXT values in the in the MDSYS.CS_SRS table by using any of several procedures whose names start with UPDATE_WKTS_ FOR (for example, SDO_CS.UPDATE_WKTS_FOR_ALL_EPSG_CRS and SDO_ CS.UPDATE_WKTS_FOR_EPSG_DATUM). If the display of SERVEROUTPUT information is enabled, these procedures display a message identifying the SRID value for each row in the MDSYS.CS_SRS table whose WKTEXT value is being updated. These procedures are described in Chapter 21. 6.8.2 MDSYS.SDO_ANGLE_UNITS View The MDSYS.SDO_ANGLE_UNITS reference view contains one row for each valid angle UNIT specification in the well-known text (WKT) description in the coordinate system definition. The WKT is described in Section 6.8.1.1. The MDSYS.SDO_ANGLE_UNITS view is based on the SDO_UNITS_OF MEASURE table (described in Section 6.7.27), and it contains the columns shown in Table 6–29. 6.8.3 MDSYS.SDO_AREA_UNITS View The MDSYS.SDO_AREA_UNITS reference view contains one row for each valid area UNIT specification in the well-known text (WKT) description in the coordinate system definition. The WKT is described in Section 6.8.1.1. The MDSYS.SDO_AREA_UNITS view is based on the SDO_UNITS_OF MEASURE table (described in Section 6.7.27), and it contains the columns shown in Table 6–30. Table 6–29 MDSYS.SDO_ANGLE_UNITS View Column Name Data Type Description SDO_UNIT VARCHAR2(32) Name of the angle unit (often a shortened form of the UNIT_NAME value). Use the SDO_UNIT value with the from_unit and to_unit parameters of the SDO_ UTIL.CONVERT_UNIT function. UNIT_NAME VARCHAR2(100) Name of the angle unit. Specify a value from this column in the UNIT specification of the WKT for any user-defined coordinate system. Examples: Decimal Degree, Radian, Decimal Second, Decimal Minute, Gon, Grad. CONVERSION_ FACTOR NUMBER The ratio of the specified unit to one radian. For example, the ratio of Decimal Degree to Radian is 0.017453293. Table 6–30 SDO_AREA_UNITS View Column Name Data Type Purpose SDO_UNIT VARCHAR2 Values are taken from the SHORT_NAME column of the SDO_UNITS_OF MEASURE table. Legacy Tables and Views Coordinate Systems (Spatial Reference Systems) 6-45 6.8.4 MDSYS.SDO_DATUMS_OLD_FORMAT and SDO_DATUMS_OLD_SNAPSHOT Tables The MDSYS.SDO_DATUMS_OLD_FORMAT and MDSYS.SDO_DATUMS_OLD_ SNAPSHOT reference tables contain one row for each valid DATUM specification in the well-known text (WKT) description in the coordinate system definition. (The WKT is described in Section 6.8.1.1.) ■ MDSYS.SDO_DATUMS_OLD_FORMAT contains the new data in the old format (that is, EPSG-based datum specifications in a table using the format from before release 10.2). ■ MDSYS.SDO_DATUMS_OLD_SNAPSHOT contains the old data in the old format (that is, datum specifications and table format from before release 10.2). These tables contain the columns shown in Table 6–31. The following are the names (in tabular format) of the datums in these tables: UNIT_NAME VARCHAR2 Values are taken from the UNIT_OF_MEAS_NAME column of the SDO_UNITS_OF MEASURE table. CONVERSION_ FACTOR NUMBER Ratio of the unit to 1 square meter. For example, the conversion factor for a square meter is 1.0, and the conversion factor for a square mile is 2589988. Table 6–31 MDSYS.SDO_DATUMS_OLD_FORMAT and SDO_DATUMS_OLD_SNAPSHOT Tables Column Name Data Type Description NAME VARCHAR2(80) for OLD_FORMAT VARCHAR2(64) for OLD_ SNAPSHOT Name of the datum. Specify a value (Oracle-supplied or user-defined) from this column in the DATUM specification of the WKT for any user-defined coordinate system. Examples: Adindan, Afgooye, Ain el Abd 1970, Anna 1 Astro 1965, Arc 1950, Arc 1960, Ascension Island 1958. SHIFT_X NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the x-axis. SHIFT_Y NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the y-axis. SHIFT_Z NUMBER Number of meters to shift the ellipsoid center relative to the center of the WGS 84 ellipsoid on the z-axis. ROTATE_X NUMBER Number of arc-seconds of rotation about the x-axis. ROTATE_Y NUMBER Number of arc-seconds of rotation about the y-axis. ROTATE_Z NUMBER Number of arc-seconds of rotation about the z-axis. SCALE_ ADJUST NUMBER A value to be used in adjusting the X, Y, and Z values after any shifting and rotation, according to the formula: 1.0 + (SCALE_ADJUST * 10-6) Table 6–30 (Cont.) SDO_AREA_UNITS View Column Name Data Type Purpose Legacy Tables and Views 6-46 Oracle Spatial Developer's Guide Adindan Afgooye Ain el Abd 1970 Anna 1 Astro 1965 Arc 1950 Arc 1960 Ascension Island 1958 Astro B4 Sorol Atoll Astro Beacon E Astro DOS 71/4 Astronomic Station 1952 Australian Geodetic 1966 Australian Geodetic 1984 Belgium Hayford Bellevue (IGN) Bermuda 1957 Bogota Observatory CH 1903 (Switzerland) Campo Inchauspe Canton Astro 1966 Cape Cape Canaveral Carthage Chatham 1971 Chua Astro Corrego Alegre DHDN (Potsdam/Rauenberg) DOS 1968 Djakarta (Batavia) Easter Island 1967 European 1950 European 1979 European 1987 GRS 67 GRS 80 GUX 1 Astro Gandajika Base Geodetic Datum 1949 Guam 1963 Hito XVIII 1963 Hjorsey 1955 Hong Kong 1963 Hu-Tzu-Shan ISTS 073 Astro 1969 Indian (Bangladesh, etc.) Indian (Thailand/Vietnam) Ireland 1965 Johnston Island 1961 Kandawala Kerguelen Island Kertau 1948 L.C. 5 Astro Liberia 1964 Lisboa (DLx) Luzon (Mindanao Island) Luzon (Philippines) Mahe 1971 Marco Astro Massawa Melrica 1973 (D73) Merchich Midway Astro 1961 Minna NAD 27 (Alaska) NAD 27 (Bahamas) NAD 27 (Canada) NAD 27 (Canal Zone) NAD 27 (Caribbean) NAD 27 (Central America) NAD 27 (Continental US) NAD 27 (Cuba) NAD 27 (Greenland) NAD 27 (Mexico) NAD 27 (Michigan) NAD 27 (San Salvador) NAD 83 NTF (Greenwich meridian) NTF (Paris meridian) NWGL 10 Nahrwan (Masirah Island) Nahrwan (Saudi Arabia) Nahrwan (Un. Arab Emirates) Naparima, BWI Netherlands Bessel Observatorio 1966 Old Egyptian Old Hawaiian Oman Ordinance Survey Great Brit Pico de las Nieves Pitcairn Astro 1967 Provisional South American Puerto Rico Pulkovo 1942 Qatar National Qornoq RT 90 (Sweden) Reunion Rome 1940 Santo (DOS) Sao Braz Sapper Hill 1943 Legacy Tables and Views Coordinate Systems (Spatial Reference Systems) 6-47 6.8.5 MDSYS.SDO_DIST_UNITS View The MDSYS.SDO_DIST_UNITS reference view contains one row for each valid distance UNIT specification in the well-known text (WKT) description in the coordinate system definition. The WKT is described in Section 6.8.1.1. The MDSYS.SDO_DIST_UNITS view is based on the SDO_UNITS_OF MEASURE table (described in Section 6.7.27), and it contains the columns shown in Table 6–32. 6.8.6 MDSYS.SDO_ELLIPSOIDS_OLD_FORMAT and SDO_ELLIPSOIDS_OLD_ SNAPSHOT Tables The MDSYS.SDO_ELLIPSOIDS_OLD_FORMAT and MDSYS.SDO_ELLIPSOIDS_ OLD_SNAPSHOT reference tables contain one row for each valid SPHEROID specification in the well-known text (WKT) description in the coordinate system definition. (The WKT is described in Section 6.8.1.1.) ■ MDSYS.SDO_ELLIPSOIDS_OLD_FORMAT contains the new data in the old format (that is, EPSG-based ellipsoid specifications in a table using the format from before release 10.2). ■ MDSYS.SDO_ELLIPSOIDS_OLD_SNAPSHOT contains the old data in the old format (that is, ellipsoid specifications and table format from before release 10.2). These tables contain the columns shown in Table 6–33. Schwarzeck South American 1969 South Asia Southeast Base Southwest Base Timbalai 1948 Tokyo Tristan Astro 1968 Viti Levu 1916 WGS 60 WGS 66 WGS 72 WGS 84 Wake-Eniwetok 1960 Yacare Zanderij Table 6–32 MDSYS.SDO_DIST_UNITS View Column Name Data Type Description SDO_UNIT VARCHAR2 Values are taken from the SHORT_NAME column of the SDO_UNITS_OF MEASURE table. UNIT_NAME VARCHAR2 Values are taken from the UNIT_OF_MEAS_NAME column of the SDO_UNITS_OF MEASURE table. CONVERSION_ FACTOR NUMBER Ratio of the unit to 1 meter. For example, the conversion factor for a meter is 1.0, and the conversion factor for a mile is 1609.344. Table 6–33 MDSYS.SDO_ELLIPSOIDS_OLD_FORMAT and SDO_ELLIPSOIDS_OLD_ SNAPSHOT Tables Column Name Data Type Description NAME VARCHAR2(80) for OLD_FORMAT VARCHAR2(64) for OLD_ SNAPSHOT Name of the ellipsoid (spheroid). Specify a value from this column in the SPHEROID specification of the WKT for any user-defined coordinate system. Examples: Clarke 1866, WGS 72, Australian, Krassovsky, International 1924. Legacy Tables and Views 6-48 Oracle Spatial Developer's Guide The following are the names (in tabular format) of the ellipsoids in these tables: 6.8.7 MDSYS.SDO_PROJECTIONS_OLD_FORMAT and SDO_PROJECTIONS_OLD_ SNAPSHOT Tables The MDSYS.SDO_PROJECTIONS_OLD_FORMAT and MDSYS.SDO_PROJECTIONS_ OLD_SNAPSHOT reference tables contain one row for each valid PROJECTION specification in the well-known text (WKT) description in the coordinate system definition. (The WKT is described in Section 6.8.1.1.) ■ MDSYS.SDO_PROJECTIONS_OLD_FORMAT contains the new data in the old format (that is, EPSG-based projection specifications in a table using the format from before release 10.2). ■ MDSYS.SDO_PROJECTIONS_OLD_SNAPSHOT contains the old data in the old format (that is, projection specifications and table format from before release 10.2). These tables contains the column shown in Table 6–34. SEMI_MAJOR_ AXIS NUMBER Radius in meters along the semi-major axis (one-half of the long axis of the ellipsoid). INVERSE_ FLATTENING NUMBER Inverse flattening of the ellipsoid. That is, 1/f, where f = (a-b)/a, and a is the semi-major axis and b is the semi-minor axis. Airy 1830 Airy 1830 (Ireland 1965) Australian Bessel 1841 Bessel 1841 (NGO 1948) Bessel 1841 (Schwarzeck) Clarke 1858 Clarke 1866 Clarke 1866 (Michigan) Clarke 1880 Clarke 1880 (Arc 1950) Clarke 1880 (IGN) Clarke 1880 (Jamaica) Clarke 1880 (Merchich) Clarke 1880 (Palestine) Everest Everest (Kalianpur) Everest (Kertau) Everest (Timbalai) Fischer 1960 (Mercury) Fischer 1960 (South Asia) Fischer 1968 GRS 67 GRS 80 Hayford Helmert 1906 Hough IAG 75 Indonesian International 1924 Krassovsky MERIT 83 NWL 10D NWL 9D New International 1967 OSU86F OSU91A Plessis 1817 South American 1969 Sphere (6370997m) Struve 1860 WGS 60 WGS 66 WGS 72 WGS 84 Walbeck War Office Table 6–33 (Cont.) MDSYS.SDO_ELLIPSOIDS_OLD_FORMAT and SDO_ELLIPSOIDS_ OLD_SNAPSHOT Tables Column Name Data Type Description Creating a User-Defined Coordinate Reference System Coordinate Systems (Spatial Reference Systems) 6-49 The following are the names (in tabular format) of the projections in these tables: 6.9 Creating a User-Defined Coordinate Reference System If the coordinate systems supplied by Oracle are not sufficient for your needs, you can create user-defined coordinate reference systems. Table 6–34 MDSYS.SDO_PROJECTIONS_OLD_FORMAT and SDO_PROJECTIONS_ OLD_SNAPSHOT Tables Column Name Data Type Description NAME VARCHAR2(80) for OLD_FORMAT VARCHAR2(64) for OLD_ SNAPSHOT Name of the map projection. Specify a value from this column in the PROJECTION specification of the WKT for any user-defined coordinate system. Examples: Geographic (Lat/Long), Universal Transverse Mercator, State Plane Coordinates, Albers Conical Equal Area. Alaska Conformal Albers Conical Equal Area Azimuthal Equidistant Bonne Cassini Cylindrical Equal Area Eckert IV Eckert VI Equidistant Conic Equirectangular Gall General Vertical Near-Side Perspective Geographic (Lat/Long) Gnomonic Hammer Hotine Oblique Mercator Interrupted Goode Homolosine Interrupted Mollweide Lambert Azimuthal Equal Area Lambert Conformal Conic Lambert Conformal Conic (Belgium 1972) Mercator Miller Cylindrical Mollweide New Zealand Map Grid Oblated Equal Area Orthographic Polar Stereographic Polyconic Robinson Sinusoidal Space Oblique Mercator State Plane Coordinates Stereographic Swiss Oblique Mercator Transverse Mercator Transverse Mercator Danish System 34 Jylland-Fyn Transverse Mercator Danish System 45 Bornholm Transverse Mercator Finnish KKJ Transverse Mercator Sjaelland Universal Transverse Mercator Van der Grinten Wagner IV Wagner VII Creating a User-Defined Coordinate Reference System 6-50 Oracle Spatial Developer's Guide The exact steps for creating a user-defined CRS depend on whether it is geodetic or projected. In both cases, supply information about the coordinate system (coordinate axes, axis names, unit of measurement, and so on). For a geodetic CRS, supply information about the datum (ellipsoid, prime meridian, and so on), as explained in Section 6.9.1. For a projected CRS, supply information about the source (geodetic) CRS and the projection (operation and parameters), as explained in Section 6.9.2. For any user-defined coordinate system, the SRID value should be 1000000 (1 million) or higher. 6.9.1 Creating a Geodetic CRS If the necessary unit of measurement, coordinate axes, SDO_COORD_SYS table row, ellipsoid, prime meridian, and datum are already defined, insert a row into the SDO_ COORD_REF_SYSTEM view (described in Section 6.7.10) to define the new geodetic CRS. Example 6–5 inserts the definition for a hypothetical geodetic CRS named My Own NAD27 (which, except for its SRID and name, is the same as the NAD27 CRS supplied by Oracle). Example 6–5 Creating a User-Defined Geodetic Coordinate Reference System INSERT INTO SDO_COORD_REF_SYSTEM ( SRID, COORD_REF_SYS_NAME, COORD_REF_SYS_KIND, COORD_SYS_ID, DATUM_ID, GEOG_CRS_DATUM_ID, SOURCE_GEOG_SRID, PROJECTION_CONV_ID, CMPD_HORIZ_SRID, CMPD_VERT_SRID, INFORMATION_SOURCE, DATA_SOURCE, IS_LEGACY, LEGACY_CODE, LEGACY_WKTEXT, LEGACY_CS_BOUNDS, IS_VALID, SUPPORTS_SDO_GEOMETRY) VALUES ( 9994267, 'My Own NAD27', 'GEOGRAPHIC2D', 6422, 6267, 6267, NULL, NULL, NULL, NULL, NULL, Note: As mentioned in Section 6.1.1, the terms coordinate system and coordinate reference system (CRS) are often used interchangeably, although coordinate reference systems must be Earth-based. Creating a User-Defined Coordinate Reference System Coordinate Systems (Spatial Reference Systems) 6-51 'EPSG', 'FALSE', NULL, NULL, NULL, 'TRUE', 'TRUE'); If the necessary information for the definition does not already exist, follow these steps, as needed, to define the information before you insert the row into the SDO_ COORD_REF_SYSTEM view: 1. If the unit of measurement is not already defined in the SDO_UNITS_OF_ MEASURE table (described in Section 6.7.27), insert a row into that table to define the new unit of measurement. 2. If the coordinate axes are not already defined in the SDO_COORD_AXES table (described in Section 6.7.1), insert one row into that table for each new coordinate axis. 3. If an appropriate entry for the coordinate system does not already exist in the SDO_COORD_SYS table (described in Section 6.7.11), insert a row into that table. Example 6–6 inserts the definition for a fictitious coordinate system. Example 6–6 Inserting a Row into the SDO_COORD_SYS Table INSERT INTO SDO_COORD_SYS ( COORD_SYS_ID, COORD_SYS_NAME, COORD_SYS_TYPE, DIMENSION, INFORMATION_SOURCE, DATA_SOURCE) VALUES ( 9876543, 'My custom CS. Axes: lat, long. Orientations: north, east. UoM: deg', 'ellipsoidal', 2, 'Myself', 'Myself'); 4. If the ellipsoid is not already defined in the SDO_ELLIPSOIDS table (described in Section 6.7.23), insert a row into that table to define the new ellipsoid. 5. If the prime meridian is not already defined in the SDO_PRIME_MERIDIANS table (described in Section 6.7.26), insert a row into that table to define the new prime meridian. 6. If the datum is not already defined in the SDO_DATUMS table (described in Section 6.7.22), insert a row into that table to define the new datum. 6.9.2 Creating a Projected CRS If the necessary unit of measurement, coordinate axes, SDO_COORD_SYS table row, source coordinate system, projection operation, and projection parameters are already defined, insert a row into the SDO_COORD_REF_SYSTEM view (described in Section 6.7.10) to define the new projected CRS. Example 6–7 inserts the definition for a hypothetical projected CRS named My Own NAD27 / Cuba Norte (which, except for its SRID and name, is the same as the NAD27 / Cuba Norte CRS supplied by Oracle). Creating a User-Defined Coordinate Reference System 6-52 Oracle Spatial Developer's Guide Example 6–7 Creating a User-Defined Projected Coordinate Reference System INSERT INTO SDO_COORD_REF_SYSTEM ( SRID, COORD_REF_SYS_NAME, COORD_REF_SYS_KIND, COORD_SYS_ID, DATUM_ID, GEOG_CRS_DATUM_ID, SOURCE_GEOG_SRID, PROJECTION_CONV_ID, CMPD_HORIZ_SRID, CMPD_VERT_SRID, INFORMATION_SOURCE, DATA_SOURCE, IS_LEGACY, LEGACY_CODE, LEGACY_WKTEXT, LEGACY_CS_BOUNDS, IS_VALID, SUPPORTS_SDO_GEOMETRY) VALUES ( 9992085, 'My Own NAD27 / Cuba Norte', 'PROJECTED', 4532, NULL, 6267, 4267, 18061, NULL, NULL, 'Institut Cubano di Hidrografia (ICH)', 'EPSG', 'FALSE', NULL, NULL, NULL, 'TRUE', 'TRUE'); If the necessary information for the definition does not already exist, follow these steps, as needed, to define the information before you insert the row into the SDO_ COORD_REF_SYSTEM view: 1. If the unit of measurement is not already defined in the SDO_UNITS_OF_ MEASURE table (described in Section 6.7.27), insert a row into that table to define the new unit of measurement. 2. If the coordinate axes are not already defined in the SDO_COORD_AXES table (described in Section 6.7.1), insert one row into that table for each new coordinate axis. 3. If an appropriate entry for the coordinate system does not already exist in SDO_ COORD_SYS table (described in Section 6.7.11), insert a row into that table. (See Example 6–6 in Section 6.9.1). 4. If the projection operation is not already defined in the SDO_COORD_OPS table (described in Section 6.7.8), insert a row into that table to define the new projection operation. Example 6–8 shows the statement used to insert information about coordinate operation ID 18061, which is supplied by Oracle. Creating a User-Defined Coordinate Reference System Coordinate Systems (Spatial Reference Systems) 6-53 Example 6–8 Inserting a Row into the SDO_COORD_OPS Table INSERT INTO SDO_COORD_OPS ( COORD_OP_ID, COORD_OP_NAME, COORD_OP_TYPE, SOURCE_SRID, TARGET_SRID, COORD_TFM_VERSION, COORD_OP_VARIANT, COORD_OP_METHOD_ID, UOM_ID_SOURCE_OFFSETS, UOM_ID_TARGET_OFFSETS, INFORMATION_SOURCE, DATA_SOURCE, SHOW_OPERATION, IS_LEGACY, LEGACY_CODE, REVERSE_OP, IS_IMPLEMENTED_FORWARD, IS_IMPLEMENTED_REVERSE) VALUES ( 18061, 'Cuba Norte', 'CONVERSION', NULL, NULL, NULL, NULL, 9801, NULL, NULL, NULL, 'EPSG', 1, 'FALSE', NULL, 1, 1, 1); 5. If the parameters for the projection operation are not already defined in the SDO_ COORD_OP_PARAM_VALS table (described in Section 6.7.5), insert one row into that table for each new parameter. Example 6–9 shows the statement used to insert information about parameters with ID values 8801, 8802, 8805, 8806, and 8807, which are supplied by Oracle. Example 6–9 Inserting a Row into the SDO_COORD_OP_PARAM_VALS Table INSERT INTO SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 18061, 9801, 8801, 22.21, Creating a User-Defined Coordinate Reference System 6-54 Oracle Spatial Developer's Guide NULL, 9110); INSERT INTO SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 18061, 9801, 8802, -81, NULL, 9110); INSERT INTO SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 18061, 9801, 8805, .99993602, NULL, 9201); INSERT INTO SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 18061, 9801, 8806, 500000, NULL, 9001); INSERT INTO SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 18061, 9801, 8807, 280296.016, Creating a User-Defined Coordinate Reference System Coordinate Systems (Spatial Reference Systems) 6-55 NULL, 9001); Example 6–10 provides an extended, annotated example of creating a user-defined projected coordinate system Example 6–10 Creating a User-Defined Projected CRS: Extended Example -- Create an EPSG equivalent for the following CRS: -- -- CS_NAME: VDOT_LAMBERT -- SRID: 51000000 -- AUTH_SRID: 51000000 -- AUTH_NAME: VDOT Custom Lambert Conformal Conic -- WKTEXT: -- -- PROJCS[ -- "VDOT_Lambert", -- GEOGCS[ -- "GCS_North_American_1983", -- DATUM[ -- "D_North_American_1983", -- SPHEROID["GRS_1980", 6378137.0, 298.257222101]], -- PRIMEM["Greenwich", 0.0], -- UNIT["Decimal Degree",0.0174532925199433]], -- PROJECTION["Lambert_Conformal_Conic"], -- PARAMETER["False_Easting", 0.0], -- PARAMETER["False_Northing", 0.0], -- PARAMETER["Central_Meridian", -79.5], -- PARAMETER["Standard_Parallel_1", 37.0], -- PARAMETER["Standard_Parallel_2", 39.5], -- PARAMETER["Scale_Factor", 1.0], -- PARAMETER["Latitude_Of_Origin", 36.0], -- UNIT["Meter", 1.0]] -- First, the base geographic CRS (GCS_North_American_1983) already exists in EPSG. -- It is 4269: -- Next, find the EPSG equivalent for PROJECTION["Lambert_Conformal_Conic"]: select coord_op_method_id, legacy_name from sdo_coord_op_methods where not legacy_name is null order by coord_op_method_id; -- Result: -- COORD_OP_METHOD_ID LEGACY_NAME -- ------------------ -------------------------------------------------- -- 9802 Lambert Conformal Conic -- 9803 Lambert Conformal Conic (Belgium 1972) -- 9805 Mercator -- 9806 Cassini -- 9807 Transverse Mercator -- 9829 Polar Stereographic -- -- 6 rows selected. Creating a User-Defined Coordinate Reference System 6-56 Oracle Spatial Developer's Guide -- -- It is EPSG method 9802. Create a projection operation 510000001, based on it: insert into MDSYS.SDO_COORD_OPS ( COORD_OP_ID, COORD_OP_NAME, COORD_OP_TYPE, SOURCE_SRID, TARGET_SRID, COORD_TFM_VERSION, COORD_OP_VARIANT, COORD_OP_METHOD_ID, UOM_ID_SOURCE_OFFSETS, UOM_ID_TARGET_OFFSETS, INFORMATION_SOURCE, DATA_SOURCE, SHOW_OPERATION, IS_LEGACY, LEGACY_CODE, REVERSE_OP, IS_IMPLEMENTED_FORWARD, IS_IMPLEMENTED_REVERSE) VALUES ( 510000001, 'VDOT_Lambert', 'CONVERSION', NULL, NULL, NULL, NULL, 9802, NULL, NULL, NULL, NULL, 1, 'FALSE', NULL, 1, 1, 1); -- Now, set the parameters. See which are required: select use.parameter_id || ': ' || use.legacy_param_name from sdo_coord_op_param_use use where use.coord_op_method_id = 9802; -- result: -- 8821: Latitude_Of_Origin -- 8822: Central_Meridian -- 8823: Standard_Parallel_1 -- 8824: Standard_Parallel_2 -- 8826: False_Easting -- 8827: False_Northing -- Creating a User-Defined Coordinate Reference System Coordinate Systems (Spatial Reference Systems) 6-57 -- 6 rows selected. -- Also check the most common units we will need: select UOM_ID || ': ' || UNIT_OF_MEAS_NAME from sdo_units_of_measure where uom_id in (9001, 9101, 9102, 9201) order by uom_id; -- result: -- 9001: metre -- 9101: radian -- 9102: degree -- 9201: unity -- Now, configure the projection parameters: -- 8821: Latitude_Of_Origin insert into MDSYS.SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 510000001, 9802, 8821, 36.0, NULL, 9102); -- 8822: Central_Meridian insert into MDSYS.SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 510000001, 9802, 8822, -79.5, NULL, 9102); -- 8823: Standard_Parallel_1 insert into MDSYS.SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, Creating a User-Defined Coordinate Reference System 6-58 Oracle Spatial Developer's Guide COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 510000001, 9802, 8823, 37.0, NULL, 9102); -- 8824: Standard_Parallel_2 insert into MDSYS.SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 510000001, 9802, 8824, 39.5, NULL, 9102); -- 8826: False_Easting insert into MDSYS.SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 510000001, 9802, 8826, 0.0, NULL, 9001); -- 8827: False_Northing insert into MDSYS.SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 510000001, 9802, 8827, Creating a User-Defined Coordinate Reference System Coordinate Systems (Spatial Reference Systems) 6-59 0.0, NULL, 9001); -- Now, create the actual projected CRS.Look at the GEOG_CRS_DATUM_ID -- and COORD_SYS_ID first. The GEOG_CRS_DATUM_ID is the datum of -- the base geog_crs (4269): select datum_id from sdo_coord_ref_sys where srid = 4269; -- DATUM_ID -- ---------- -- 6269 -- And the COORD_SYS_ID is the Cartesian CS used for the projected CRS. -- We can use 4400, if meters will be the unit: select COORD_SYS_NAME from sdo_coord_sys where COORD_SYS_ID = 4400; -- Cartesian 2D CS. Axes: easting, northing (E,N). Orientations: east, north. -- UoM: m. -- Now create the projected CRS: insert into MDSYS.SDO_COORD_REF_SYSTEM ( SRID, COORD_REF_SYS_NAME, COORD_REF_SYS_KIND, COORD_SYS_ID, DATUM_ID, SOURCE_GEOG_SRID, PROJECTION_CONV_ID, CMPD_HORIZ_SRID, CMPD_VERT_SRID, INFORMATION_SOURCE, DATA_SOURCE, IS_LEGACY, LEGACY_CODE, LEGACY_WKTEXT, LEGACY_CS_BOUNDS, GEOG_CRS_DATUM_ID) VALUES ( 51000000, 'VDOT_LAMBERT', 'PROJECTED', 4400, NULL, 4269, 510000001, NULL, NULL, NULL, NULL, 'FALSE', NULL, NULL, NULL, 6269); -- To see the result: Creating a User-Defined Coordinate Reference System 6-60 Oracle Spatial Developer's Guide select srid, wktext from cs_srs where srid = 51000000; -- 51000000 -- PROJCS[ -- "VDOT_LAMBERT", -- GEOGCS [ -- "NAD83", -- DATUM [ -- "North American Datum 1983 (EPSG ID 6269)", -- SPHEROID [ -- "GRS 1980 (EPSG ID 7019)", -- 6378137, -- 298.257222101]], -- PRIMEM [ "Greenwich", 0.000000 ], -- UNIT ["Decimal Degree", 0.01745329251994328]], -- PROJECTION ["VDOT_Lambert"], -- PARAMETER ["Latitude_Of_Origin", 36], -- PARAMETER ["Central_Meridian", -79.50000000000000000000000000000000000028], -- PARAMETER ["Standard_Parallel_1", 37], -- PARAMETER ["Standard_Parallel_2", 39.5], -- PARAMETER ["False_Easting", 0], -- PARAMETER ["False_Northing", 0], -- UNIT ["Meter", 1]] 6.9.3 Creating a Vertical CRS A vertical CRS has only one dimension, usually height. On its own, a vertical CRS is of little use, but it can be combined with a two-dimensional CRS (geodetic or projected), to result in a compound CRS. Example 6–11 shows the statement that created the vertical CRS with SRID 5701, which is included with Spatial. This definition refers to an existing (one-dimensional) coordinate system (ID 6499; see Section 6.7.11, "SDO_ COORD_SYS Table") and vertical datum (ID 5101; see Section 6.7.22, "SDO_DATUMS Table"). Example 6–11 Creating a Vertical Coordinate Reference System INSERT INTO MDSYS.SDO_COORD_REF_SYSTEM ( SRID, COORD_REF_SYS_NAME, COORD_REF_SYS_KIND, COORD_SYS_ID, DATUM_ID, SOURCE_GEOG_SRID, PROJECTION_CONV_ID, CMPD_HORIZ_SRID, CMPD_VERT_SRID, INFORMATION_SOURCE, DATA_SOURCE, IS_LEGACY, LEGACY_CODE, LEGACY_WKTEXT, LEGACY_CS_BOUNDS) VALUES ( 5701, 'Newlyn', 'VERTICAL', 6499, 5101, NULL, Creating a User-Defined Coordinate Reference System Coordinate Systems (Spatial Reference Systems) 6-61 NULL, NULL, NULL, NULL, 'EPSG', 'FALSE', NULL, NULL, NULL); A vertical CRS might define some undulating equipotential surface. The shape of that surface, and its offset from some ellipsoid, is not actually defined in the vertical CRS record itself (other than textually). Instead, that definition is included in an operation between the vertical CRS and another CRS. Consequently, you can define several alternative operations between the same pair of geoidal and WGS84-ellipsoidal heights. For example, there are geoid offset matrixes GEOID90, GEOID93, GEOID96, GEOID99, GEOID03, GEOID06, and others, and for each of these variants there can be a separate operation. Section 6.9.6 describes such an operation. 6.9.4 Creating a Compound CRS A compound CRS combines an existing horizontal (two-dimensional) CRS and a vertical (one-dimensional) CRS. The horizontal CRS can be geodetic or projected. Example 6–12 shows the statement that created the compound CRS with SRID 7405, which is included with Spatial. This definition refers to an existing projected CRS and vertical CRS (IDs 27700 and 5701, respectively; see Section 6.7.9, "SDO_COORD_REF_ SYS Table"). Example 6–12 Creating a Compound Coordinate Reference System INSERT INTO MDSYS.SDO_COORD_REF_SYSTEM ( SRID, COORD_REF_SYS_NAME, COORD_REF_SYS_KIND, COORD_SYS_ID, DATUM_ID, SOURCE_GEOG_SRID, PROJECTION_CONV_ID, CMPD_HORIZ_SRID, CMPD_VERT_SRID, INFORMATION_SOURCE, DATA_SOURCE, IS_LEGACY, LEGACY_CODE, LEGACY_WKTEXT, LEGACY_CS_BOUNDS) VALUES ( 7405, 'OSGB36 / British National Grid + ODN', 'COMPOUND', NULL, NULL, NULL, NULL, 27700, 5701, NULL, 'EPSG', 'FALSE', Creating a User-Defined Coordinate Reference System 6-62 Oracle Spatial Developer's Guide NULL, NULL, NULL); 6.9.5 Creating a Geographic 3D CRS A geographic 3D CRS is the combination of a geographic 2D CRS with ellipsoidal height. Example 6–13 shows the statement that created the geographic 3D CRS with SRID 4327, which is included with Spatial. This definition refers to an existing projected coordinate system (ID 6401; see Section 6.7.11, "SDO_COORD_SYS Table") and datum (ID 6326; see Section 6.7.22, "SDO_DATUMS Table"). Example 6–13 Creating a Geographic 3D Coordinate Reference System INSERT INTO MDSYS.SDO_COORD_REF_SYSTEM ( SRID, COORD_REF_SYS_NAME, COORD_REF_SYS_KIND, COORD_SYS_ID, DATUM_ID, GEOG_CRS_DATUM_ID, SOURCE_GEOG_SRID, PROJECTION_CONV_ID, CMPD_HORIZ_SRID, CMPD_VERT_SRID, INFORMATION_SOURCE, DATA_SOURCE, IS_LEGACY, LEGACY_CODE, LEGACY_WKTEXT, LEGACY_CS_BOUNDS, IS_VALID, SUPPORTS_SDO_GEOMETRY) VALUES ( 4327, 'WGS 84 (geographic 3D)', 'GEOGRAPHIC3D', 6401, 6326, 6326, NULL, NULL, NULL, NULL, 'NIMA TR8350.2 January 2000 revision. http://164.214.2.59/GandG/tr8350_2.html', 'EPSG', 'FALSE', NULL, NULL, NULL, 'TRUE', 'TRUE'); 6.9.6 Creating a Transformation Operation Section 6.9.2 described the creation of a projection operation, for the purpose of then creating a projected CRS. A similar requirement can arise when using a compound CRS based on orthometric height: you may want to transform from and to ellipsoidal height. The offset between the two heights is undulating and irregular. Creating a User-Defined Coordinate Reference System Coordinate Systems (Spatial Reference Systems) 6-63 By default, Spatial transforms between ellipsoidal and orthometric height using an identity transformation. (Between different ellipsoids, the default would instead be a datum transformation.) The identity transformation is a reasonable approximation; however, a more accurate approach involves an EPSG type 9635 operation, involving an offset matrix. Example 6–14 is a declaration of such an operation: Example 6–14 Creating a Transformation Operation INSERT INTO MDSYS.SDO_COORD_OPS ( COORD_OP_ID, COORD_OP_NAME, COORD_OP_TYPE, SOURCE_SRID, TARGET_SRID, COORD_TFM_VERSION, COORD_OP_VARIANT, COORD_OP_METHOD_ID, UOM_ID_SOURCE_OFFSETS, UOM_ID_TARGET_OFFSETS, INFORMATION_SOURCE, DATA_SOURCE, SHOW_OPERATION, IS_LEGACY, LEGACY_CODE, REVERSE_OP, IS_IMPLEMENTED_FORWARD, IS_IMPLEMENTED_REVERSE) VALUES ( 999998, 'Test operation, based on GEOID03 model, using Hawaii grid', 'TRANSFORMATION', NULL, NULL, NULL, NULL, 9635, NULL, NULL, 'NGS', 'NGS', 1, 'FALSE', NULL, 1, 1, 1); INSERT INTO MDSYS.SDO_COORD_OP_PARAM_VALS ( COORD_OP_ID, COORD_OP_METHOD_ID, PARAMETER_ID, PARAMETER_VALUE, PARAM_VALUE_FILE_REF, UOM_ID) VALUES ( 999998, 9635, 8666, NULL, 'g2003h01.asc', Creating a User-Defined Coordinate Reference System 6-64 Oracle Spatial Developer's Guide NULL); The second INSERT statement in Example 6–14 specifies the file name g2003h01.asc, but not yet its actual CLOB content with the offset matrix. As with NADCON and NTv2 matrixes, geoid matrixes have to be loaded into the PARAM_ VALUE_FILE column. Due to space and copyright considerations, Oracle does not supply most of these matrixes; however, they are usually available for download on the Web. Good sources are the relevant government web sites, and you can search by file name (such as g2003h01 in this example). Although some of these files are available in both binary format (such as .gsb) and ASCII format (such as .gsa or .asc), only the ASCII variant can be used with Spatial. The existing EPSG operations include file names in standard use. Example 6–15 is a script for loading a set of such matrixes. It loads specified physical files (such as ntv20.gsa) into database CLOBs, based on the official file name reference (such as NTV2_0.GSB). Example 6–15 Loading Offset Matrixes DECLARE ORCL_HOME_DIR VARCHAR2(128); ORCL_WORK_DIR VARCHAR2(128); Src_loc BFILE; Dest_loc CLOB; CURSOR PARAM_FILES IS SELECT COORD_OP_ID, PARAMETER_ID, PARAM_VALUE_FILE_REF FROM MDSYS.SDO_COORD_OP_PARAM_VALS WHERE PARAMETER_ID IN (8656, 8657, 8658, 8666); PARAM_FILE PARAM_FILES%ROWTYPE; ACTUAL_FILE_NAME VARCHAR2(128); platform NUMBER; BEGIN EXECUTE IMMEDIATE 'CREATE OR REPLACE DIRECTORY work_dir AS ''define_your_source_ directory_here'''; FOR PARAM_FILE IN PARAM_FILES LOOP CASE UPPER(PARAM_FILE.PARAM_VALUE_FILE_REF) /* NTv2, fill in your files here */ WHEN 'NTV2_0.GSB' THEN ACTUAL_FILE_NAME := 'ntv20.gsa'; /* GEOID03, fill in your files here */ WHEN 'G2003H01.ASC' THEN ACTUAL_FILE_NAME := 'g2003h01.asc'; ELSE ACTUAL_FILE_NAME := NULL; END CASE; IF(NOT (ACTUAL_FILE_NAME IS NULL)) THEN BEGIN dbms_output.put_line('Loading file ' || actual_file_name || '...'); Src_loc := BFILENAME('WORK_DIR', ACTUAL_FILE_NAME); DBMS_LOB.OPEN(Src_loc, DBMS_LOB.LOB_READONLY); END; UPDATE MDSYS.SDO_COORD_OP_PARAM_VALS SET PARAM_VALUE_FILE = EMPTY_CLOB() Creating a User-Defined Coordinate Reference System Coordinate Systems (Spatial Reference Systems) 6-65 WHERE COORD_OP_ID = PARAM_FILE.COORD_OP_ID AND PARAMETER_ID = PARAM_FILE.PARAMETER_ID RETURNING PARAM_VALUE_FILE INTO Dest_loc; DBMS_LOB.OPEN(Dest_loc, DBMS_LOB.LOB_READWRITE); DBMS_LOB.LOADFROMFILE(Dest_loc, Src_loc, DBMS_LOB.LOBMAXSIZE); DBMS_LOB.CLOSE(Dest_loc); DBMS_LOB.CLOSE(Src_loc); DBMS_LOB.FILECLOSE(Src_loc); END IF; END LOOP; END; / 6.9.7 Using British Grid Transformation OSTN02/OSGM02 (EPSG Method 9633) To use British Grid Transformation OSTN02/OSGM02 (EPSG method 9633) in a projected coordinate reference system, you must first insert a modified version of the OSTN02_OSGM02_GB.txt grid file into the PARAM_VALUE_FILE column (type CLOB) of the SDO_COORD_OP_PARAM_VALS table (described in Section 6.7.5). The OSTN02_OSGM02_GB.txt file contains the offset matrix on which EPSG transformation method 9633 is based. Follow these steps: 1. Download the following file: http://www.ordnancesurvey.co.uk/oswebsite/gps/docs/OSTN02_ OSGM02files.zip 2. From the OSTN02_OSGM02files.zip file, extract the following file: OSTN02_ OSGM02_GB.txt 3. Edit your copy of OSTN02_OSGM02_GB.txt, and insert the following lines before the first line of the current file: SDO Header x: 0.0 - 700000.0 y: 0.0 - 1250000.0 x-intervals: 1000.0 y-intervals: 1000.0 End of SDO Header The is, after the editing operation, the contents of the file will look like this: SDO Header x: 0.0 - 700000.0 y: 0.0 - 1250000.0 x-intervals: 1000.0 y-intervals: 1000.0 End of SDO Header 1,0,0,0.000,0.000,0.000,0 2,1000,0,0.000,0.000,0.000,0 3,2000,0,0.000,0.000,0.000,0 4,3000,0,0.000,0.000,0.000,0 5,4000,0,0.000,0.000,0.000,0 . . . 876949,698000,1250000,0.000,0.000,0.000,0 876950,699000,1250000,0.000,0.000,0.000,0 876951,700000,1250000,0.000,0.000,0.000,0 Creating a User-Defined Coordinate Reference System 6-66 Oracle Spatial Developer's Guide 4. Save the edited file, perhaps using a different name (for example, my_OSTN02_ OSGM02_GB.txt). 5. In the SDO_COORD_OP_PARAM_VALS table, for each operation of EPSG method 9633 that has PARAM_VALUE_FILE_REF value OSTN02_OSGM02_ GB.TXT, update the PARAM_VALUE_FILE column to be the contents of the saved file (for example, the contents of my_OSTN02_OSGM02_GB.txt). You can use coding similar to that in Example 6–16. Example 6–16 Using British Grid Transformation OSTN02/OSGM02 (EPSG Method 9633) DECLARE ORCL_HOME_DIR VARCHAR2(128); ORCL_WORK_DIR VARCHAR2(128); Src_loc BFILE; Dest_loc CLOB; CURSOR PARAM_FILES IS SELECT COORD_OP_ID, PARAMETER_ID, PARAM_VALUE_FILE_REF FROM MDSYS.SDO_COORD_OP_PARAM_VALS WHERE PARAMETER_ID IN (8656, 8657, 8658, 8664, 8666) order by COORD_OP_ID, PARAMETER_ID; PARAM_FILE PARAM_FILES%ROWTYPE; ACTUAL_FILE_NAME VARCHAR2(128); platform NUMBER; BEGIN EXECUTE IMMEDIATE 'CREATE OR REPLACE DIRECTORY work_dir AS ''' || system.geor_ dir || ''''; FOR PARAM_FILE IN PARAM_FILES LOOP CASE UPPER(PARAM_FILE.PARAM_VALUE_FILE_REF) /* NTv2 */ WHEN 'NTV2_0.GSB' THEN ACTUAL_FILE_NAME := 'ntv20.gsa'; /* GEOID03 */ WHEN 'G2003H01.ASC' THEN ACTUAL_FILE_NAME := 'g2003h01.asc'; /* British Ordnance Survey (9633) */ WHEN 'OSTN02_OSGM02_GB.TXT' THEN ACTUAL_FILE_NAME := 'my_OSTN02_OSGM02_GB.txt'; ELSE ACTUAL_FILE_NAME := NULL; END CASE; IF(NOT (ACTUAL_FILE_NAME IS NULL)) THEN BEGIN dbms_output.put_line('Loading file ' || actual_file_name || '...'); Src_loc := BFILENAME('WORK_DIR', ACTUAL_FILE_NAME); DBMS_LOB.OPEN(Src_loc, DBMS_LOB.LOB_READONLY); END; UPDATE MDSYS.SDO_COORD_OP_PARAM_VALS SET PARAM_VALUE_FILE = EMPTY_CLOB() WHERE COORD_OP_ID = PARAM_FILE.COORD_OP_ID AND Notes and Restrictions with Coordinate Systems Support Coordinate Systems (Spatial Reference Systems) 6-67 PARAMETER_ID = PARAM_FILE.PARAMETER_ID RETURNING PARAM_VALUE_FILE INTO Dest_loc; DBMS_LOB.OPEN(Dest_loc, DBMS_LOB.LOB_READWRITE); DBMS_LOB.LOADFROMFILE(Dest_loc, Src_loc, DBMS_LOB.LOBMAXSIZE); DBMS_LOB.CLOSE(Dest_loc); DBMS_LOB.CLOSE(Src_loc); DBMS_LOB.FILECLOSE(Src_loc); END IF; END LOOP; END; / Note that adding "header" information to a grid file is required only for British Grid Transformation OSTN02/OSGM02. It is not required for NADCON, NTv2, or VERTCON matrixes, because they already have headers of varying formats. See also the following for related information: ■ Section 6.9.2, "Creating a Projected CRS" ■ Section 6.9.6, "Creating a Transformation Operation" 6.10 Notes and Restrictions with Coordinate Systems Support The following notes and restrictions apply to coordinate systems support in the current release of Oracle Spatial. If you have geodetic data, see Section 6.2 for additional considerations, guidelines, and restrictions. 6.10.1 Different Coordinate Systems for Geometries with Operators and Functions For Spatial operators (described in Chapter 19) that take two geometries as input parameters, if the geometries are based on different coordinate systems, the query window (the second geometry) is transformed to the coordinate system of the first geometry before the operation is performed. This transformation is a temporary internal operation performed by Spatial; it does not affect any stored query-window geometry. For SDO_GEOM package geometry functions (described in Chapter 24) that take two geometries as input parameters, both geometries must be based on the same coordinate system. 6.10.2 3D LRS Functions Not Supported with Geodetic Data In the current release, the 3D formats of LRS functions (explained in Section 7.4) are not supported with geodetic data. 6.10.3 Functions Supported by Approximations with Geodetic Data In the current release, the following functions are supported by approximations with geodetic data: ■ SDO_GEOM.SDO_BUFFER ■ SDO_GEOM.SDO_CENTROID ■ SDO_GEOM.SDO_CONVEXHULL U.S. National Grid Support 6-68 Oracle Spatial Developer's Guide When these functions are used on data with geodetic coordinates, they internally perform the operations in an implicitly generated local-tangent-plane Cartesian coordinate system and then transform the results to the geodetic coordinate system. For SDO_GEOM.SDO_BUFFER, generated arcs are approximated by line segments before the back-transform. 6.10.4 Unknown CRS and NaC Coordinate Reference Systems The following coordinate reference systems are provided for Oracle internal use and for other possible special uses: ■ unknown CRS (SRID 999999) means that the coordinate system is unknown, and its space could be geodetic or Cartesian. Contrast this with specifying a null coordinate reference system, which indicates an unknown coordinate system with a Cartesian space. ■ NaC (SRID 999998) means Not-a-CRS. Its name is patterned after the NaN (Not-a-Number) value in Java. It is intended for potential use with nonspatial geometries. The following restrictions apply to geometries based on the unknown CRS and NaC coordinate reference systems: ■ You cannot perform coordinate system transformations on these geometries. ■ Operations that require a coordinate system will return a null value when performed on these geometries. These operations include finding the area or perimeter of a geometry, creating a buffer, densifying an arc, and computing the aggregate centroid. 6.11 U.S. National Grid Support The U.S. National Grid is a point coordinate representation using a single alphanumeric coordinate (for example, 18SUJ2348316806479498). This approach contrasts with the use of numeric coordinates to represent the location of a point, as is done with Oracle Spatial and EPSG. A good description of the U.S. National Grid is available at http://www.ngs.noaa.gov/TOOLS/usng.html. To support the U.S. National Grid in Spatial, the SDO_GEOMETRY type cannot be used because it is based on numeric coordinates. Instead, a point in U.S. National Grid format is represented as a single string of type VARCHAR2. To allow conversion between the SDO_GEOMETRY format and the U.S. National grid format, the SDO_CS package (documented in Chapter 21) contains the following functions: ■ SDO_CS.FROM_USNG ■ SDO_CS.TO_USNG 6.12 Google Maps Considerations Google Maps uses spherical math in its projections, as opposed to the ellipsoidal math used by Oracle Spatial. This difference can lead to inconsistencies in applications, such as when overlaying a map based on Google Maps with a map based on an Oracle Spatial ellipsoidal projection. For example, an Oracle Spatial transformation from the ellipsoidal SRID 8307 to the spherical SRID 3785 accounts, by default, for the different ellipsoidal shapes, whereas Google Maps does not consider ellipsoidal shapes. If you want Oracle Spatial to accommodate the Google Maps results, consider the following options: Example of Coordinate System Transformation Coordinate Systems (Spatial Reference Systems) 6-69 ■ Use the spherical SRID 4055 instead of the ellipsoidal SRID 8307. This may be the simplest approach; however, if you need to accommodate SRID 8307-based data (such as from a third-party tool) as if it were spherical, you must use another option. ■ Declare an EPSG rule between the ellipsoidal and spherical coordinate systems. For example, declare an EPSG rule between SRIDs 8307 and 3785, ignoring the ellipsoidal shape of SRID 8307, as in the following example: CALL sdo_cs.create_pref_concatenated_op( 302, 'CONCATENATED OPERATION', TFM_PLAN(SDO_TFM_CHAIN(8307, 1000000000, 4055, 19847, 3785)), NULL); In this example, operation 1000000000 represents no-operation, causing the datum transformation between ellipsoid and sphere to be ignored. With this approach, you must declare a rule for each desired SRID pair (ellipsoidal and spherical). ■ Specify a use case name of USE_SPHERICAL with the SDO_CS.TRANSFORM function or the SDO_CS.TRANSFORM_LAYER procedure, as in the following examples: SELECT SDO_CS.TRANSFORM( sdo_geometry( 2001, 4326, sdo_point_type(1, 1, null), null, null), 'USE_SPHERICAL', 3785) FROM DUAL; CALL SDO_CS.TRANSFORM_LAYER( 'source_geoms', 'GEOMETRY', 'GEO_CS_3785_SPHERICAL', 'USE_SPHERICAL', 3785); If you specify a use_case parameter value of USE_SPHERICAL in such cases, the transformation defaults to using spherical math instead of ellipsoidal math, thereby accommodating Google Maps and some other third-party tools that use spherical math. If you use this approach (specifying ’USE_SPHERICAL’) but you have also declared an EPSG rule requiring that ellipsoidal math be used in transformations between two specified SRIDs, then the declared EPSG rule takes precedence and ellipsoidal math is used for transformations between those two SRIDs. 6.13 Example of Coordinate System Transformation This section presents a simplified example that uses coordinate system transformation functions and procedures. It refers to concepts that are explained in this chapter and uses functions documented in Chapter 21. Example of Coordinate System Transformation 6-70 Oracle Spatial Developer's Guide Example 6–17 uses mostly the same geometry data (cola markets) as in Section 2.1, except that instead of null SDO_SRID values, the SDO_SRID value 8307 is used. That is, the geometries are defined as using the coordinate system whose SRID is 8307 and whose well-known name is "Longitude / Latitude (WGS 84)". This is probably the most widely used coordinate system, and it is the one used for global positioning system (GPS) devices. The geometries are then transformed using the coordinate system whose SRID is 8199 and whose well-known name is "Longitude / Latitude (Arc 1950)". Example 6–17 uses the geometries illustrated in Figure 2–1 in Section 2.1, except that cola_d is a rectangle (here, a square) instead of a circle, because arcs are not supported with geodetic coordinate systems. Example 6–17 does the following: ■ Creates a table (COLA_MARKETS_CS) to hold the spatial data ■ Inserts rows for four areas of interest (cola_a, cola_b, cola_c, cola_d), using the SDO_SRID value 8307 ■ Updates the USER_SDO_GEOM_METADATA view to reflect the dimension of the areas, using the SDO_SRID value 8307 ■ Creates a spatial index (COLA_SPATIAL_IDX_CS) ■ Performs some transformation operations (single geometry and entire layer) Example 6–18 includes the output of the SELECT statements in Example 6–17. Example 6–17 Simplified Example of Coordinate System Transformation -- Create a table for cola (soft drink) markets in a -- given geography (such as city or state). CREATE TABLE cola_markets_cs ( mkt_id NUMBER PRIMARY KEY, name VARCHAR2(32), shape SDO_GEOMETRY); -- The next INSERT statement creates an area of interest for -- Cola A. This area happens to be a rectangle. -- The area could represent any user-defined criterion: for -- example, where Cola A is the preferred drink, where -- Cola A is under competitive pressure, where Cola A -- has strong growth potential, and so on. INSERT INTO cola_markets_cs VALUES( 1, 'cola_a', SDO_GEOMETRY( 2003, -- two-dimensional polygon 8307, -- SRID for 'Longitude / Latitude (WGS 84)' coordinate system NULL, SDO_ELEM_INFO_ARRAY(1,1003,1), -- polygon SDO_ORDINATE_ARRAY(1,1, 5,1, 5,7, 1,7, 1,1) -- All vertices must -- be defined for rectangle with geodetic data. ) ); -- The next two INSERT statements create areas of interest for -- Cola B and Cola C. These areas are simple polygons (but not -- rectangles). Example of Coordinate System Transformation Coordinate Systems (Spatial Reference Systems) 6-71 INSERT INTO cola_markets_cs VALUES( 2, 'cola_b', SDO_GEOMETRY( 2003, -- two-dimensional polygon 8307, NULL, SDO_ELEM_INFO_ARRAY(1,1003,1), -- one polygon (exterior polygon ring) SDO_ORDINATE_ARRAY(5,1, 8,1, 8,6, 5,7, 5,1) ) ); INSERT INTO cola_markets_cs VALUES( 3, 'cola_c', SDO_GEOMETRY( 2003, -- two-dimensional polygon 8307, NULL, SDO_ELEM_INFO_ARRAY(1,1003,1), --one polygon (exterior polygon ring) SDO_ORDINATE_ARRAY(3,3, 6,3, 6,5, 4,5, 3,3) ) ); -- Insert a rectangle (here, square) instead of a circle as in the original, -- because arcs are not supported with geodetic coordinate systems. INSERT INTO cola_markets_cs VALUES( 4, 'cola_d', SDO_GEOMETRY( 2003, -- two-dimensional polygon 8307, -- SRID for 'Longitude / Latitude (WGS 84)' coordinate system NULL, SDO_ELEM_INFO_ARRAY(1,1003,1), -- polygon SDO_ORDINATE_ARRAY(10,9, 11,9, 11,10, 10,10, 10,9) -- All vertices must -- be defined for rectangle with geodetic data. ) ); --------------------------------------------------------------------------- -- UPDATE METADATA VIEW -- --------------------------------------------------------------------------- -- Update the USER_SDO_GEOM_METADATA view. This is required -- before the Spatial index can be created. Do this only once for each -- layer (table-column combination; here: cola_markets_cs and shape). INSERT INTO user_sdo_geom_metadata (TABLE_NAME, COLUMN_NAME, DIMINFO, SRID) VALUES ( 'cola_markets_cs', 'shape', SDO_DIM_ARRAY( SDO_DIM_ELEMENT('Longitude', -180, 180, 10), -- 10 meters tolerance SDO_DIM_ELEMENT('Latitude', -90, 90, 10) -- 10 meters tolerance ), 8307 -- SRID for 'Longitude / Latitude (WGS 84)' coordinate system Example of Coordinate System Transformation 6-72 Oracle Spatial Developer's Guide ); ------------------------------------------------------------------- -- CREATE THE SPATIAL INDEX -- ------------------------------------------------------------------- CREATE INDEX cola_spatial_idx_cs ON cola_markets_cs(shape) INDEXTYPE IS MDSYS.SPATIAL_INDEX; ------------------------------------------------------------------- -- TEST COORDINATE SYSTEM TRANSFORMATION -- ------------------------------------------------------------------- -- Return the transformation of cola_c using to_srid 8199 -- ('Longitude / Latitude (Arc 1950)') SELECT c.name, SDO_CS.TRANSFORM(c.shape, 8199) FROM cola_markets_cs c WHERE c.name = 'cola_c'; -- Same as preceding, but using to_srname parameter. SELECT c.name, SDO_CS.TRANSFORM(c.shape, 'Longitude / Latitude (Arc 1950)') FROM cola_markets_cs c WHERE c.name = 'cola_c'; -- Transform the entire SHAPE layer and put results in the table -- named cola_markets_cs_8199, which the procedure will create. CALL SDO_CS.TRANSFORM_LAYER('COLA_MARKETS_CS','SHAPE','COLA_MARKETS_CS_ 8199',8199); -- Select all from the old (existing) table. SELECT * from cola_markets_cs; -- Select all from the new (layer transformed) table. SELECT * from cola_markets_cs_8199; -- Show metadata for the new (layer transformed) table. DESCRIBE cola_markets_cs_8199; -- Use a geodetic MBR with SDO_FILTER. SELECT c.name FROM cola_markets_cs c WHERE SDO_FILTER(c.shape, SDO_GEOMETRY( 2003, 8307, -- SRID for WGS 84 longitude/latitude NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(6,5, 10,10)) ) = 'TRUE'; Example 6–18 shows the output of the SELECT statements in Example 6–17. Notice the slight differences between the coordinates in the original geometries (SRID 8307) and the transformed coordinates (SRID 8199) -- for example, (1, 1, 5, 1, 5, 7, 1, 7, 1, 1) and (1.00078604, 1.00274579, 5.00069354, 1.00274488, 5.0006986, 7.00323528, 1.00079179, 7.00324162, 1.00078604, 1.00274579) for cola_a. Example 6–18 Output of SELECT Statements in Coordinate System Transformation Example SQL> -- Return the transformation of cola_c using to_srid 8199 SQL> -- ('Longitude / Latitude (Arc 1950)') SQL> SELECT c.name, SDO_CS.TRANSFORM(c.shape, 8199) 2 FROM cola_markets_cs c WHERE c.name = 'cola_c'; Example of Coordinate System Transformation Coordinate Systems (Spatial Reference Systems) 6-73 NAME -------------------------------- SDO_CS.TRANSFORM(C.SHAPE,8199)(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM -------------------------------------------------------------------------------- cola_c SDO_GEOMETRY(2003, 8199, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(3.00074114, 3.00291482, 6.00067068, 3.00291287, 6.0006723, 5.00307625, 4.0007 1961, 5.00307838, 3.00074114, 3.00291482)) SQL> SQL> -- Same as preceding, but using to_srname parameter. SQL> SELECT c.name, SDO_CS.TRANSFORM(c.shape, 'Longitude / Latitude (Arc 1950)') 2 FROM cola_markets_cs c WHERE c.name = 'cola_c'; NAME -------------------------------- SDO_CS.TRANSFORM(C.SHAPE,'LONGITUDE/LATITUDE(ARC1950)')(SDO_GTYPE, SDO_SRID, SDO -------------------------------------------------------------------------------- cola_c SDO_GEOMETRY(2003, 8199, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(3.00074114, 3.00291482, 6.00067068, 3.00291287, 6.0006723, 5.00307625, 4.0007 1961, 5.00307838, 3.00074114, 3.00291482)) SQL> SQL> -- Transform the entire SHAPE layer and put results in the table SQL> -- named cola_markets_cs_8199, which the procedure will create. SQL> CALL SDO_CS.TRANSFORM_LAYER('COLA_MARKETS_CS','SHAPE','COLA_MARKETS_CS_ 8199',8199); Call completed. SQL> SQL> -- Select all from the old (existing) table. SQL> SELECT * from cola_markets_cs; MKT_ID NAME ---------- -------------------------------- SHAPE(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDINATES) -------------------------------------------------------------------------------- 1 cola_a SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(1, 1, 5, 1, 5, 7, 1, 7, 1, 1)) 2 cola_b SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(5, 1, 8, 1, 8, 6, 5, 7, 5, 1)) 3 cola_c MKT_ID NAME ---------- -------------------------------- SHAPE(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDINATES) -------------------------------------------------------------------------------- SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(3, 3, 6, 3, 6, 5, 4, 5, 3, 3)) 4 cola_d SDO_GEOMETRY(2003, 8307, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(10, 9, 11, 9, 11, 10, 10, 10, 10, 9)) Example of Coordinate System Transformation 6-74 Oracle Spatial Developer's Guide SQL> SQL> -- Select all from the new (layer transformed) table. SQL> SELECT * from cola_markets_cs_8199; SDO_ROWID ------------------ GEOMETRY(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDINATES) -------------------------------------------------------------------------------- AAABZzAABAAAOa6AAA SDO_GEOMETRY(2003, 8199, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(1.00078604, 1.00274579, 5.00069354, 1.00274488, 5.0006986, 7.00323528, 1.0007 9179, 7.00324162, 1.00078604, 1.00274579)) AAABZzAABAAAOa6AAB SDO_GEOMETRY(2003, 8199, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(5.00069354, 1.00274488, 8.00062191, 1.00274427, 8.00062522, 6.00315345, 5.000 6986, 7.00323528, 5.00069354, 1.00274488)) SDO_ROWID ------------------ GEOMETRY(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDINATES) -------------------------------------------------------------------------------- AAABZzAABAAAOa6AAC SDO_GEOMETRY(2003, 8199, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(3.00074114, 3.00291482, 6.00067068, 3.00291287, 6.0006723, 5.00307625, 4.0007 1961, 5.00307838, 3.00074114, 3.00291482)) AAABZzAABAAAOa6AAD SDO_GEOMETRY(2003, 8199, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARR AY(10.0005802, 9.00337775, 11.0005553, 9.00337621, 11.0005569, 10.0034478, 10.00 SDO_ROWID ------------------ GEOMETRY(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDINATES) -------------------------------------------------------------------------------- 05819, 10.0034495, 10.0005802, 9.00337775)) SQL> SQL> -- Show metadata for the new (layer transformed) table. SQL> DESCRIBE cola_markets_cs_8199; Name Null? Type ----------------------------------------- -------- ---------------------------- SDO_ROWID ROWID GEOMETRY SDO_GEOMETRY SQL> SQL> -- Use a geodetic MBR with SDO_FILTER SQL> SELECT c.name FROM cola_markets_cs c WHERE 2 SDO_FILTER(c.shape, 3 SDO_GEOMETRY( 4 2003, 5 8307, -- SRID for WGS 84 longitude/latitude 6 NULL, 7 SDO_ELEM_INFO_ARRAY(1,1003,3), 8 SDO_ORDINATE_ARRAY(6,5, 10,10)) 9 ) = 'TRUE'; Example of Coordinate System Transformation Coordinate Systems (Spatial Reference Systems) 6-75 NAME -------------------------------- cola_c cola_b cola_d Example of Coordinate System Transformation 6-76 Oracle Spatial Developer's Guide 7 Linear Referencing System 7-1 7 Linear Referencing System Linear referencing is a natural and convenient means to associate attributes or events to locations or portions of a linear feature. It has been widely used in transportation applications (such as for highways, railroads, and transit routes) and utilities applications (such as for gas and oil pipelines). The major advantage of linear referencing is its capability of locating attributes and events along a linear feature with only one parameter (usually known as measure) instead of two (such as longitude/latitude or x/y in Cartesian space). Sections of a linear feature can be referenced and created dynamically by indicating the start and end locations along the feature without explicitly storing them. The linear referencing system (LRS) application programming interface (API) in Oracle Spatial provides server-side LRS capabilities at the cartographic level. The linear measure information is directly integrated into the Oracle Spatial geometry structure. The Oracle Spatial LRS API provides support for dynamic segmentation, and it serves as a groundwork for third-party or middle-tier application development for virtually any linear referencing methods and models in any coordinate system. For an example of LRS, see Section 7.7. However, you may want to read the rest of this chapter first, to understand the concepts that the example illustrates. For reference information about LRS functions and procedures, see Chapter 25. This chapter contains the following major sections: ■ Section 7.1, "Terms and Concepts" ■ Section 7.2, "LRS Data Model" ■ Section 7.3, "Indexing of LRS Data" ■ Section 7.4, "3D Formats of LRS Functions" ■ Section 7.5, "LRS Operations" ■ Section 7.6, "Tolerance Values with LRS Functions" ■ Section 7.7, "Example of LRS Functions" 7.1 Terms and Concepts This section explains important terms and concepts related to linear referencing support in Oracle Spatial. 7.1.1 Geometric Segments (LRS Segments) Geometric segments are basic LRS elements in Oracle Spatial. A geometric segment can be any of the following: Terms and Concepts 7-2 Oracle Spatial Developer's Guide ■ Line string: an ordered, nonbranching, and continuous geometry (for example, a simple road) ■ Multiline string: nonconnected line strings (for example, a highway with a gap caused by a lake or a bypass road) ■ Polygon (for example, a racetrack or a scenic tour route that starts and ends at the same point) A geometric segment must contain at least start and end measures for its start and end points. Measures of points of interest (such as highway exits) on the geometric segments can also be assigned. These measures are either assigned by users or derived from existing geometric segments. Figure 7–1 shows a geometric segment with four line segments and one arc. Points on the geometric segment are represented by triplets (x, y, m), where x and y describe the location and m denotes the measure (with each measure value underlined in Figure 7–1). Figure 7–1 Geometric Segment 7.1.2 Shape Points Shape points are points that are specified when an LRS segment is constructed, and that are assigned measure information. In Oracle Spatial, a line segment is represented by its start and end points, and an arc is represented by three points: start, middle, and end points of the arc. You must specify these points as shape points, but you can also specify other points as shape points if you need measure information stored for these points (for example, an exit in the middle of a straight part of the highway). Thus, shape points can serve one or both of the following purposes: to indicate the direction of the segment (for example, a turn or curve), and to identify a point of interest for which measure information is to be stored. Shape points might not directly relate to mileposts or reference posts in LRS; they are used as internal reference points. The measure information of shape points is automatically populated when you define the LRS segment using the SDO_ LRS.DEFINE_GEOM_SEGMENT procedure, which is described in Chapter 25. 7.1.3 Direction of a Geometric Segment The direction of a geometric segment is indicated from the start point of the geometric segment to the end point. The direction is determined by the order of the vertices (from start point to end point) in the geometry definition. Measures of points on a Segment Direction Line Segments (15, 5, 11.180) (30, 10, 26.991) Arc (40, 5, 38.171) (50, 10, 53.879) Start Point (5, 10, 0) End Point (55, 15, 60.950) Terms and Concepts Linear Referencing System 7-3 geometric segment always either increase or decrease along the direction of the geometric segment. 7.1.4 Measure (Linear Measure) The measure of a point along a geometric segment is the linear distance (in the measure dimension) to the point measured from the start point (for increasing values) or end point (for decreasing values) of the geometric segment. The measure information does not necessarily have to be of the same scale as the distance. However, the linear mapping relationship between measure and distance is always preserved. Some LRS functions use offset instead of measure to represent measured distance along linear features. Although some other linear referencing systems might use offset to mean what the Oracle Spatial LRS refers to as measure, offset has a different meaning in Oracle Spatial from measure, as explained in Section 7.1.5. 7.1.5 Offset The offset of a point along a geometric segment is the perpendicular distance between the point and the geometric segment. Offsets are positive if the points are on the left side along the segment direction and are negative if they are on the right side. Points are on a geometric segment if their offsets to the segment are zero. The unit of measurement for an offset is the same as for the coordinate system associated with the geometric segment. For geodetic data, the default unit of measurement is meters. Figure 7–2 shows how a point can be located along a geometric segment with measure and offset information. By assigning an offset together with a measure, it is possible to locate not only points that are on the geometric segment, but also points that are perpendicular to the geometric segment. Figure 7–2 Describing a Point Along a Segment with a Measure and an Offset 7.1.6 Measure Populating Any unassigned measures of a geometric segment are automatically populated based upon their distance distribution. This is done before any LRS operations for geometric segments with unknown measures (NULL in Oracle Spatial). The resulting geometric segments from any LRS operations return the measure information associated with geometric segments. The measure of a point on the geometric segment can be obtained based upon a linear mapping relationship between its previous and next known measures or locations. See the algorithm representation in Figure 7–3 and the example in Figure 7–4. Segment Direction Start Point End Point Ms Me Mp Positive Offset Negative Offset Offset Value Point to Be Located Measure Terms and Concepts 7-4 Oracle Spatial Developer's Guide Figure 7–3 Measures, Distances, and Their Mapping Relationship Figure 7–4 Measure Populating of a Geometric Segment Measures are evenly spaced between assigned measures. However, the assigned measures for points of interest on a geometric segment do not need to be evenly spaced. This could eliminate the problem of error accumulation and account for inaccuracy of data source. Moreover, the assigned measures do not even need to reflect actual distances (for example, they can reflect estimated driving time); they can be any valid values within the measure range. Figure 7–5 shows the measure population that results when assigned measure values are not proportional and reflect widely varying gaps. Figure 7–5 Measure Populating with Disproportional Assigned Measures In all cases, measure populating is done in an incremental fashion along the segment direction. This improves the performance of current and subsequent LRS operations. Mprev = 20 Mp = 60 Mnext = 20 Measure Pprev(0, 0) Pnext(100, 0) Distance P(50, 0) PprevP = 50 PprevPnext = 100 (Mnext - Mprev) + Mprev Mp = PprevP PprevPnext 0 60 90 120 12090600 Assigned Measures Populated Measures Before Measure Populating After Measure Populating 15 30 45 70 80 100 110 0 88 97 100 10097880 Assigned Measures Populated Measures Before Measure Populating After Measure Populating 22 44 66 91 94 98 99 Terms and Concepts Linear Referencing System 7-5 7.1.7 Measure Range of a Geometric Segment The start and end measures of a geometric segment define the linear measure range of the geometric segment. Any valid LRS measures of a geometric segment must fall within its linear measure range. 7.1.8 Projection The projection of a point along a geometric segment is the point on the geometric segment with the minimum distance to the specified point. The measure information of the resulting point is also returned in the point geometry. 7.1.9 LRS Point LRS points are points with linear measure information along a geometric segment. A valid LRS point is a point geometry with measure information. All LRS point data must be stored in the SDO_ELEM_INFO_ARRAY and SDO_ ORDINATE_ARRAY, and cannot be stored in the SDO_POINT field in the SDO_ GEOMETRY definition of the point. 7.1.10 Linear Features Linear features are any spatial objects that can be treated as a logical set of linear segments. Examples of linear features are highways in transportation applications and pipelines in utility industry applications. The relationship of linear features, geometric segments, and LRS points is shown in Figure 7–6, where a single linear feature consists of three geometric segments, and three LRS points are shown on the first segment. Figure 7–6 Linear Feature, Geometric Segments, and LRS Points 7.1.11 Measures with Multiline Strings and Polygons with Holes With a multiline string or polygon with hole LRS geometry, the SDO_LRS.DEFINE_ GEOM_SEGMENT procedure and SDO_LRS.CONVERT_TO_LRS_GEOM function by default assign the same measure value to the end point of one segment and the start point (separated by a gap) of the next segment, although you can later assign different measure values to points. Thus, by default there will duplicate measure values in different segments for such geometries. In such cases, LRS subprograms use the first point with a specified measure, except when doing so would result in an invalid geometry. For example, assume that in a multiline string LRS geometry, the first segment is from measures 0 through 100 and the second segment is from measures 100 through 150. If you use the SDO_LRS.LOCATE_PT function to find the point at measure 100, the Geometric Segment 1 Geometric Segment 2 Geometric Segment 3 LRS Points Direction Direction Direction M1 s M1 eM2 sM2 e M3 eM3 s Linear Feature LRS Data Model 7-6 Oracle Spatial Developer's Guide returned point will be at measure 100 in the first segment. If you use the SDO_ LRS.CLIP_GEOM_SEGMENT, SDO_LRS.DYNAMIC_SEGMENT, or SDO_ LRS.OFFSET_GEOM_SEGMENT function to return the geometry object between measures 75 and 125, the result is a multiline string geometry consisting of two segments. If you use the same function to return the geometry object between measures 100 and 125, the point at measure 100 in the first segment is ignored, and the result is a line string along the second segment from measures 100 through 125. 7.2 LRS Data Model The Oracle Spatial LRS data model incorporates measure information into its geometry representation at the point level. The measure information is directly integrated into the Oracle Spatial model. To accomplish this, an additional measure dimension must be added to the Oracle Spatial metadata. Oracle Spatial LRS support affects the Spatial metadata and data (the geometries). Example 7–1 shows how a measure dimension can be added to two-dimensional geometries in the Spatial metadata. The measure dimension must be the last element of the SDO_DIM_ARRAY in a spatial object definition (shown in bold in Example 7–1). Example 7–1 Including LRS Measure Dimension in Spatial Metadata INSERT INTO user_sdo_geom_metadata (TABLE_NAME, COLUMN_NAME, DIMINFO, SRID) VALUES( 'LRS_ROUTES', 'GEOMETRY', SDO_DIM_ARRAY ( SDO_DIM_ELEMENT('X', 0, 20, 0.005), SDO_DIM_ELEMENT('Y', 0, 20, 0.005), SDO_DIM_ELEMENT('M', 0, 100, 0.005)), NULL); After adding the new measure dimension, geometries with measure information such as geometric segments and LRS points can be represented. An example of creating a geometric segment with three line segments is shown in Figure 7–7. Figure 7–7 Creating a Geometric Segment In Figure 7–7, the geometric segment has the following definition (with measure values underlined): SDO_GEOMETRY(3302, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,2,1), SDO_ORDINATE_ARRAY(5,10,0, 20,5,NULL, 35,10,NULL, 55,10,100)) Start Measure End Measure Start Point End Point (55, 10, 100)(5, 10, 0) (35, 10, NULL) (20, 5, NULL) 3D Formats of LRS Functions Linear Referencing System 7-7 Whenever a geometric segment is defined, its start and end measures must be defined or derived from some existing geometric segment. The unsigned measures of all shape points on a geometric segment will be automatically populated. The SDO_GTYPE of any point geometry used with an LRS function must be 3301. 7.3 Indexing of LRS Data If LRS data has four dimensions (three plus the M dimension) and if you need to index all three non-measure dimensions, you must use a spatial R-tree index to index the data, and you must specify PARAMETERS('sdo_indx_dims=3') in the CREATE INDEX statement to ensure that the first three dimensions are indexed. Note, however, that if you specify an sdo_indx_dims value of 3 or higher, only those operators listed in Section 1.11 as considering all three dimensions can be used on the indexed geometries; the other operators described in Chapter 19 cannot be used. (The default value for the sdo_indx_dims keyword is 2, which would cause only the first two dimensions to be indexed.) For example, if the dimensions are X, Y, Z, and M, specify sdo_indx_dims=3 to index the X, Y, and Z dimensions, but not the measure (M) dimension. Do not include the measure dimension in a spatial index, because this causes additional processing overhead and produces no benefit. Information about the CREATE INDEX statement and its parameters and keywords is in Chapter 18. 7.4 3D Formats of LRS Functions Most LRS functions have formats that end in _3D: for example, DEFINE_GEOM_ SEGMENT_3D, CLIP_GEOM_SEGMENT_3D, FIND_MEASURE_3D, and LOCATE_ PT_3D. If a function has a 3D format, it is identified in the Usage Notes for the function in Chapter 25. The 3D formats are supported only for line string and multiline string geometries. The 3D formats should be used only when the geometry object has four dimensions and the fourth dimension is the measure (for example, X, Y, Z, and M), and only when you want the function to consider the first three dimensions (for example, X, Y, and Z). If the standard format of a function (that is, without the _3D) is used on a geometry with four dimensions, the function considers only the first two dimensions (for example, X and Y). For example, the following format considers the X, Y, and Z dimensions of the specified GEOM object in performing the clip operation: SELECT SDO_LRS.CLIP_GEOM_SEGMENT_3D(a.geom, m.diminfo, 5, 10) FROM routes r, user_sdo_geom_metadata m WHERE m.table_name = 'ROUTES' AND m.column_name = 'GEOM' AND r.route_id = 1; However, the following format considers only the X and Y dimensions, and ignores the Z dimension, of the specified GEOM object in performing the clip operation: SELECT SDO_LRS.CLIP_GEOM_SEGMENT(a.geom, m.diminfo, 5, 10) FROM routes r, user_sdo_geom_metadata m WHERE m.table_name = 'ROUTES' AND m.column_name = 'GEOM' AND r.route_id = 1; The parameters for the standard and 3D formats of any function are the same, and the Usage Notes apply to both formats. The 3D formats are not supported with the following: LRS Operations 7-8 Oracle Spatial Developer's Guide ■ Geodetic data ■ Polygons, arcs, or circles 7.5 LRS Operations This section describes several linear referencing operations supported by the Oracle Spatial LRS API. 7.5.1 Defining a Geometric Segment There are two ways to create a geometric segment with measure information: ■ Construct a geometric segment and assign measures explicitly. ■ Define a geometric segment with specified start and end, and any other measures, in an ascending or descending order. Measures of shape points with unknown (unassigned) measures (null values) in the geometric segment will be automatically populated according to their locations and distance distribution. Figure 7–8 shows different ways of defining a geometric segment: Figure 7–8 Defining a Geometric Segment An LRS segment must be defined (or must already exist) before any LRS operations can proceed. That is, the start, end, and any other assigned measures must be present to derive the location from a specified measure. The measure information of intermediate shape points will automatically be populated if measure values are not assigned. 7.5.2 Redefining a Geometric Segment You can redefine a geometric segment to replace the existing measures of all shape points between the start and end point with automatically calculated measures. Redefining a segment can be useful if errors have been made in one or more explicit Start Point End Point (55, 10, NULL)(5, 10, NULL) (35, 10, NULL) (20, 5, NULL) a. Geometric Segment with No Measures Assigned Start Point End Point (55, 10, 100)(5, 10, 0) (35, 10, NULL) (20, 5, NULL) Start Measure End Measure b. Geometric Segment with Start and End Measures Start Point End Point (55, 10, 100)(5, 10, 0) (35, 10, 61.257) (20, 5, 30.628) c. Populating Measures of Shape Points in a Geometric Segment LRS Operations Linear Referencing System 7-9 measure assignments, and you want to start over with proportionally assigned measures. Figure 7–9 shows the redefinition of a segment where the existing (before) assigned measure values are not proportional and reflect widely varying gaps. Figure 7–9 Redefining a Geometric Segment After the segment redefinition in Figure 7–9, the populated measures reflect proportional distances along the segment. 7.5.3 Clipping a Geometric Segment You can clip a geometric segment to create a new geometric segment out of an existing geometric segment, as shown in Figure 7–10, part a. Figure 7–10 Clipping, Splitting, and Concatenating Geometric Segments In Figure 7–10, part a, a segment is created from part of a larger segment. The new segment has its own start and end points, and the direction is the same as in the original larger segment. 7.5.4 Splitting a Geometric Segment You can create two new geometric segments by splitting a geometric segment, as shown in Figure 7–10, part b. The direction of each new segment is the same as in the original segment. Assigned Measures Populated Measures Before Segment Redefinition After Segment Redefinition 10097880 22 44 66 91 94 98 99 100 7040 0 10 20 30 50 60 80 90 Assigned Measures Populated Measures Start Point End Point Start Point End Point Segment Direction Segment Direction Segment 1 Segment 1 Segment 2 Segment 2 Ms Me Ms Mea. Segment Clipping b. Segment Splitting c. Segment Concatenation LRS Operations 7-10 Oracle Spatial Developer's Guide 7.5.5 Concatenating Geometric Segments You can create a new geometric segment by concatenating two geometric segments, as shown in Figure 7–10, part c. The geometric segments do not need to be spatially connected, although they are connected in the illustration in Figure 7–10, part c. (If the segments are not spatially connected, the concatenated result is a multiline string.) The measures of the second geometric segment are shifted so that the end measure of the first segment is the same as the start measure of the second segment. The direction of the segment resulting from the concatenation is the same as in the two original segments. Measure assignments for the clipping, splitting, and concatenating operations in Figure 7–10 are shown in Figure 7–11. Measure information and segment direction are preserved in a consistent manner. The assignment is done automatically when the operations have completed. Figure 7–11 Measure Assignment in Geometric Segment Operations The direction of the geometric segment resulting from concatenation is always the direction of the first segment (geom_segment1 in the call to the SDO_ LRS.CONCATENATE_GEOM_SEGMENTS function), as shown in Figure 7–12. Note: In Figure 7–10 and several figures that follow, small gaps between segments are used in illustrations of segment splitting and concatenation. Each gap simply reinforces the fact that two different segments are involved. However, the two segments (such as segment 1 and segment 2 in Figure 7–10, parts b and c) are actually connected. The tolerance (see Section 1.5.5) is considered in determining whether or not segments are connected. M=0 M=100 M=25 M=70 M=25 M=70M=0 M=100 M=100 M=0 M=50 M=50Segment 1 Segment 2 M=0 M=50 M=30 M=80 Segment 1 Segment 2 a. Segment Splitting b. Segment Clipping M=0 M=100 M=50 Second Segment Measure Shifted By 20 Continuous Measures for Segment Concatenation c. Segment Concatenation LRS Operations Linear Referencing System 7-11 Figure 7–12 Segment Direction with Concatenation In addition to explicitly concatenating two connected segments using the SDO_ LRS.CONCATENATE_GEOM_SEGMENTS function, you can perform aggregate concatenation: that is, you can concatenate all connected geometric segments in a column (layer) using the SDO_AGGR_LRS_CONCAT spatial aggregate function. (See the description and example of the SDO_AGGR_LRS_CONCAT spatial aggregate function in Chapter 20.) 7.5.6 Scaling a Geometric Segment You can create a new geometric segment by performing a linear scaling operation on a geometric segment. Figure 7–13 shows the mapping relationship for geometric segment scaling. Figure 7–13 Scaling a Geometric Segment In general, scaling a geometric segment only involves rearranging measures of the newly created geometric segment. However, if the scaling factor is negative, the order of the shape points needs to be reversed so that measures will increase along the geometric segment’s direction (which is defined by the order of the shape points). A scale operation can perform any combination of the following operations: ■ Translating (shifting) measure information. (For example, add the same value to Ms and Me to get M’s and M’e.) ■ Reversing measure information. (Let M’s = Me, M’e = Ms, and Mshift = 0.) ■ Performing simple scaling of measure information. (Let Mshift = 0.) Directions of Segments Concatenate Direction of Resulting Segment (Always Same as First Segment) geom_segment1 geom_segment2 Mshift Shift Measure M's M' M'e Ms M Me Segment Direction Start Point End Point (New Start Measure) (New End Measure) Linear Mapping Relationship M' = (M - Ms) x (M'e - M's) (Me - Ms) + M's + Mshift Scaling Factor LRS Operations 7-12 Oracle Spatial Developer's Guide For examples of these operations, see the Usage Notes and Examples for theSDO_ LRS.SCALE_GEOM_SEGMENT, SDO_LRS.TRANSLATE_MEASURE, SDO_ LRS.REVERSE_GEOMETRY, and SDO_LRS.REDEFINE_GEOM_SEGMENT subprograms in Chapter 25. 7.5.7 Offsetting a Geometric Segment You can create a new geometric segment by performing an offsetting operation on a geometric segment. Figure 7–14 shows the mapping relationship for geometric segment offsetting. Figure 7–14 Offsetting a Geometric Segment In the offsetting operation shown in Figure 7–14, the resulting geometric segment is offset by 5 units from the specified start and end measures of the original segment. For more information, see the Usage Notes and Examples for the SDO_LRS.OFFSET_ GEOM_SEGMENT function in Chapter 25. 7.5.8 Locating a Point on a Geometric Segment You can find the position of a point described by a measure and an offset on a geometric segment (see Figure 7–15). Figure 7–15 Locating a Point Along a Segment with a Measure and an Offset There is always a unique location with a specific measure on a geometric segment. Ambiguity arises when offsets are given and the points described by the measures fall on shape points of the geometric segment (see Figure 7–16). Direction of the Segments Resulting Segment Positive Offset (for example, 5) Negative Offset (for example, -5) Start Measure End Measure Segment Direction Start Point End Point Positive Offset Negative Offset Offset (Positive if to left along segment direction; negative if to right along segment direction.)Point to Be Located Measure Projection Point LRS Operations Linear Referencing System 7-13 Figure 7–16 Ambiguity in Location Referencing with Offsets As shown in Figure 7–16, an offset arc of a shape point on a geometric segment is an arc on which all points have the same minimum distance to the shape point. As a result, all points on the offset arc are represented by the same (measure, offset) pair. To resolve this one-to-many mapping problem, the middle point on the offset arc is returned. 7.5.9 Projecting a Point onto a Geometric Segment You can find the projection point of a point with respect to a geometric segment. The point to be projected can be on or off the segment. If the point is on the segment, the point and its projection point are the same. Projection is a reverse operation of the point-locating operation shown in Figure 7–15. Similar to a point-locating operation, all points on the offset arc of a shape point will have the same projection point (that is, the shape point itself), measure, and offset (see Figure 7–16). If there are multiple projection points for a point, the first one from the start point is returned (Projection Point 1 in both illustrations in Figure 7–17). Figure 7–17 Multiple Projection Points (5, 10, 0) (35, 10, 61.257) (55, 10, 100) o oo Shape Point on the Geometric Segment Many-to-One Mapping Offset ArcMiddle Point m (5, 10, 0) (35, 10, 61.257) (55, 10, 100) P (m, o) One-to-One Mapping om (20, 5, 30.628) (20, 5, 30.628) Segment Direction P Segment Direction Projection Point 2 Point to Be Projected Projection Point 1 Arc Segment Direction Point to Be Projected P Projection Point 1 LRS Operations 7-14 Oracle Spatial Developer's Guide 7.5.10 Converting LRS Geometries You can convert geometries from standard line string format to LRS format, and the reverse. The main use of conversion functions will probably occur if you have a large amount of existing line string data, in which case conversion is a convenient alternative to creating all of the LRS segments manually. However, if you need to convert LRS segments to standard line strings for certain applications, that capability is provided also. Functions are provided to convert: ■ Individual line strings or points For conversion from standard format to LRS format, a measure dimension (named M by default) is added, and measure information is provided for each point. For conversion from LRS format to standard format, the measure dimension and information are removed. In both cases, the dimensional information (DIMINFO) metadata in the USER_SDO_GEOM_METADATA view is not affected. ■ Layers (all geometries in a column) For conversion from standard format to LRS format, a measure dimension (named M by default) is added, but no measure information is provided for each point. For conversion from LRS format to standard format, the measure dimension and information are removed. In both cases, the dimensional information (DIMINFO) metadata in the USER_SDO_GEOM_METADATA view is modified as needed. ■ Dimensional information (DIMINFO) The dimensional information (DIMINFO) metadata in the USER_SDO_GEOM_ METADATA view is modified as needed. For example, converting a standard dimensional array with X and Y dimensions (SDO_DIM_ELEMENT) to an LRS dimensional array causes an M dimension (SDO_DIM_ELEMENT) to be added. Figure 7–18 shows the addition of measure information when a standard line string is converted to an LRS line string (using the SDO_LRS.CONVERT_TO_LRS_GEOM function). The measure dimension values are underlined in Figure 7–18. Figure 7–18 Conversion from Standard to LRS Line String For conversions of point geometries, the SDO_POINT attribute (described in Section 2.2.3) in the returned geometry is affected as follows: ■ If a standard point is converted to an LRS point, the SDO_POINT attribute information in the input geometry is used to set the SDO_ELEM_INFO and SDO_ ORDINATES attributes (described in Section 2.2.4 and Section 2.2.5) in the resulting geometry, and the SDO_POINT attribute in the resulting geometry is set to null. ■ If an LRS point is converted to a standard point, the information in the SDO_ ELEM_INFO and SDO_ORDINATES attributes (described in Section 2.2.4 and Section 2.2.5) in the input geometry is used to set the SDO_POINT attribute (0, 0) (10, 0) (20, 0) (0, 0, 0) (10, 0, 10) (20, 0, 20) Standard Line String LRS Line String (After Conversion) Example of LRS Functions Linear Referencing System 7-15 information in the resulting geometry, and the SDO_ELEM_INFO and SDO_ ORDINATES attributes in the resulting geometry are set to null. The conversion functions are listed in Table 25–3 in Chapter 25. See also the reference information in Chapter 25 about each conversion function. 7.6 Tolerance Values with LRS Functions Many LRS functions require that you specify a tolerance value or one or more dimensional arrays. Thus, you can control whether to specify a single tolerance value for all non-measure dimensions or to use the tolerance associated with each non-measure dimension in the dimensional array or arrays. The tolerance is applied only to the geometry portion of the data, not to the measure dimension. The tolerance value for geodetic data is in meters, and for non-geodetic data it is in the unit of measurement associated with the data. (For a detailed discussion of tolerance, see Section 1.5.5.) Be sure that the tolerance value used is appropriate to the data and your purpose. If the results of LRS functions seem imprecise or incorrect, you may need to specify a smaller tolerance value. For clip operations (see Section 7.5.3) and offset operations (see Section 7.5.7), if the returned segment has any shape points within the tolerance value of the input geometric segment from what would otherwise be the start point or end point of the returned segment, the shape point is used as the start point or end point of the returned segment. This is done to ensure that the resulting geometry does not contain any redundant vertices, which would cause the geometry to be invalid. For example, assume that the tolerance associated with the geometric segment (non-geodetic data) in Figure 7–19 is 0.5. Figure 7–19 Segment for Clip Operation Affected by Tolerance If you request a clip operation to return the segment between measure values 0 (the start point) and 61.5 in Figure 7–19, and if the distance between the points associated with measure values 61.5 and 61.257 is less than the 0.5 tolerance value, the end point of the returned segment is (35, 10, 61.257). 7.7 Example of LRS Functions This section presents a simplified example that uses LRS functions. It refers to concepts that are explained in this chapter and uses functions documented in Chapter 25. This example uses the road that is illustrated in Figure 7–20. Start Point End Point (55, 10, 100)(5, 10, 0) (35, 10, 61.257) (20, 5, 30.628) Example of LRS Functions 7-16 Oracle Spatial Developer's Guide Figure 7–20 Simplified LRS Example: Highway In Figure 7–20, the highway (Route 1) starts at point 2,2 and ends at point 5,14, follows the path shown, and has six entrance-exit points (Exit 1 through Exit 6). For simplicity, each unit on the graph represents one unit of measure, and thus the measure from start to end is 27 (the segment from Exit 5 to Exit 6 being the hypotenuse of a 3-4-5 right triangle). Each row in Table 7–1 lists an actual highway-related feature and the LRS feature that corresponds to it or that can be used to represent it. Example 7–2 does the following: ■ Creates a table to hold the segment depicted in Figure 7–20 ■ Inserts the definition of the highway depicted in Figure 7–20 into the table Table 7–1 Highway Features and LRS Counterparts Highway Feature LRS Feature Named route, road, or street LRS segment, or linear feature (logical set of segments) Mile or kilometer marker Measure Accident reporting and location tracking SDO_LRS.LOCATE_PT function Construction zone (portion of a road) SDO_LRS.CLIP_GEOM_SEGMENT function Road extension (adding at the beginning or end) or combination (designating or renaming two roads that meet as one road) SDO_LRS.CONCATENATE_GEOM_ SEGMENTS function Road reconstruction or splitting (resulting in two named roads from one named road) SDO_LRS.SPLIT_GEOM_SEGMENT procedure Finding the closest point on the road to a point off the road (such as a building) SDO_LRS.PROJECT_PT function Guard rail or fence alongside a road SDO_LRS.OFFSET_GEOM_SEGMENT function 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Route1 (start) Route1 (end) Exit 1 Exit 2 Exit 3 Exit 4 Exit 5 Exit 6 Segment Direction Example of LRS Functions Linear Referencing System 7-17 ■ Inserts the necessary metadata into the USER_SDO_GEOM_METADATA view ■ Uses PL/SQL and SQL statements to define the segment and perform operations on it Example 7–3 includes the output of the SELECT statements in Example 7–2. Example 7–2 Simplified Example: Highway -- Create a table for routes (highways). CREATE TABLE lrs_routes ( route_id NUMBER PRIMARY KEY, route_name VARCHAR2(32), route_geometry SDO_GEOMETRY); -- Populate table with just one route for this example. INSERT INTO lrs_routes VALUES( 1, 'Route1', SDO_GEOMETRY( 3302, -- line string, 3 dimensions: X,Y,M NULL, NULL, SDO_ELEM_INFO_ARRAY(1,2,1), -- one line string, straight segments SDO_ORDINATE_ARRAY( 2,2,0, -- Start point - Exit1; 0 is measure from start. 2,4,2, -- Exit2; 2 is measure from start. 8,4,8, -- Exit3; 8 is measure from start. 12,4,12, -- Exit4; 12 is measure from start. 12,10,NULL, -- Not an exit; measure automatically calculated and filled. 8,10,22, -- Exit5; 22 is measure from start. 5,14,27) -- End point (Exit6); 27 is measure from start. ) ); -- Update the Spatial metadata. INSERT INTO user_sdo_geom_metadata (TABLE_NAME, COLUMN_NAME, DIMINFO, SRID) VALUES ( 'lrs_routes', 'route_geometry', SDO_DIM_ARRAY( -- 20X20 grid SDO_DIM_ELEMENT('X', 0, 20, 0.005), SDO_DIM_ELEMENT('Y', 0, 20, 0.005), SDO_DIM_ELEMENT('M', 0, 20, 0.005) -- Measure dimension ), NULL -- SRID ); -- Create the spatial index. CREATE INDEX lrs_routes_idx ON lrs_routes(route_geometry) INDEXTYPE IS MDSYS.SPATIAL_INDEX; -- Test the LRS procedures. DECLARE geom_segment SDO_GEOMETRY; line_string SDO_GEOMETRY; dim_array SDO_DIM_ARRAY; Example of LRS Functions 7-18 Oracle Spatial Developer's Guide result_geom_1 SDO_GEOMETRY; result_geom_2 SDO_GEOMETRY; result_geom_3 SDO_GEOMETRY; BEGIN SELECT a.route_geometry into geom_segment FROM lrs_routes a WHERE a.route_name = 'Route1'; SELECT m.diminfo into dim_array from user_sdo_geom_metadata m WHERE m.table_name = 'LRS_ROUTES' AND m.column_name = 'ROUTE_GEOMETRY'; -- Define the LRS segment for Route1. This will populate any null measures. -- No need to specify start and end measures, because they are already defined -- in the geometry. SDO_LRS.DEFINE_GEOM_SEGMENT (geom_segment, dim_array); SELECT a.route_geometry INTO line_string FROM lrs_routes a WHERE a.route_name = 'Route1'; -- Split Route1 into two segments. SDO_LRS.SPLIT_GEOM_SEGMENT(line_string,dim_array,5,result_geom_1,result_geom_2); -- Concatenate the segments that were just split. result_geom_3 := SDO_LRS.CONCATENATE_GEOM_SEGMENTS(result_geom_1, dim_array, result_geom_2, dim_array); -- Update and insert geometries into table, to display later. UPDATE lrs_routes a SET a.route_geometry = geom_segment WHERE a.route_id = 1; INSERT INTO lrs_routes VALUES( 11, 'result_geom_1', result_geom_1 ); INSERT INTO lrs_routes VALUES( 12, 'result_geom_2', result_geom_2 ); INSERT INTO lrs_routes VALUES( 13, 'result_geom_3', result_geom_3 ); END; / -- First, display the data in the LRS table. SELECT route_id, route_name, route_geometry FROM lrs_routes; -- Are result_geom_1 and result_geom2 connected? SELECT SDO_LRS.CONNECTED_GEOM_SEGMENTS(a.route_geometry, b.route_geometry, 0.005) FROM lrs_routes a, lrs_routes b WHERE a.route_id = 11 AND b.route_id = 12; -- Is the Route1 segment valid? Example of LRS Functions Linear Referencing System 7-19 SELECT SDO_LRS.VALID_GEOM_SEGMENT(route_geometry) FROM lrs_routes WHERE route_id = 1; -- Is 50 a valid measure on Route1? (Should return FALSE; highest Route1 measure is 27.) SELECT SDO_LRS.VALID_MEASURE(route_geometry, 50) FROM lrs_routes WHERE route_id = 1; -- Is the Route1 segment defined? SELECT SDO_LRS.IS_GEOM_SEGMENT_DEFINED(route_geometry) FROM lrs_routes WHERE route_id = 1; -- How long is Route1? SELECT SDO_LRS.GEOM_SEGMENT_LENGTH(route_geometry) FROM lrs_routes WHERE route_id = 1; -- What is the start measure of Route1? SELECT SDO_LRS.GEOM_SEGMENT_START_MEASURE(route_geometry) FROM lrs_routes WHERE route_id = 1; -- What is the end measure of Route1? SELECT SDO_LRS.GEOM_SEGMENT_END_MEASURE(route_geometry) FROM lrs_routes WHERE route_id = 1; -- What is the start point of Route1? SELECT SDO_LRS.GEOM_SEGMENT_START_PT(route_geometry) FROM lrs_routes WHERE route_id = 1; -- What is the end point of Route1? SELECT SDO_LRS.GEOM_SEGMENT_END_PT(route_geometry) FROM lrs_routes WHERE route_id = 1; -- Translate (shift measure values) (+10). -- First, display the original segment; then, translate. SELECT a.route_geometry FROM lrs_routes a WHERE a.route_id = 1; SELECT SDO_LRS.TRANSLATE_MEASURE(a.route_geometry, m.diminfo, 10) FROM lrs_routes a, user_sdo_geom_metadata m WHERE m.table_name = 'LRS_ROUTES' AND m.column_name = 'ROUTE_GEOMETRY' AND a.route_id = 1; -- Redefine geometric segment to "convert" miles to kilometers DECLARE geom_segment SDO_GEOMETRY; dim_array SDO_DIM_ARRAY; BEGIN SELECT a.route_geometry into geom_segment FROM lrs_routes a WHERE a.route_name = 'Route1'; SELECT m.diminfo into dim_array from user_sdo_geom_metadata m WHERE m.table_name = 'LRS_ROUTES' AND m.column_name = 'ROUTE_GEOMETRY'; -- "Convert" mile measures to kilometers (27 * 1.609 = 43.443). SDO_LRS.REDEFINE_GEOM_SEGMENT (geom_segment, dim_array, 0, -- Zero starting measure: LRS segment starts at start of route. 43.443); -- End of LRS segment. 27 miles = 43.443 kilometers. -- Update and insert geometries into table, to display later. Example of LRS Functions 7-20 Oracle Spatial Developer's Guide UPDATE lrs_routes a SET a.route_geometry = geom_segment WHERE a.route_id = 1; END; / -- Display the redefined segment, with all measures "converted." SELECT a.route_geometry FROM lrs_routes a WHERE a.route_id = 1; -- Clip a piece of Route1. SELECT SDO_LRS.CLIP_GEOM_SEGMENT(route_geometry, 5, 10) FROM lrs_routes WHERE route_id = 1; -- Point (9,3,NULL) is off the road; should return (9,4,9). SELECT SDO_LRS.PROJECT_PT(route_geometry, SDO_GEOMETRY(3301, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1, 1), SDO_ORDINATE_ARRAY(9, 3, NULL)) ) FROM lrs_routes WHERE route_id = 1; -- Return the measure of the projected point. SELECT SDO_LRS.GET_MEASURE( SDO_LRS.PROJECT_PT(a.route_geometry, m.diminfo, SDO_GEOMETRY(3301, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1, 1), SDO_ORDINATE_ARRAY(9, 3, NULL)) ), m.diminfo ) FROM lrs_routes a, user_sdo_geom_metadata m WHERE m.table_name = 'LRS_ROUTES' AND m.column_name = 'ROUTE_GEOMETRY' AND a.route_id = 1; -- Is point (9,3,NULL) a valid LRS point? (Should return TRUE.) SELECT SDO_LRS.VALID_LRS_PT( SDO_GEOMETRY(3301, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1, 1), SDO_ORDINATE_ARRAY(9, 3, NULL)), m.diminfo) FROM lrs_routes a, user_sdo_geom_metadata m WHERE m.table_name = 'LRS_ROUTES' AND m.column_name = 'ROUTE_GEOMETRY' AND a.route_id = 1; -- Locate the point on Route1 at measure 9, offset 0. SELECT SDO_LRS.LOCATE_PT(route_geometry, 9, 0) FROM lrs_routes WHERE route_id = 1; Example 7–3 shows the output of the SELECT statements in Example 7–2. Example 7–3 Simplified Example: Output of SELECT Statements SQL> -- First, display the data in the LRS table. SQL> SELECT route_id, route_name, route_geometry FROM lrs_routes; ROUTE_ID ROUTE_NAME ---------- -------------------------------- ROUTE_GEOMETRY(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDIN -------------------------------------------------------------------------------- 1 Route1 SDO_GEOMETRY(3302, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( 2, 2, 0, 2, 4, 2, 8, 4, 8, 12, 4, 12, 12, 10, 18, 8, 10, 22, 5, 14, 27)) 11 result_geom_1 Example of LRS Functions Linear Referencing System 7-21 SDO_GEOMETRY(3302, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( 2, 2, 0, 2, 4, 2, 5, 4, 5)) 12 result_geom_2 ROUTE_ID ROUTE_NAME ---------- -------------------------------- ROUTE_GEOMETRY(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDIN -------------------------------------------------------------------------------- SDO_GEOMETRY(3302, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( 5, 4, 5, 8, 4, 8, 12, 4, 12, 12, 10, 18, 8, 10, 22, 5, 14, 27)) 13 result_geom_3 SDO_GEOMETRY(3302, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( 2, 2, 0, 2, 4, 2, 5, 4, 5, 8, 4, 8, 12, 4, 12, 12, 10, 18, 8, 10, 22, 5, 14, 27) ) SQL> -- Are result_geom_1 and result_geom2 connected? SQL> SELECT SDO_LRS.CONNECTED_GEOM_SEGMENTS(a.route_geometry, 2 b.route_geometry, 0.005) 3 FROM lrs_routes a, lrs_routes b 4 WHERE a.route_id = 11 AND b.route_id = 12; SDO_LRS.CONNECTED_GEOM_SEGMENTS(A.ROUTE_GEOMETRY,B.ROUTE_GEOMETRY,0.005) -------------------------------------------------------------------------------- TRUE SQL> -- Is the Route1 segment valid? SQL> SELECT SDO_LRS.VALID_GEOM_SEGMENT(route_geometry) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.VALID_GEOM_SEGMENT(ROUTE_GEOMETRY) -------------------------------------------------------------------------------- TRUE SQL> -- Is 50 a valid measure on Route1? (Should return FALSE; highest Route1 measure is 27.) SQL> SELECT SDO_LRS.VALID_MEASURE(route_geometry, 50) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.VALID_MEASURE(ROUTE_GEOMETRY,50) -------------------------------------------------------------------------------- FALSE SQL> -- Is the Route1 segment defined? SQL> SELECT SDO_LRS.IS_GEOM_SEGMENT_DEFINED(route_geometry) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.IS_GEOM_SEGMENT_DEFINED(ROUTE_GEOMETRY) -------------------------------------------------------------------------------- TRUE SQL> -- How long is Route1? SQL> SELECT SDO_LRS.GEOM_SEGMENT_LENGTH(route_geometry) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.GEOM_SEGMENT_LENGTH(ROUTE_GEOMETRY) ------------------------------------------- 27 Example of LRS Functions 7-22 Oracle Spatial Developer's Guide SQL> -- What is the start measure of Route1? SQL> SELECT SDO_LRS.GEOM_SEGMENT_START_MEASURE(route_geometry) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.GEOM_SEGMENT_START_MEASURE(ROUTE_GEOMETRY) -------------------------------------------------- 0 SQL> -- What is the end measure of Route1? SQL> SELECT SDO_LRS.GEOM_SEGMENT_END_MEASURE(route_geometry) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.GEOM_SEGMENT_END_MEASURE(ROUTE_GEOMETRY) ------------------------------------------------ 27 SQL> -- What is the start point of Route1? SQL> SELECT SDO_LRS.GEOM_SEGMENT_START_PT(route_geometry) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.GEOM_SEGMENT_START_PT(ROUTE_GEOMETRY)(SDO_GTYPE, SDO_SRID, SDO_POINT(X, -------------------------------------------------------------------------------- SDO_GEOMETRY(3301, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1, 1), SDO_ORDINATE_ARRAY( 2, 2, 0)) SQL> -- What is the end point of Route1? SQL> SELECT SDO_LRS.GEOM_SEGMENT_END_PT(route_geometry) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.GEOM_SEGMENT_END_PT(ROUTE_GEOMETRY)(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, -------------------------------------------------------------------------------- SDO_GEOMETRY(3301, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1, 1), SDO_ORDINATE_ARRAY( 5, 14, 27)) SQL> -- Translate (shift measure values) (+10). SQL> -- First, display the original segment; then, translate. SQL> SELECT a.route_geometry FROM lrs_routes a WHERE a.route_id = 1; ROUTE_GEOMETRY(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDIN -------------------------------------------------------------------------------- SDO_GEOMETRY(3302, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( 2, 2, 0, 2, 4, 2, 8, 4, 8, 12, 4, 12, 12, 10, 18, 8, 10, 22, 5, 14, 27)) SQL> SELECT SDO_LRS.TRANSLATE_MEASURE(a.route_geometry, m.diminfo, 10) 2 FROM lrs_routes a, user_sdo_geom_metadata m 3 WHERE m.table_name = 'LRS_ROUTES' AND m.column_name = 'ROUTE_GEOMETRY' 4 AND a.route_id = 1; SDO_LRS.TRANSLATE_MEASURE(A.ROUTE_GEOMETRY,M.DIMINFO,10)(SDO_GTYPE, SDO_SRID, SD -------------------------------------------------------------------------------- SDO_GEOMETRY(3302, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( 2, 2, 10, 2, 4, 12, 8, 4, 18, 12, 4, 22, 12, 10, 28, 8, 10, 32, 5, 14, 37)) SQL> -- Redefine geometric segment to "convert" miles to kilometers SQL> DECLARE 2 geom_segment SDO_GEOMETRY; 3 dim_array SDO_DIM_ARRAY; 4 5 BEGIN Example of LRS Functions Linear Referencing System 7-23 6 7 SELECT a.route_geometry into geom_segment FROM lrs_routes a 8 WHERE a.route_name = 'Route1'; 9 SELECT m.diminfo into dim_array from 10 user_sdo_geom_metadata m 11 WHERE m.table_name = 'LRS_ROUTES' AND m.column_name = 'ROUTE_GEOMETRY'; 12 13 -- "Convert" mile measures to kilometers (27 * 1.609 = 43.443). 14 SDO_LRS.REDEFINE_GEOM_SEGMENT (geom_segment, 15 dim_array, 16 0, -- Zero starting measure: LRS segment starts at start of route. 17 43.443); -- End of LRS segment. 27 miles = 43.443 kilometers. 18 19 -- Update and insert geometries into table, to display later. 20 UPDATE lrs_routes a SET a.route_geometry = geom_segment 21 WHERE a.route_id = 1; 22 23 END; 24 / PL/SQL procedure successfully completed. SQL> -- Display the redefined segment, with all measures "converted." SQL> SELECT a.route_geometry FROM lrs_routes a WHERE a.route_id = 1; ROUTE_GEOMETRY(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), SDO_ELEM_INFO, SDO_ORDIN -------------------------------------------------------------------------------- SDO_GEOMETRY(3302, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( 2, 2, 0, 2, 4, 3.218, 8, 4, 12.872, 12, 4, 19.308, 12, 10, 28.962, 8, 10, 35.398 , 5, 14, 43.443)) SQL> -- Clip a piece of Route1. SQL> SELECT SDO_LRS.CLIP_GEOM_SEGMENT(route_geometry, 5, 10) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.CLIP_GEOM_SEGMENT(ROUTE_GEOMETRY,5,10)(SDO_GTYPE, SDO_SRID, SDO_POINT(X, -------------------------------------------------------------------------------- SDO_GEOMETRY(3302, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1), SDO_ORDINATE_ARRAY( 5, 4, 5, 8, 4, 8, 10, 4, 10)) SQL> -- Point (9,3,NULL) is off the road; should return (9,4,9). SQL> SELECT SDO_LRS.PROJECT_PT(route_geometry, 2 SDO_GEOMETRY(3301, NULL, NULL, 3 SDO_ELEM_INFO_ARRAY(1, 1, 1), 4 SDO_ORDINATE_ARRAY(9, 3, NULL)) ) 5 FROM lrs_routes WHERE route_id = 1; SDO_LRS.PROJECT_PT(ROUTE_GEOMETRY,SDO_GEOMETRY(3301,NULL,NULL,SDO_EL -------------------------------------------------------------------------------- SDO_GEOMETRY(3301, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1, 1), SDO_ORDINATE_ARRAY( 9, 4, 9)) SQL> -- Return the measure of the projected point. SQL> SELECT SDO_LRS.GET_MEASURE( 2 SDO_LRS.PROJECT_PT(a.route_geometry, m.diminfo, 3 SDO_GEOMETRY(3301, NULL, NULL, 4 SDO_ELEM_INFO_ARRAY(1, 1, 1), 5 SDO_ORDINATE_ARRAY(9, 3, NULL)) ), 6 m.diminfo ) 7 FROM lrs_routes a, user_sdo_geom_metadata m Example of LRS Functions 7-24 Oracle Spatial Developer's Guide 8 WHERE m.table_name = 'LRS_ROUTES' AND m.column_name = 'ROUTE_GEOMETRY' 9 AND a.route_id = 1; SDO_LRS.GET_MEASURE(SDO_LRS.PROJECT_PT(A.ROUTE_GEOMETRY,M.DIMINFO,SDO_GEOM -------------------------------------------------------------------------------- 9 SQL> -- Is point (9,3,NULL) a valid LRS point? (Should return TRUE.) SQL> SELECT SDO_LRS.VALID_LRS_PT( 2 SDO_GEOMETRY(3301, NULL, NULL, 3 SDO_ELEM_INFO_ARRAY(1, 1, 1), 4 SDO_ORDINATE_ARRAY(9, 3, NULL)), 5 m.diminfo) 6 FROM lrs_routes a, user_sdo_geom_metadata m 7 WHERE m.table_name = 'LRS_ROUTES' AND m.column_name = 'ROUTE_GEOMETRY' 8 AND a.route_id = 1; SDO_LRS.VALID_LRS_PT(SDO_GEOMETRY(3301,NULL,NULL,SDO_ELEM_INFO_ARRAY ------------------------------------------------------------------------------ TRUE SQL> -- Locate the point on Route1 at measure 9, offset 0. SQL> SELECT SDO_LRS.LOCATE_PT(route_geometry, 9, 0) 2 FROM lrs_routes WHERE route_id = 1; SDO_LRS.LOCATE_PT(ROUTE_GEOMETRY,9,0)(SDO_GTYPE, SDO_SRID, SDO_POINT(X, Y, Z), S -------------------------------------------------------------------------------- SDO_GEOMETRY(3301, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1, 1), SDO_ORDINATE_ARRAY( 9, 4, 9)) 8 Spatial Analysis and Mining 8-1 8 Spatial Analysis and Mining This chapter describes the Oracle Spatial support for spatial analysis and mining in Oracle Data Mining (ODM) applications. For reference information about spatial analysis and mining functions and procedures in the SDO_SAM package, see Chapter 29. This chapter contains the following major sections: ■ Section 8.1, "Spatial Information and Data Mining Applications" ■ Section 8.2, "Spatial Binning for Detection of Regional Patterns" ■ Section 8.3, "Materializing Spatial Correlation" ■ Section 8.4, "Colocation Mining" ■ Section 8.5, "Spatial Clustering" ■ Section 8.6, "Location Prospecting" 8.1 Spatial Information and Data Mining Applications ODM allows automatic discovery of knowledge from a database. Its techniques include discovering hidden associations between different data attributes, classification of data based on some samples, and clustering to identify intrinsic patterns. Spatial data can be materialized for inclusion in data mining applications. Thus, ODM might enable you to discover that sales prospects with addresses located in specific areas (neighborhoods, cities, or regions) are more likely to watch a particular television program or to respond favorably to a particular advertising solicitation. (The addresses are geocoded into longitude/latitude points and stored in an Oracle Spatial geometry object.) In many applications, data at a specific location is influenced by data in the neighborhood. For example, the value of a house is largely determined by the value of Note: To use the features described in this chapter, you must understand the main concepts and techniques explained in the Oracle Data Mining documentation. Note: SDO_SAM subprograms are supported for two-dimensional geometries only. They are not supported for three-dimensional geometries. Spatial Information and Data Mining Applications 8-2 Oracle Spatial Developer's Guide other houses in the neighborhood. This phenomenon is called spatial correlation (or, neighborhood influence), and is discussed further in Section 8.3. The spatial analysis and mining features in Oracle Spatial let you exploit spatial correlation by using the location attributes of data items in several ways: for binning (discretizing) data into regions (such as categorizing data into northern, southern, eastern, and western regions), for materializing the influence of neighborhood (such as number of customers within a two-mile radius of each store), and for identifying colocated data items (such as video rental stores and pizza restaurants). To perform spatial data mining, you materialize spatial predicates and relationships for a set of spatial data using thematic layers. Each layer contains data about a specific kind of spatial data (that is, having a specific "theme"), for example, parks and recreation areas, or demographic income data. The spatial materialization could be performed as a preprocessing step before the application of data mining techniques, or it could be performed as an intermediate step in spatial mining, as shown in Figure 8–1. Figure 8–1 Spatial Mining and Oracle Data Mining Notes on Figure 8–1: ■ The original data, which included spatial and nonspatial data, is processed to produce materialized data. ■ Spatial data in the original data is processed by spatial mining functions to produce materialized data. The processing includes such operations as spatial binning, proximity, and colocation materialization. Original data Spatial Mining Functions Materialized data (spatial binning, proximity, colocation materialization) ODM engine Spatial thematic data layers Mining results Spatial Mining (ODM + Spatial engine) Materializing Spatial Correlation Spatial Analysis and Mining 8-3 ■ The ODM engine processes materialized data (spatial and nonspatial) to generate mining results. The following are examples of the kinds of data mining applications that could benefit from including spatial information in their processing: ■ Business prospecting: Determine if colocation of a business with another franchise (such as colocation of a Pizza Hut restaurant with a Blockbuster video store) might improve its sales. ■ Store prospecting: Find a good store location that is within 50 miles of a major city and inside a state with no sales tax. (Although 50 miles is probably too far to drive to avoid a sales tax, many customers may live near the edge of the 50-mile radius and thus be near the state with no sales tax.) ■ Hospital prospecting: Identify the best locations for opening new hospitals based on the population of patients who live in each neighborhood. ■ Spatial region-based classification or personalization: Determine if southeastern United States customers in a certain age or income category are more likely to prefer "soft" or "hard" rock music. ■ Automobile insurance: Given a customer’s home or work location, determine if it is in an area with high or low rates of accident claims or auto thefts. ■ Property analysis: Use colocation rules to find hidden associations between proximity to a highway and either the price of a house or the sales volume of a store. ■ Property assessment: In assessing the value of a house, examine the values of similar houses in a neighborhood, and derive an estimate based on variations and spatial correlation. 8.2 Spatial Binning for Detection of Regional Patterns Spatial binning (spatial discretization) discretizes the location values into a small number of groups associated with geographical areas. The assignment of a location to a group can be done by any of the following methods: ■ Reverse geocoding the longitude/latitude coordinates to obtain an address that specifies (for United States locations) the ZIP code, city, state, and country ■ Checking a spatial bin table to determine which bin this specific location belongs in You can then apply ODM techniques to the discretized locations to identify interesting regional patterns or association rules. For example, you might discover that customers in area A prefer regular soda, while customers in area B prefer diet soda. The following functions and procedures, documented in Chapter 29, perform operations related to spatial binning: ■ SDO_SAM.BIN_GEOMETRY ■ SDO_SAM.BIN_LAYER 8.3 Materializing Spatial Correlation Spatial correlation (or, neighborhood influence) refers to the phenomenon of the location of a specific object in an area affecting some nonspatial attribute of the object. For example, the value (nonspatial attribute) of a house at a given address (geocoded to Colocation Mining 8-4 Oracle Spatial Developer's Guide give a spatial attribute) is largely determined by the value of other houses in the neighborhood. To use spatial correlation in a data mining application, you materialize the spatial correlation by adding attributes (columns) in a data mining table. You use associated thematic tables to add the appropriate attributes. You then perform mining tasks on the data mining table using ODM functions. The following functions and procedures, documented in Chapter 29, perform operations related to materializing spatial correlation: ■ SDO_SAM.SIMPLIFY_GEOMETRY ■ SDO_SAM.SIMPLIFY_LAYER ■ SDO_SAM.AGGREGATES_FOR_GEOMETRY ■ SDO_SAM.AGGREGATES_FOR_LAYER 8.4 Colocation Mining Colocation is the presence of two or more spatial objects at the same location or at significantly close distances from each other. Colocation patterns can indicate interesting associations among spatial data objects with respect to their nonspatial attributes. For example, a data mining application could discover that sales at franchises of a specific pizza restaurant chain were higher at restaurants colocated with video stores than at restaurants not colocated with video stores. Two types of colocation mining are supported: ■ Colocation of items in a data mining table. Given a data layer, this approach identifies the colocation of multiple features. For example, predator and prey species could be colocated in animal habitats, and high-sales pizza restaurants could be colocated with high-sales video stores. You can use a reference-feature approach (using one feature as a reference and the other features as thematic attributes, and materializing all neighbors for the reference feature) or a buffer-based approach (materializing all items that are within all windows of a specified size). ■ Colocation with thematic layers. Given several data layers, this approach identifies colocation across the layers. For example, given a lakes layer and a vegetation layer, lakes could be colocated with areas of high vegetation. You materialize the data, add categorical and numerical spatial relationships to the data mining table, and apply the ODM Association-Rule mechanisms. The following functions and procedures, documented in Chapter 29, perform operations related to colocation mining: ■ SDO_SAM.COLOCATED_REFERENCE_FEATURES ■ SDO_SAM.BIN_GEOMETRY 8.5 Spatial Clustering Spatial clustering returns cluster geometries for a layer of data. An example of spatial clustering is the clustering of crime location data. The SDO_SAM.SPATIAL_CLUSTERS function, documented in Chapter 29, performs spatial clustering. This function requires a spatial R-tree index on the geometry column of the layer, and it returns a set of SDO_REGION objects where the geometry Location Prospecting Spatial Analysis and Mining 8-5 column specifies the boundary of each cluster and the geometry_key value is set to null. You can use the SDO_SAM.BIN_GEOMETRY function, with the returned spatial clusters in the bin table, to identify the cluster to which a geometry belongs. 8.6 Location Prospecting Location prospecting can be performed by using thematic layers to compute aggregates for a layer, and choosing the locations that have the maximum values for computed aggregates. The following functions, documented in Chapter 29, perform operations related to location prospecting: ■ SDO_SAM.AGGREGATES_FOR_GEOMETRY ■ SDO_SAM.AGGREGATES_FOR_LAYER ■ SDO_SAM.TILED_AGGREGATES Location Prospecting 8-6 Oracle Spatial Developer's Guide 9 Extending Spatial Indexing Capabilities 9-1 9 Extending Spatial Indexing Capabilities This chapter shows how to create and use spatial indexes on objects other than a geometry column. In other chapters, the focus is on indexing and querying spatial data that is stored in a single column of type SDO_GEOMETRY. This chapter shows how to: ■ Embed an SDO_GEOMETRY object in a user-defined object type, and index the geometry attribute of that type (see Section 9.1) ■ Create and use a function-based index where the function returns an SDO_ GEOMETRY object (see Section 9.2) The techniques in this chapter are intended for experienced and knowledgeable application developers. You should be familiar with the Spatial concepts and techniques described in other chapters. You should also be familiar with, or able to learn about, relevant Oracle database features, such as user-defined data types and function-based indexing. 9.1 SDO_GEOMETRY Objects in User-Defined Type Definitions The SDO_GEOMETRY type can be embedded in a user-defined data type definition. The procedure is very similar to that for using the SDO_GEOMETRY type for a spatial data column: 1. Create the user-defined data type. 2. Create a table with a column based on that data type. 3. Insert data into the table. 4. Update the USER_SDO_GEOM_METADATA view. 5. Create the spatial index on the geometry attribute. 6. Perform queries on the data. For example, assume that you want to follow the cola markets scenario in the simplified example in Section 2.1, but want to incorporate the market name attribute and the geometry attribute in a single type. First, create the user-defined data type, as in the following example that creates an object type named MARKET_TYPE: CREATE OR REPLACE TYPE market_type AS OBJECT (name VARCHAR2(32), shape SDO_GEOMETRY); / Create a table that includes a column based on the user-defined type. The following example creates a table named COLA_MARKETS_2 that will contain the same information as the COLA_MARKETS table used in the example in Section 2.1. SDO_GEOMETRY Objects in User-Defined Type Definitions 9-2 Oracle Spatial Developer's Guide CREATE TABLE cola_markets_2 ( mkt_id NUMBER PRIMARY KEY, market MARKET_TYPE); Insert data into the table, using the object type name as a constructor. For example: INSERT INTO cola_markets_2 VALUES( 1, MARKET_TYPE('cola_a', SDO_GEOMETRY( 2003, -- two-dimensional polygon NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), -- one rectangle (1003 = exterior) SDO_ORDINATE_ARRAY(1,1, 5,7) -- only 2 points needed to -- define rectangle (lower left and upper right) ) ) ); Update the USER_SDO_GEOM_METADATA view, using dot-notation to specify the column name and spatial attribute. The following example specifies MARKET.SHAPE as the COLUMN_NAME (explained in Section 2.8.2) in the metadata view. INSERT INTO user_sdo_geom_metadata (TABLE_NAME, COLUMN_NAME, DIMINFO, SRID) VALUES ( 'cola_markets_2', 'market.shape', SDO_DIM_ARRAY( -- 20X20 grid SDO_DIM_ELEMENT('X', 0, 20, 0.005), SDO_DIM_ELEMENT('Y', 0, 20, 0.005) ), NULL -- SRID ); Create the spatial index, specifying the column name and spatial attribute using dot-notation. For example. CREATE INDEX cola_spatial_idx_2 ON cola_markets_2(market.shape) INDEXTYPE IS MDSYS.SPATIAL_INDEX; Perform queries on the data, using dot-notation to refer to attributes of the user-defined type. The following simple query returns information associated with the cola market named cola_a. SELECT c.mkt_id, c.market.name, c.market.shape FROM cola_markets_2 c WHERE c.market.name = 'cola_a'; The following query returns information associated with all geometries that have any spatial interaction with a specified query window, namely, the rectangle with lower-left coordinates (4,6) and upper-right coordinates (8,8). SELECT c.mkt_id, c.market.name, c.market.shape FROM cola_markets_2 c WHERE SDO_RELATE(c.market.shape, SDO_GEOMETRY Objects in Function-Based Indexes Extending Spatial Indexing Capabilities 9-3 SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(4,6, 8,8)), 'mask=anyinteract' = 'TRUE'; 9.2 SDO_GEOMETRY Objects in Function-Based Indexes A function-based spatial index facilitates queries that use locational information (of type SDO_GEOMETRY) returned by a function or expression. In this case, the spatial index is created based on the precomputed values returned by the function or expression. If you are not already familiar with function-based indexes, see the following for detailed explanations of their benefits, options, and requirements, as well as usage examples: ■ Oracle Database Advanced Application Developer's Guide ■ Oracle Database Administrator's Guide The procedure for using an SDO_GEOMETRY object in a function-based index is as follows: 1. Create the function that returns an SDO_GEOMETRY object. The function must be declared as DETERMINISTIC. 2. If the spatial data table does not already exist, create it, and insert data into the table. 3. Update the USER_SDO_GEOM_METADATA view. 4. Create the spatial index. For a function-based spatial index, the number of parameters must not exceed 32. 5. Perform queries on the data. The rest of this section describes two examples of using function-based indexes. In both examples, a function is created that returns an SDO_GEOMETRY object, and a spatial index is created on that function. In the first example, the input parameters to the function are a standard Oracle data type (NUMBER). In the second example, the input to the function is a user-defined object type. 9.2.1 Example: Function with Standard Types In the following example, the input parameters to the function used for the function-based index are standard numeric values (longitude and latitude). Assume that you want to create a function that returns the longitude and latitude of a point and to use that function in a spatial index. First, create the function, as in the following example that creates a function named GET_LONG_LAT_PT: -- Create a function to return a point geometry (SDO_GTYPE = 2001) with -- input of 2 numbers: longitude and latitude (SDO_SRID = 8307, for -- "Longitude / Latitude (WGS 84)", probably the most widely used -- coordinate system, and the one used for GPS devices. -- Specify DETERMINISTIC for the function. create or replace function get_long_lat_pt(longitude in number, latitude in number) return SDO_GEOMETRY deterministic is begin SDO_GEOMETRY Objects in Function-Based Indexes 9-4 Oracle Spatial Developer's Guide return sdo_geometry(2001, 8307, sdo_point_type(longitude, latitude, NULL),NULL, NULL); end; / If the spatial data table does not already exist, create the table and add data to it, as in the following example that creates a table named LONG_LAT_TABLE: create table LONG_LAT_TABLE (lon number, lat number, name varchar2(32)); insert into LONG_LAT_TABLE values (10,10, 'Place1'); insert into LONG_LAT_TABLE values (20,20, 'Place2'); insert into LONG_LAT_TABLE values (30,30, 'Place3'); Update the USER_SDO_GEOM_METADATA view, using dot-notation to specify the schema name and function name. The following example specifies SCOTT.GET_ LONG_LAT_PT(LON,LAT) as the COLUMN_NAME (explained in Section 2.8.2) in the metadata view. -- Set up the metadata entry for this table. -- The column name sets up the function on top -- of the two columns used in this function, -- along with the owner of the function. insert into user_sdo_geom_metadata values('LONG_LAT_TABLE', 'scott.get_long_lat_pt(lon,lat)', sdo_dim_array( sdo_dim_element('Longitude', -180, 180, 0.005), sdo_dim_element('Latitude', -90, 90, 0.005)), 8307); Create the spatial index, specifying the function name with parameters. For example: create index LONG_LAT_TABLE_IDX on LONG_LAT_TABLE(get_long_lat_pt(lon,lat)) indextype is mdsys.spatial_index; Perform queries on the data. The following example specifies the user-defined function in a call to the SDO_FILTER operator. select name from LONG_LAT_TABLE a where sdo_filter( get_long_lat_pt(a.lon,a.lat), sdo_geometry(2001, 8307, sdo_point_type(10,10,NULL), NULL, NULL) )='TRUE'; NAME -------------------------------- Place1 9.2.2 Example: Function with a User-Defined Object Type In the following example, the input parameter to the function used for the function-based index is an object of a user-defined type that includes the longitude and latitude. Assume that you want to create a function that returns the longitude and latitude of a point and to create a spatial index on that function. First, create the user-defined data type, as in the following example that creates an object type named LONG_LAT and its member function GetGeometry: create type long_lat as object ( SDO_GEOMETRY Objects in Function-Based Indexes Extending Spatial Indexing Capabilities 9-5 longitude number, latitude number, member function GetGeometry(SELF in long_lat) RETURN SDO_GEOMETRY DETERMINISTIC) / create or replace type body long_lat as member function GetGeometry(self in long_lat) return SDO_GEOMETRY is begin return sdo_geometry(2001, 8307, sdo_point_type(longitude, latitude, NULL), NULL,NULL); end; end; / If the spatial data table does not already exist, create the table and add data to it, as in the following example that creates a table named TEST_LONG_LAT: create table test_long_lat (location long_lat, name varchar2(32)); insert into test_long_lat values (long_lat(10,10), 'Place1'); insert into test_long_lat values (long_lat(20,20), 'Place2'); insert into test_long_lat values (long_lat(30,30), 'Place3'); Update the USER_SDO_GEOM_METADATA view, using dot-notation to specify the schema name, table name, and function name and parameter value. The following example specifies SCOTT.LONG_LAT.GetGeometry(LOCATION) as the COLUMN_ NAME (explained in Section 2.8.2) in the metadata view. insert into user_sdo_geom_metadata values('test_long_lat', 'scott.long_lat.GetGeometry(location)', sdo_dim_array( sdo_dim_element('Longitude', -180, 180, 0.005), sdo_dim_element('Latitude', -90, 90, 0.005)), 8307); Create the spatial index, specifying the column name and function name using dot-notation. For example: create index test_long_lat_idx on test_long_lat(location.GetGeometry()) indextype is mdsys.spatial_index; Perform queries on the data. The following query performs a primary filter operation, asking for the names of geometries that are likely to interact spatially with point (10,10). SELECT a.name FROM test_long_lat a WHERE SDO_FILTER(a.location.GetGeometry(), SDO_GEOMETRY(2001, 8307, SDO_POINT_TYPE(10,10,NULL), NULL, NULL) ) = 'TRUE'; SDO_GEOMETRY Objects in Function-Based Indexes 9-6 Oracle Spatial Developer's Guide Part II Part II Spatial Web Services This document has the following parts: ■ Part I provides conceptual and usage information about Oracle Spatial. ■ Part II provides conceptual and usage information about Oracle Spatial Web services. ■ Part III provides reference information about Oracle Spatial operators, functions, and procedures. ■ Part IV provides supplementary information (appendixes and a glossary). Part II contains the following chapters: ■ Chapter 10, "Introduction to Spatial Web Services" ■ Chapter 11, "Geocoding Address Data" ■ Chapter 12, "Business Directory (Yellow Pages) Support" ■ Chapter 13, "Routing Engine" ■ Chapter 14, "OpenLS Support" ■ Chapter 15, "Web Feature Service (WFS) Support" ■ Chapter 16, "Catalog Services for the Web (CSW) Support" ■ Chapter 17, "Security Considerations for Spatial Web Services" 10 Introduction to Spatial Web Services 10-1 10 Introduction to Spatial Web Services This chapter introduces the Oracle Spatial support for spatial Web services. A Web service enables developers of Oracle Spatial applications to provide feature data and metadata to their application users over the Web. This chapter contains the following major sections: ■ Section 10.1, "Types of Spatial Web Services" ■ Section 10.2, "Types of Users of Spatial Web Services" ■ Section 10.3, "Setting Up the Client for Spatial Web Services" ■ Section 10.4, "Demo Files for Sample Java Client" 10.1 Types of Spatial Web Services Oracle Spatial provides the following types of Web services: ■ Geocoding, which enables users to associate spatial locations (longitude and latitude coordinates) with postal addresses. Geocoding support is explained in Chapter 11. ■ Yellow Pages, which enables users to find businesses by name or category based on their relationship to a location. Yellow Pages support is explained in Chapter 12. ■ Routing, which provides driving information and instructions for individual or multiple routes. Routing support is explained in Chapter 13. ■ OpenLS, which provides location-based services based on the Open Location Services Initiative (OpenLS) specification for geocoding, mapping, routing, and yellow pages. OpenLS support is explained in Chapter 14. ■ Web Feature Services (WFS), which enables users to find features (roads, rivers, and so on) based on their relationship to a location or a nonspatial attribute. WFS support is explained in Chapter 15. Note: If you are using Spatial Web Feature Service (WFS) or Catalog Services for the Web (CSW) support, and if you have data from a previous release that was indexed using one or more SYS.XMLTABLEINDEX indexes, you must drop the associated indexes before the upgrade and re-create the indexes after the upgrade. For more information, see Section A.2. Types of Users of Spatial Web Services 10-2 Oracle Spatial Developer's Guide ■ Catalog Services for the Web (CSW), which describes the Oracle Spatial implementation of the Open GIS Consortium specification for catalog services. According to this specification: "Catalogue services support the ability to publish and search collections of descriptive information (metadata) for data, services, and related information objects." CSW support is explained in Chapter 16. Security considerations for Web services are explained in Chapter 17. 10.2 Types of Users of Spatial Web Services In the general business sense of the word "user," implementing any spatial Web services application involves the following kinds of people: ■ Administrators set up the Web services infrastructure. Administrators might create database users, grant privileges and access rights to new and existing database users, and do other operations that affect multiple database users. For Web feature services, administrators register feature tables, publish feature types, and unlock certain accounts. For example, an administrator might set up the infrastructure to enable access to spatial features, such as roads and rivers. ■ Application developers create and manage the spatial data and metadata. They create spatial data tables, create spatial indexes, insert rows into the USER_SDO_ GEOM_METADATA view, and use Spatial functions and procedures to implement the application logic. For example, an application developer might create tables of roads and rivers, and implement application logic that enables end users to find roads and rivers based on spatial query criteria. ■ End users access the services through their Web browsers. For example, an end user might ask for all roads that are within one mile of a specific river or that intersect (cross) that river. From the perspective of an administrator, application developers and end users are all "users" because database users must be created to accommodate their needs. Application developers will connect to the database as users with sufficient privileges to create and manage spatial tables and to use Oracle Spatial functions and procedures. End users will access the database through a database user with limited access privileges, typically read-only access to data or limited write access. The chapters about Spatial Web services are written for administrators and application developers, not for end users. 10.3 Setting Up the Client for Spatial Web Services Before anyone can use Spatial Web services, you, as an administrator with the DBA role, must ensure that: ■ The $ORACLE_HOME/md/jlib/sdows.ear file is deployed into an OC4J instance. ■ The necessary database connections are defined (if you accepted the default location for the sdows.ear file deployment) in the /home/applications/sdows/META-INF/data-sources.xml file. This file defines database connections available for use with all Web services, including OpenLS and WFS. Setting Up the Client for Spatial Web Services Introduction to Spatial Web Services 10-3 You should then examine and modify the /home/applications/sdows/sdows/WEB-INF/conf/WSConfig.xml file, which controls Web services behavior. Example 10–1 shows the Oracle-supplied WSConfig.xml file, which you should modify as needed for your system environment. For more information about how to modify this and other files, see the Readme.txt file for the wsclient.jar demo file (described in Section 10.4) Example 10–1 WSConfig.xml File Setting Up the Client for Spatial Web Services 10-4 Oracle Spatial Developer's Guide oracle.spatial.ws.openls.OpenLsHandler SpatialWsXmlUser Demo Files for Sample Java Client 10-6 Oracle Spatial Developer's Guide oracle.spatial.wfs.WFSHandler SpatialWsXmlUser oracle.spatial.csw.CSWHandler SpatialWsXmlUser oracle.spatial.ws.svrproxy.SdoRequestHandler SpatialWsXmlUser oracle.spatial.ws.svrproxy.SdoTestRequestHandler SpatialWsXmlUser oracle.spatial.network.xml.NetworkWSHandler You must also perform specific tasks that depend on which Web services you will be supporting for use in your environment. You will probably need to create and grant privileges to database users. You may need to download and load special data (such as for geocoding) or to modify configuration files. See the chapters on individual Web services for any specific requirements. 10.4 Demo Files for Sample Java Client To help you get started with Spatial Web services, Oracle supplies a. jar file (wsclient.jar) with the source code and related files for setting up a sample Java client. To use this file, follow these steps: 1. Find wsclient.jar under the Spatial demo directory. 2. Expand (unzip) wsclient.jar into a directory of your choice. The top-level directory for all the files in the .jar file is named src. 3. In the src directory, read the file named Readme.txt and follow its instructions. The Readme.txt file contains detailed explanations and guidelines. 11 Geocoding Address Data 11-1 11 Geocoding Address Data Geocoding is the process of associating spatial locations (longitude and latitude coordinates) with postal addresses. This chapter includes the following major sections: ■ Section 11.1, "Concepts for Geocoding" ■ Section 11.2, "Data Types for Geocoding" ■ Section 11.3, "Using the Geocoding Capabilities" ■ Section 11.4, "Geocoding from a Place Name" ■ Section 11.5, "Data Structures for Geocoding" ■ Section 11.7, "Using the Geocoding Service (XML API)" 11.1 Concepts for Geocoding This section describes concepts that you must understand before you use the Spatial geocoding capabilities. 11.1.1 Address Representation Addresses to be geocoded can be represented either as formatted addresses or unformatted addresses. A formatted address is described by a set of attributes for various parts of the address, which can include some or all of those shown in Table 11–1. Table 11–1 Attributes for Formal Address Representation Address Attribute Description Name Place name (optional). Intersecting street Intersecting street name (optional). Street Street address, including the house or building number, street name, street type (Street, Road, Blvd, and so on), and possibly other information. In the current release, the first four characters of the street name must match a street name in the geocoding data for there to be a potential street name match. Settlement The lowest-level administrative area to which the address belongs. In most cases it is the city. In some European countries, the settlement can be an area within a large city, in which case the large city is the municipality. Concepts for Geocoding 11-2 Oracle Spatial Developer's Guide Formatted addresses are specified using the SDO_GEO_ADDR data type, which is described in Section 11.2.1. An unformatted address is described using lines with information in the postal address format for the relevant country. The address lines must contain information essential for geocoding, and they might also contain information that is not needed for geocoding (something that is common in unprocessed postal addresses). An unformatted address is stored as an array of strings. For example, an address might consist of the following strings: '22 Monument Square' and 'Concord, MA 01742'. Unformatted addresses are specified using the SDO_KEYWORDARRAY data type, which is described in Section 11.2.3. 11.1.2 Match Modes The match mode for a geocoding operation determines how closely the attributes of an input address must match the data being used for the geocoding. Input addresses can include different ways of representing the same thing (such as Street and the abbreviation St), and they can include minor errors (such as the wrong postal code, even though the street address and city are correct and the street address is unique within the city). You can require an exact match between the input address and the data used for geocoding, or you can relax the requirements for some attributes so that geocoding can be performed despite certain discrepancies or errors in the input addresses. Table 11–2 lists the match modes and their meanings. Use a value from this table with the MatchMode attribute of the SDO_GEO_ADDR data type (described in Section 11.2.1) and for the match_mode parameter of a geocoding function or procedure. Municipality The administrative area above settlement. Municipality is not used for United States addresses. In European countries where cities contain settlements, the municipality is the city. Region The administrative area above municipality (if applicable), or above settlement if municipality does not apply. In the United States, the region is the state; in some other countries, the region is the province. Postal code Postal code (optional if administrative area information is provided). In the United States, the postal code is the 5-digit ZIP code. Postal add-on code String appended to the postal code. In the United States, the postal add-on code is typically the last four numbers of a 9-digit ZIP code specified in "5-4" format. Country The country name or ISO country code. Table 11–2 Match Modes for Geocoding Operations Match Mode Description EXACT All attributes of the input address must match the data used for geocoding. However, if the house or building number, base name (street name), street type, street prefix, and street suffix do not all match the geocoding data, a location in the first match found in the following is returned: postal code, city or town (settlement) within the state, and state. For example, if the street name is incorrect but a valid postal code is specified, a location in the postal code is returned. Table 11–1 (Cont.) Attributes for Formal Address Representation Address Attribute Description Concepts for Geocoding Geocoding Address Data 11-3 11.1.3 Match Codes The match code is a number indicating which input address attributes matched the data used for geocoding. The match code is stored in the MatchCode attribute of the output SDO_GEO_ADDR object (described in Section 11.2.1). Table 11–3 lists the possible match code values. RELAX_STREET_TYPE The street type can be different from the data used for geocoding. For example, if Main St is in the data used for geocoding, Main Street would also match that, as would Main Blvd if there was no Main Blvd and no other street type named Main in the relevant area. RELAX_POI_NAME The name of the point of interest does not have to match the data used for geocoding. For example, if Jones State Park is in the data used for geocoding, Jones State Pk and Jones Park would also match as long as there were no ambiguities or other matches in the data. RELAX_HOUSE_ NUMBER The house or building number and street type can be different from the data used for geocoding. For example, if 123 Main St is in the data used for geocoding, 123 Main Lane and 124 Main St would also match as long as there were no ambiguities or other matches in the data. RELAX_BASE_NAME The base name of the street, the house or building number, and the street type can be different from the data used for geocoding. For example, if Pleasant Valley is the base name of a street in the data used for geocoding, Pleasant Vale would also match as long as there were no ambiguities or other matches in the data. RELAX_POSTAL_CODE The postal code (if provided), base name, house or building number, and street type can be different from the data used for geocoding. RELAX_BUILTUP_AREA The address can be outside the city specified as long as it is within the same county. Also includes the characteristics of RELAX_POSTAL_CODE. RELAX_ALL Equivalent to RELAX_BUILTUP_AREA. DEFAULT Equivalent to RELAX_POSTAL_CODE. Table 11–3 Match Codes for Geocoding Operations Match Code Description 1 Exact match: the city name, postal code, street base name, street type (and suffix or prefix or both, if applicable), and house or building number match the data used for geocoding. 2 The city name, postal code, street base name, and house or building number match the data used for geocoding, but the street type, suffix, or prefix does not match. 3 The city name, postal code, and street base name match the data used for geocoding, but the house or building number does not match. 4 The city name and postal code match the data used for geocoding, but the street address does not match. 10 The city name matches the data used for geocoding, but the postal code does not match. Table 11–2 (Cont.) Match Modes for Geocoding Operations Match Mode Description Concepts for Geocoding 11-4 Oracle Spatial Developer's Guide 11.1.4 Error Messages for Output Geocoded Addresses For an output geocoded address, the ErrorMessage attribute of the SDO_GEO_ ADDR object (described in Section 11.2.1) contains a string that indicates which address attributes have been matched against the data used for geocoding. Before the geocoding operation begins, the string is set to the value ???????????281C??; and the value is modified to reflect which attributes have been matched. Table 11–4 lists the character positions in the string and the address attribute corresponding to each position. It also lists the character value that the position is set to if the attribute is matched. 11.1.5 Match Vector for Output Geocoded Addresses For an output geocoded address, the MatchVector attribute of the SDO_GEO_ADDR object (described in Section 11.2.1) contains a string that indicates how each address attribute has been matched against the data used for geocoding. It gives more accurate 11 The postal code matches the data used for geocoding, but the city name does not match. Note: You are encouraged to use the MatchVector attribute (see Section 11.1.5) instead of the ErrorMessage attribute, which is described in this section. Table 11–4 Geocoded Address Error Message Interpretation Position Attribute Value If Matched 1-2 (Reserved for future use) ?? 3Address pointX 4POI nameO 5 House or building number # 6 Street prefix E 7 Street base name N 8 Street suffix U 9 Street type T 10 Secondary unit S 11 Built-up area or city B 12-13 (Reserved) (Ignore any values in these positions.) 14 Region 1 15 Country C 16 Postal code P 17 Postal add-on code A Table 11–3 (Cont.) Match Codes for Geocoding Operations Match Code Description Data Types for Geocoding Geocoding Address Data 11-5 and detailed information about the match status of each address attribute than the ErrorMessage attribute (described in Section 11.1.4). Before the geocoding operation begins, the string is set to the value ?????????????????. Each character of this string indicates the match status of an address attribute. Table 11–5 lists the character positions in the string and the address attribute corresponding to each position. Following the table is an explanation of what the value in each character position represents. Each character position in Table 11–5 can have one of the following possible numeric values: ■ 0: The input attribute is not null and is matched with a non-null value. ■ 1: The input attribute is null and is matched with a null value. ■ 2: The input attribute is not null and is replaced by a different non-null value. ■ 3: The input attribute is not null and is replaced by a null value. ■ 4: The input attribute is null and is replaced by a non-null value. 11.2 Data Types for Geocoding This section describes the data types specific to geocoding functions and procedures. 11.2.1 SDO_GEO_ADDR Type The SDO_GEO_ADDR object type is used to describe an address. When a geocoded address is output by an SDO_GCDR function or procedure, it is stored as an object of type SDO_GEO_ADDR. Table 11–6 lists the attributes of the SDO_GEO_ADDR type. Not all attributes will be relevant in any given case. The attributes used for a returned geocoded address depend on the geographical context of the input address, especially the country. Table 11–5 Geocoded Address Match Vector Interpretation Position Attribute 1-2 (Reserved for future use) 3 Address point 4POI name 5 House or building number 6 Street prefix 7 Street base name 8 Street suffix 9 Street type 10 Secondary unit 11 Built-up area or city 14 Region 15 Country 16 Postal code 17 Postal add-on code Data Types for Geocoding 11-6 Oracle Spatial Developer's Guide Table 11–6 SDO_GEO_ADDR Type Attributes Attribute Data Type Description Id NUMBER (Not used.) AddressLines SDO_ KEYWORDARRAY Address lines. (The SDO_KEYWORDARRAY type is described in Section 11.2.3.) PlaceName VARCHAR2(200) Point of interest (POI) name. Example: CALIFORNIA PACIFIC MEDICAL CTR StreetName VARCHAR2(200) Street name, including street type. Example: MAIN ST IntersectStreet VARCHAR2(200) Intersecting street. SecUnit VARCHAR2(200) Secondary unit, such as an apartment number or building number. Settlement VARCHAR2(200) Lowest-level administrative area to which the address belongs. (See Table 11–1.) Municipality VARCHAR2(200) Administrative area above settlement. (See Table 11–1.) Region VARCHAR2(200) Administrative area above municipality (if applicable), or above settlement if municipality does not apply. (See Table 11–1.) Country VARCHAR2(100) Country name or ISO country code. PostalCode VARCHAR2(20) Postal code (optional if administrative area information is provided). In the United States, the postal code is the 5-digit ZIP code. PostalAddOnCode VARCHAR2(20) String appended to the postal code. In the United States, the postal add-on code is typically the last four numbers of a 9-digit ZIP code specified in "5-4" format. FullPostalCode VARCHAR2(20) Full postal code, including the postal code and postal add-on code. POBox VARCHAR2(100) Post Office box number. HouseNumber VARCHAR2(100) House or building number. Example: 123 in 123 MAIN ST BaseName VARCHAR2(200) Base name of the street. Example: MAIN in 123 MAIN ST StreetType VARCHAR2(20) Type of the street. Example: ST in 123 MAIN ST StreetTypeBefore VARCHAR2(1) (Not used.) StreetTypeAttached VARCHAR2(1) (Not used.) StreetPrefix VARCHAR2(20) Prefix for the street. Example: S in 123 S MAIN ST StreetSuffix VARCHAR2(20) Suffix for the street. Example: NE in 123 MAIN ST NE Side VARCHAR2(1) Side of the street (L for left or R for right) that the house is on when you are traveling along the road segment following its orientation (that is, from its start node toward its end node). The house numbers may be increasing or decreasing. Data Types for Geocoding Geocoding Address Data 11-7 You can return the entire SDO_GEO_ADDR object, or you can specify an attribute using standard "dot" notation. Example 11–1 contains statements that geocode the address of the San Francisco City Hall; the first statement returns the entire SDO_ GEO_ADDR object, and the remaining statements return some specific attributes. Example 11–1 Geocoding, Returning Address Object and Specific Attributes SELECT SDO_GCDR.GEOCODE('SCOTT', SDO_KEYWORDARRAY('1 Carlton B Goodlett Pl', 'San Francisco, CA 94102'), 'US', 'RELAX_BASE_NAME') FROM DUAL; SDO_GCDR.GEOCODE('SCOTT',SDO_KEYWORDARRAY('1CARLTONBGOODLETTPL','SANFRANCISCO -------------------------------------------------------------------------------- SDO_GEO_ADDR(0, SDO_KEYWORDARRAY(), NULL, 'CARLTON B GOODLETT PL', NULL, NULL, ' SAN FRANCISCO', NULL, 'CA', 'US', '94102', NULL, '94102', NULL, '1', 'CARLTON B GOODLETT', 'PL', 'F', 'F', NULL, NULL, 'L', .01, 23614360, '????#ENUT?B281CP?', 1, 'RELAX_BASE_NAME', -122.41815, 37.7784183, '????0101010??000?') SELECT SDO_GCDR.GEOCODE('SCOTT', SDO_KEYWORDARRAY('1 Carlton B Goodlett Pl', 'San Francisco, CA 94102'), 'US', 'RELAX_BASE_NAME').StreetType FROM DUAL; SDO_GCDR.GEOCODE('SCOTT',SDO_KEYWORDARRAY('1CARLTONBGOODLETTPL','SANFRANCISCO -------------------------------------------------------------------------------- PL SELECT SDO_GCDR.GEOCODE('SCOTT', SDO_KEYWORDARRAY('1 Carlton B Goodlett Pl', 'San Francisco, CA 94102'), 'US', 'RELAX_BASE_NAME').Side RROM DUAL; S - L SELECT SDO_GCDR.GEOCODE('SCOTT', SDO_KEYWORDARRAY('1 Carlton B Goodlett Pl', 'San Francisco, CA 94102'), 'US', 'RELAX_BASE_NAME').Percent FROM DUAL; Percent NUMBER Number from 0 to 1 (multiply by 100 to get a percentage value) indicating how far along the street you are when traveling following the road segment orientation. EdgeID NUMBER Edge ID of the road segment. ErrorMessage VARCHAR2(20) Error message (see Section 11.1.4). Note: You are encouraged to use the MatchVector attribute instead of the ErrorMessage attribute. MatchCode NUMBER Match code (see Section 11.1.3). MatchMode VARCHAR2(30) Match mode (see Section 11.1.2). Longitude NUMBER Longitude coordinate value. Latitude NUMBER Latitude coordinate value. MatchVector VARCHAR2(20) A string that indicates how each address attribute has been matched against the data used for geocoding (see Section 11.1.5). Table 11–6 (Cont.) SDO_GEO_ADDR Type Attributes Attribute Data Type Description Using the Geocoding Capabilities 11-8 Oracle Spatial Developer's Guide SDO_GCDR.GEOCODE('SCOTT',SDO_KEYWORDARRAY('1CARLTONBGOODLETTPL','SANFRANCISCO -------------------------------------------------------------------------------- .01 SELECT SDO_GCDR.GEOCODE('SCOTT', SDO_KEYWORDARRAY('1 Carlton B Goodlett Pl', 'San Francisco, CA 94102'), 'US', 'RELAX_BASE_NAME').EdgeID FROM DUAL; SDO_GCDR.GEOCODE('SCOTT',SDO_KEYWORDARRAY('1CARLTONBGOODLETTPL','SANFRANCISCO -------------------------------------------------------------------------------- 23614360 SELECT SDO_GCDR.GEOCODE('SCOTT', SDO_KEYWORDARRAY('1 Carlton B Goodlett Pl', 'San Francisco, CA 94102'), 'US', 'RELAX_BASE_NAME').MatchCode FROM DUAL; SDO_GCDR.GEOCODE('SCOTT',SDO_KEYWORDARRAY('1CARLTONBGOODLETTPL','SANFRANCISCO -------------------------------------------------------------------------------- 1 SELECT SDO_GCDR.GEOCODE('SCOTT', SDO_KEYWORDARRAY('1 Carlton B Goodlett Pl', 'San Francisco, CA 94102'), 'US', 'RELAX_BASE_NAME').MatchVector FROM DUAL; SDO_GCDR.GEOCODE('SC -------------------- ????0101010??000? 11.2.2 SDO_ADDR_ARRAY Type The SDO_ADDR_ARRAY type is a VARRAY of SDO_GEO_ADDR objects (described in Section 11.2.1) used to store geocoded address results. Multiple address objects can be returned when multiple addresses are matched as a result of a geocoding operation. The SDO_ADDR_ARRAY type is defined as follows: CREATE TYPE sdo_addr_array AS VARRAY(1000) OF sdo_geo_addr; 11.2.3 SDO_KEYWORDARRAY Type The SDO_KEYWORDARRAY type is a VARRAY of VARCHAR2 strings used to store address lines for unformatted addresses. (Formatted and unformatted addresses are described in Section 11.1.1.) The SDO_KEYWORDARRAY type is defined as follows: CREATE TYPE sdo_keywordarray AS VARRAY(10000) OF VARCHAR2(9000); 11.3 Using the Geocoding Capabilities To use the Oracle Spatial geocoding capabilities, you must use data provided by a geocoding vendor, and the data must be in the format supported by the Oracle Spatial geocoding feature. For information about getting and loading this data, go to the Spatial page of the Oracle Technology Network (OTN): http://www.oracle.com/technology/products/spatial/ Find the link for geocoding, and follow the instructions. Geocoding from a Place Name Geocoding Address Data 11-9 To geocode an address using the geocoding data, use the SDO_GCDR PL/SQL package subprograms, which are documented in Chapter 23: ■ The SDO_GCDR.GEOCODE function geocodes an unformatted address to return an SDO_GEO_ADDR object. ■ The SDO_GCDR.GEOCODE_ADDR function geocodes an input address using attributes in an SDO_GEO_ADDR object, and returns the first matched address as an SDO_GEO_ADDR object. ■ The SDO_GCDR.GEOCODE_ADDR_ALL function geocodes an input address using attributes in an SDO_GEO_ADDR object, and returns matching addresses as an SDO_ADDR_ARRAY object. ■ The SDO_GCDR.GEOCODE_AS_GEOMETRY function geocodes an unformatted address to return an SDO_GEOMETRY object. ■ The SDO_GCDR.GEOCODE_ALL function geocodes all addresses associated with an unformatted address and returns the result as an SDO_ADDR_ARRAY object (an array of address objects). ■ The SDO_GCDR.REVERSE_GEOCODE function reverse geocodes a location, specified by its spatial geometry object and country, and returns the result as an SDO_GEO_ADDR object. 11.4 Geocoding from a Place Name If you know a place name (point of interest) but not its locality details, you can create a PL/SQL function to construct an SDO_GEO_ADDR object from placename and country input parameters, as shown in Example 11–2, which creates a function named create_addr_from_placename. The SELECT statement in this example uses the SDO_GCDR.GEOCODE_ADDR function to geocode the address constructed using the create_addr_from_placename function. Example 11–2 Geocoding from a Place Name and Country create or replace function create_addr_from_placename( placename varchar2, country varchar2) return sdo_geo_addr deterministic as addr sdo_geo_addr ; begin addr := sdo_geo_addr() ; addr.country := country ; addr.placename := placename ; addr.matchmode := 'default' ; return addr ; end; / SELECT sdo_gcdr.geocode_addr('SCOTT', create_addr_from_placename('CALIFORNIA PACIFIC MEDICAL CTR', 'US')) FROM DUAL; If you know at least some of the locality information, such as settlement, region, and postal code, you can get better performance if you can provide such information. Example 11–3 provides an alternate version of the create_addr_from_placename function that accepts additional parameters. To call this version of the function, specify Data Structures for Geocoding 11-10 Oracle Spatial Developer's Guide actual values for the placename and country parameters, and specify an actual value or a null value for each of the other input parameters. Example 11–3 Geocoding from a Place Name, Country, and Other Fields create or replace function create_addr_from_placename( placename varchar2, city varchar2, state varchar2, postalcode varchar2, country varchar2) return sdo_geo_addr deterministic as addr sdo_geo_addr ; begin addr := sdo_geo_addr() ; addr.settlement := city ; addr.region := state ; addr.postalcode := postalcode ; addr.country := country ; addr.placename := placename ; addr.matchmode := 'default' ; return addr ; end; / SELECT sdo_gcdr.geocode_addr('SCOTT', create_addr_from_placename('CALIFORNIA PACIFIC MEDICAL CTR', 'san francisco', 'ca', null, 'US')) FROM DUAL; 11.5 Data Structures for Geocoding Oracle uses the following tables for geocoding: ■ GC_PARSER_PROFILES ■ GC_PARSER_PROFILEAFS ■ GC_COUNTRY_PROFILE ■ GC_AREA_ ■ GC_POSTAL_CODE_ ■ GC_ROAD_SEGMENT_ ■ GC_ROAD_ ■ GC_POI_ ■ GC_INTERSECTION_ The GC_PARSER_PROFILES and GC_PARSER_PROFILEAFS tables store address format definitions of all supported counties. These tables are used by the internal address parser in parsing postal addresses into addressing fields. The data for these two tables is provided by your data provider or by Oracle. (If these tables are not supplied by your data provider, you will need to install and populate them as explained in Section 11.6.) The remaining tables store geocoding data provided by data vendors. Each user that owns the tables containing geocoding data (that is, each user that can be specified with the username parameter in a call to an SDO_GCDR subprogram) must Data Structures for Geocoding Geocoding Address Data 11-11 have one GC_PARSER_PROFILES table, one GC_PARSER_PROFILEAFS table, and one GC_COUNTRY_PROFILE table. Each such user can have multiple sets of the other tables (GC_xxx_). Each set of tables whose names end with the same suffix stores geocoding data of a country. For example, the following set of tables can be used to store geocoding data of the United States: ■ GC_AREA_US ■ GC_POSTAL_CODE_US ■ GC_ROAD_SEGMENT_US ■ GC_ROAD_US ■ GC_POI_US ■ GC_INTERSECTION_US Geocoding data of one country cannot be stored in more than one set of those tables. The table suffix is defined by data venders and is specified in the GC_TABLE_SUFFIX column in the GC_COUNTRY_PROFILE table (described in Section 11.5.3). The following sections describe the vendor-supplied tables that store geocoding data, in alphabetical order by table name. Section 11.5.11 describes the indexes that you must create in order to use these tables for geocoding. 11.5.1 GC_ADDRESS_POINT_ Table and Index The GC_ADDRESS_POINT_ table (for example, GC_ADDRESS_POINT_US) stores the geographic (latitude, longitude) coordinates for addresses in the country or group of countries associated with the table-name suffix. This table is not required for geocoding (although it is required for point-based geocoding); however, it enables the geocoder to provide more accurate location results. It is automatically used when present in the schema. This table contains one row for each address stored in the table, and it contains the columns shown in Table 11–7. Table 11–7 GC_ADDRESS_POINT_ Table Column Name Data Type Description ADDRESS_ POINT_ID NUMBER(10) ID number of the address point. (Required) ROAD_ID NUMBER ID number of the road on which the address point is located. (Required) ROAD_ SEGMENT_ID NUMBER(10) ID number of the road segment on the road on which the address point is located. (Required) SIDE VARCHAR2(1) Side of the road on which the address point is located. Possible values: L (left) or R (right). (Required) LANG_CODE VARCHAR2(3) 3-letter ISO national language code for the language associated with the address point. (Required) point HOUSE_NUMBER VARCHAR2(600 CHAR) House number of the address point; may contain non-numeric characters. (Required) PERCENT NUMBER Decimal fraction of the length of the road segment on which the address point is located. It is computed by dividing the distance from the segment start point to the address point by the length of the road segment. (Required). Data Structures for Geocoding 11-12 Oracle Spatial Developer's Guide If you use the GC_ADDRESS_POINT_ table, you must create an index on the table using a statement in the following form: CREATE INDEX idx__addrpt_addr ON gc_address_point_ (road_segment_ id, road_id, house_number, side); 11.5.2 GC_AREA_ Table The GC_AREA_ table (for example, CG_AREA_US) stores administration area information for the country associated with the table name suffix. This table contains one row for each administration area, and it contains the columns shown in Table 11–8. ADDR_LONG NUMBER(10) Longitude coordinate value of the address point. (Required) ADDR_LAT NUMBER(10) Latitude coordinate value of the address point. (Required) COUNTRY_ CODE_2 VARCHAR2(2) 2- letter ISO country code of the country to which the address point belongs. (Required) PARTITION_ID NUMBER Partition key used for partitioning geocoder data by geographic boundaries. If the data is not partitioned, set the value to 1. (Required) Table 11–8 GC_AREA_ Table Column Name Data Type Description AREA_ID NUMBER(10) Area ID number. (Required) AREA_NAME VARCHAR2(64) Area name. (Required) LANG_CODE VARCHAR2(3) 3-letter ISO national language code for the language associated with the area. (Required) ADMIN_LEVEL NUMBER(1) Administration hierarchy level for the area. (Required) LEVEL1_AREA_ ID NUMBER(10) ID of the level-1 area to which the area belongs. In the administration hierarchy, the level-1 area is the country. (Required) LEVEL2_AREA_ ID NUMBER(10) ID of the level-2 area to which the area belongs, if applicable. You must specify an area ID for each level in the administration hierarchy to which this area belongs. (Optional) LEVEL3_AREA_ ID NUMBER(10) ID of the level-3 area to which the area belongs, if applicable. You must specify an area ID for each level in the administration hierarchy to which this area belongs. (Optional) LEVEL4_AREA_ ID NUMBER(10) ID of the level-4 area to which the area belongs, if applicable. You must specify an area ID for each level in the administration hierarchy to which this area belongs. (Optional) LEVEL5_AREA_ ID NUMBER(10) ID of the level-5 area to which the area belongs, if applicable. You must specify an area ID for each level in the administration hierarchy to which this area belongs. (Optional) Table 11–7 (Cont.) GC_ADDRESS_POINT_ Table Column Name Data Type Description Data Structures for Geocoding Geocoding Address Data 11-13 LEVEL6_AREA_ ID NUMBER(10) ID of the level-6 area to which the area belongs, if applicable. You must specify an area ID for each level in the administration hierarchy to which this area belongs. (Optional) LEVEL7_AREA_ ID NUMBER(10) ID of the level-7 area to which the area belongs, if applicable. You must specify an area ID for each level in the administration hierarchy to which this area belongs. (Optional) CENTER_LONG NUMBER Longitude value of the center of the area. The center is set to the closest road segment to the center longitude and latitude values. Oracle recommends that these two attributes be set properly. If these values are not set, the longitude and latitude coordinates of the geocoded result of an area will be (0,0). (Optional) CENTER_LAT NUMBER Latitude value of the center of the area. (See the explanation for the CENTER_LONG column.) (Optional) ROAD_ SEGMENT_ID NUMBER(10) ID of the road segment to which the area center is set. This value must be set correctly if the geocoder is intended to work with the Oracle Spatial routing engine (described in Chapter 13); otherwise, it can be set to any nonzero value, but it cannot be null. (Required) POSTAL_CODE VARCHAR2(16) Postal code for the center of the area. Oracle recommends that this attribute be set correctly. If this value is null, the postal code attribute of the geocoded result of an area will be null. (Optional) COUNTRY_ CODE_2 VARCHAR2(2) 2- letter ISO country code of the country to which the area belongs. (Required) PARTITION_ID NUMBER Partition key used for partitioning geocoder data by geographic boundaries. If the data is not partitioned, set the value to 1. (Required) REAL_NAME VARCHAR2(64) The real name of the area, as spelled using the local language. This column is useful for area names that are not in English. For example, the German name of city MUNICH is MÜNCHEN. It is allowed to be spelled as MUNCHEN, but its REAL_NAME value should be MÜNCHEN. In the area table for Germany, areas with name MÜNCHEN and MUNCHEN both refer to the same area, and they both have the same real name MÜNCHEN. If the area name does not have any non-English characters, set REAL_NAME to be the same as AREA_ NAME. (Required) IS_ALIAS VARCHAR2(1) Contains T if this area is an alias of another area that is an officially recognized administrative area; contains F if this area is not an alias of another area that is an officially recognized administrative area. For example, Manhattan is not an officially recognized administrative area, but it is used by the public to refer to a part of New York City. In this case, Manhattan is an alias of New York City. (Required) NUM_STREETS NUMBER The number of streets inside this area. (Optional) Table 11–8 (Cont.) GC_AREA_ Table Column Name Data Type Description Data Structures for Geocoding 11-14 Oracle Spatial Developer's Guide 11.5.3 GC_COUNTRY_PROFILE Table The GC_COUNTRY_PROFILE table stores country profile information used by the geocoder. This information includes administrative-area hierarchy definitions, the national languages, and the table-name suffix used by the data tables and their indexes. This table contains one row for each supported country, and it contains the columns shown in Table 11–9. Table 11–9 GC_COUNTRY_PROFILE Table Column Name Data Type Description COUNTRY_ NAME VARCHAR2(60) Country name. (Required) COUNTRY_ CODE_3 VARCHAR2(3) 3- letter ISO country code. (Required) COUNTRY_ CODE_2 VARCHAR2(2) 2- letter ISO country code. (Required) LANG_CODE_1 VARCHAR2(3) 3-letter ISO national language code. Some countries might have multiple national languages, in which case LANG_CODE_2 and perhaps other LANG_CODE_n columns should contain values. (Required) LANG_CODE_2 VARCHAR2(3) 3-letter ISO national language code. (Optional) LANG_CODE_3 VARCHAR2(3) 3-letter ISO national language code. (Optional) LANG_CODE_4 VARCHAR2(3) 3-letter ISO national language code. (Optional) NUMBER_ ADMIN_LEVELS NUMBER(1) Number of administration hierarchy levels. A country can have up to 7 administration area levels, numbered from 1 to 7 (largest to smallest). The top level area (country) is level 1. For the United States, the administration hierarchy is as follows: level 1 = country, level 2 = state, level 3 = county, level 4 = city. (Required) SETTLEMENT_ LEVEL NUMBER(1) Administration hierarchy level for a settlement, which is the lowest area level used in addressing. In the United States, this is the city level; in Europe, this is generally a subdivision of a city (level 5). (Required) MUNICIPALITY_ LEVEL NUMBER(1) Administration hierarchy level for a municipality, which is the second-lowest area level used in addressing. In the United States, this is the county (level 3); in Europe, this is generally a city (level 4). (Optional) REGION_LEVEL NUMBER(1) Administrative level for the region, which is above the municipality level. In the United States, this is the state or third-lowest area level used in addressing (level 2); in Europe, this is a recognized subdivision of the country (level 2 or level 3). (Optional) SETTLEMENT_IS_ OPTIONAL VARCHAR2(1) Contains T if settlement information is required in the address data; contains F if settlement information is not required in the address data. (Required) MUNICIPALITY_ IS_OPTIONAL VARCHAR2(1) Contains T if municipality information is required in the address data; contains F if municipality information is not required in the address data. (Required) REGION_IS_ OPTIONAL VARCHAR2(1) Contains T if region information is required in the address data; contains F if region information is not required in the address data. (Required) Data Structures for Geocoding Geocoding Address Data 11-15 11.5.4 GC_INTERSECTION_ Table The GC_INTERSECTION_ table (for example, GC_INTERSECTION_US) stores information on road intersections for the country or group of countries associated with the table-name suffix. An intersection occurs when roads meet or cross each other. This table contains the columns shown in Table 11–10. POSTCODE_IN_ SETTLEMENT VARCHAR(1) Contains T if each postal code must be completely within a settlement area; contains F if a postal code can include areas from multiple settlements. (Required) SETTLEMENT_ AS_CITY VARCHAR(1) Contains T if a city name can identify both a municipality and a settlement; contains F if a city name can identify only a settlement. For example, in the United Kingdom, London can be both the name of a municipality area and the name of a settlement area, which is inside the municipality of London. This is common in large cities in some European countries, such as the UK and Belgium. (Required) CACHED_ ADMIN_AREA_ LEVEL NUMBER (Reserved for future use.) GC_TABLE_ SUFFIX VARCHAR2(5) Table name suffix identifying the country for the GC_* data tables. For example, if the value of GC_TABLE_ SUFFIX is US, the names of tables with geocoding data for this country end with _US (for example, CG_ AREA_US). (Required) CENTER_LONG NUMBER Longitude value of the center of the area. (Optional) CENTER_LAT NUMBER Latitude value of the center of the area. (Optional) SEPARATE_ PREFIX VARCHAR2(1) Contains T if the street name prefix is a separate word from the street name; contains F if the street name prefix is in the same word with the street name. For example, in an American street address of 123 N Main St, the prefix is N, and it is separate from the street name, which is Main. (Optional; not currently used by Oracle) SEPARATE_ SUFFIX VARCHAR2(1) Contains T if the street name suffix is a separate word from the street name; contains F if the street name suffix is in the same word with the street name. For example, in an American street address of 123 Main St NW, the suffix is NW, and it is separate from the street name, which is Main, and from the street type, which is St. (Optional; not currently used by Oracle) SEPARATE_ STYPE VARCHAR2(1) Contains T if the street type is a separate word from the street name; contains F if the street type is in the same word with the street name. For example, in a German street address of 123 Beethovenstrass, the type is strass, and it is in the same word with the street name, which is Beethoven. (Optional; not currently used by Oracle) AREA_ID NUMBER Not currently used by Oracle. (Optional) VERSION VARCHAR2(10) Version of the data. The first version should be 1.0. (Required) Table 11–9 (Cont.) GC_COUNTRY_PROFILE Table Column Name Data Type Description Data Structures for Geocoding 11-16 Oracle Spatial Developer's Guide 11.5.5 GC_PARSER_PROFILES Table The GC_PARSER_PROFILES table stores information about keywords typically found in postal addresses. The geocoder uses keywords to identify address fields, such as house number, road name, city name, state name, and postal code. A keyword can be the type of street (such as road, street, drive, or avenue) or the prefix or suffix of a street (such as north, south, east, or west). This table contains the columns shown in Table 11–11. Table 11–10 GC_INTERSECTION_ Table Column Name Data Type Description ROAD_ID_1 NUMBER ID number of the first road on which the intersection is located. (Required) ROAD_ SEGMENT_ID_1 NUMBER ID number of the road segment on the first road on which the intersection is located. (Required) ROAD_ID_2 NUMBER ID number of the second road on which the intersection is located. (Required) ROAD_ SEGMENT_ID_2 NUMBER ID number of the road segment on the second road on which the intersection is located. (Required) INTS_LONG NUMBER Longitude coordinate value of the intersection. (Required) INTS_LAT NUMBER Latitude coordinate value of the intersection. (Required) HOUSE_NUMBER NUMBER The leading numerical part of the house number at the intersection. (See the explanation of house numbers after Table 11–16 in Section 11.5.10.) (Required) HOUSE_ NUMBER_2 VARCHAR2(10) The second part of the house number at the intersection. (See the explanation of house numbers after Table 11–16 in Section 11.5.10.) (Required) SIDE VARCHAR2(1) Side of the street on which the house at the intersection is located. Possible values: L (left) or R (right). (Required) COUNTRY_ CODE_2 VARCHAR2(2) 2- letter ISO country code of the country to which the house at the intersection belongs. (Required) PARTITION_ID NUMBER Partition key used for partitioning geocoder data by geographic boundaries. If the data is not partitioned, set the value to 1. (Required) Table 11–11 GC_PARSER_PROFILES Table Column Name Data Type Description COUNTRY_ CODE VARCHAR2(2) 2- letter ISO country code of the country for the keyword. (Required) Data Structures for Geocoding Geocoding Address Data 11-17 KEYWORDS SDO_ KEYWORDARRAY A single array of keywords for a specific address field. The array may contain a single word, or a group of words and abbreviations that can be used with the same meaning; for example, United States of America, USA, and United States all refer to the US. The first word of this array should be the official full name of the keyword, if there is any. The US uses over 400 keywords in parsing addresses. The following are some examples of keyword arrays and keywords from the US data set; however, only a single SDO_ KEYWORDARRAY object is stored in each row: SDO_KEYWORDARRAY( 'UNITED STATES OF AMERICA','US', 'USA', 'UNITED STATES', 'U.S.A.', 'U.S.') SDO_KEYWORDARRAY('AVENUE','AV', 'AVE', 'AVEN', 'AVENU', 'AVN', 'AVNUE', 'AV.','AVE.') SDO_KEYWORDARRAY('40TH', 'FORTIETH') SDO_KEYWORDARRAY('NEW YORK’,'NY') SDO_KEYWORDARRAY('LIBRARY') OUTPUT_ KEYWORD VARCHAR2(2000) A keyword used in the geocoder data to represent an address field. It must be the same as one of the keywords used in the keyword array. The output keyword is used to match the addresses stored in the geocoding data tables to the user’s input, for example, if the output keyword AV is used for street type Avenue in the GC_ROAD_US table, wherever a user enters an address containing any of the keywords (AVENUE, AV, AVE, AVEN, AVENU, AVN, AVNUE, AV., AVE.), the keyword will be interpreted and matched to the output keyword AV to help find the address in the database The following are some examples of output keywords; however, only a single output keyword is stored in each row: US AV 40TH NY LIBRARY Table 11–11 (Cont.) GC_PARSER_PROFILES Table Column Name Data Type Description Data Structures for Geocoding 11-18 Oracle Spatial Developer's Guide SECTION_ LABEL VARCHAR2(30) A label used to identify the type of keyword represented in the KEYWORDS and OUTPUT_ KEYWORD columns. There are the multiple different section labels; however, only a single section label for each row is used in identifying the type of keywords: COUNTRY_NAME: Identifies keywords that are used to represent country names. LOCALITY_KEYWORD_DICTIONARY: Identifies keywords that are used to replace words in a locality (city, state, province, and so on) with a standardized form of the word. For example, Saint is replaced by St; and by doing so, the city names Saint Thomas and St. Thomas will be standardized to St Thomas, which is stored in the database. PLACE_NAME_KEYWORD: Identifies a point of interest (POI) name keyword, such as for a restaurant or a hotel. REGION_LIST: Identifies keywords that are known names of regions, such as NY, New York, NH, and New Hampshire. The regions identified must be administrative areas that belong to the third-lowest area level or third-smallest area used in addressing. In the US this is the state level (the lowest area level or smallest area is the city level). SECOND_UNIT_KEYWORD: Identifies keywords used in second-unit descriptions, such as Floor, #, Suite, and Apartment. STREET_KEYWORD_DICTIONARY: Identifies keywords used to replace non-street-type keywords in street names (such as 40TH and Fortieth) with a standardized form. STREET_PREFIX_KEYWORD: Identifies street name prefix keywords, such as South, North, West, and East. STREET_TYPE_KEYWORD: Identifies street type keywords, such as Road, Street, and Drive. IN_LINE_STREET_TYPE_KEYWORD: Identifies street type keywords that are attached to street names, such as strasse in the German street name Steinstrasse. POSITION VARCHAR2(1) The position of the keyword relative to a street name. It indicates whether the keyword can precede (P) or follow (F) the actual street name, or both (B). Thus, P, F, and B are the only valid entries. In the US, most street type keywords follow the street names, for example, the street type Blvd in Hollywood Blvd. In France, however, street type keywords usually precede the street names, for example, the street type Avenue in Avenue De Paris. SEPARATENESS VARCHAR2(1) Indicates whether the keyword is separate from a street name. Keywords are either separable (S) or non-separable (N). Thus, S and N are the only valid entries. In the US, all street-type keywords are separate words from the street name, for example, the street type Blvd in Hollywood Blvd. In Germany, however, the street-type keywords are not separate from the street name, for example, the street type strasse in Augustenstrasse. Table 11–11 (Cont.) GC_PARSER_PROFILES Table Column Name Data Type Description Data Structures for Geocoding Geocoding Address Data 11-19 11.5.6 GC_PARSER_PROFILEAFS Table The GC_PARSER_PROFILEAFS table stores the XML definition of postal-address formats. An XML string describes each address format for a specific country. In the Oracle Geocoder 10g and earlier, the J2EE geocoder uses a country_name.ppr file instead of this table. The content of the country_name.ppr file is equivalent to the content of the ADDRESS_FORMAT_STRING attribute. This table contains the columns shown in Table 11–12. Example 11–4 shows the ADDRESS_FORMAT_STRING definition for the US address format. Example 11–4 XML Definition for the US Address Format Table 11–12 GC_PARSER_PROFILEAFS Table Column Name Data Type Description COUNTRY_CODE VARCHAR2(2) 2- letter ISO country code of the country. (Required) ADDRESS_FORMAT_ STRING CLOB XML string describing the address format for the country specified in the COUNTRY_CODE column. (Example 11–4 shows the XML definition for the US address format, and Section 11.5.6.1 explains the elements used in the US address format definition.). Data Structures for Geocoding 11-20 Oracle Spatial Developer's Guide 11.5.6.1 ADDRESS_FORMAT_STRING Description The ADDRESS_FORMAT_STRING column of the GC_PARSER_PROFILEAFS table describes the format of address fields and their positioning in valid postal addresses. The address format string is organized by address lines, because postal addresses are typically written in multiple address lines. The address parser uses the format description defined in the XML address format, combined with the keyword definition for each address field defined in the GC_ PARSER_PROFILES table, to parse the input address and identify individual address fields. Element The element includes the unit_separator and replace_ hyphen attributes. The unit_separator attribute is used to separate fields in the stored data. By default it is a comma (unit_separator=","). The replace_ hyphen attribute specifies whether to replace all hyphens in the user’s input with a space. By default it is set to true (replace_hyphen="true"), that is, it is expected that all names in the data tables will contain a space instead of a hyphen. Data Structures for Geocoding Geocoding Address Data 11-21 If replace_hyphen="true", administrative-area names in the data tables containing hyphens will not be matched during geocoding if replace_ hyphen="true"; however, these area names with hyphens can be placed in the REAL_NAME column of the GC_AREA table to be returned as the administrative-area name in the geocoded result. Road names in the NAME column of the GC_ROAD table containing hyphens will, however, be matched during geocoding, but the matching performance will be degraded Elements Each element in the XML address format string describes the format of an address line. Each element can have one or more child elements describing the individual address fields, such as street address, city, state (region or province), and postal code. These address field elements are listed in the order that the address fields appear in valid postal addresses. The optional attribute of the address field element is set to "no" if the address field is mandatory. By default, address field elements are optional. Elements The format descriptions for house number, special street name, post box, and postal code elements are specified with a single or multiple elements. Each element specifies a valid layout and range of values for a particular address field. The following example illustrates the format used to define a special street name: The form attribute uses a regular expression-like string to describe the format: 1 stands for any alphabetic letter; 0 stands for any numerical digit; 2 stands for any alphabetic letter or any numerical digit; 1* specifies a sting consisting of all alphabetic letters; 0* specifies a string consisting of all numerical digits; 2* specifies a string consisting of any combination of numerical digits and alphabetic letters. All other symbols represent themselves. Any string matching the pattern specified by the form attribute is considered to be a valid string for its (parent) address field. A valid string can then be broken down into segments specified by the attributes effective and addon_effective. The effective attribute specifies the more important, primary piece of the address string; the addon_effective attribute specifies the secondary piece of the address string. ■ The effective attribute specifies a substring of the full pattern using the start and end positions for the end descriptor of the form attribute. In the preceding example, effective="7-8" retrieves the substring (counting from position 0) starting at position 7 and ending at position 8, which is the substring defined by 0*, at the end of the form attribute. ■ The addon_effective attribute specifies a substring of the full pattern using the start and end positions for the start descriptor of the form attribute. In the preceding example, addon_effective="0-1" retrieves the substring, (counting from position 0) starting at position 0 and ending at position 1, which is the sub-string defined by 1*, at the beginning of the form attribute. The output and addon_output attributes specify the output form of the address string for segments specified by the effective and addon_effective attributes, Data Structures for Geocoding 11-22 Oracle Spatial Developer's Guide respectively. These output forms are used during address matching. The symbol $ stands for the matched string, and other symbols represent themselves. In the preceding example: ■ In output="$", the $ stands for the substring that was matched in the effective attribute. ■ In addon_output="$ HIGHWAY", the $ HIGHWAY stands for the substring that was matched in the addon_effective attribute, followed by a space, followed by the word HIGHWAY. Using the element in the preceding example, with form="1* HWY 0*", the input string ’STATE HWY 580’ will have effective=580, output=580, addon_ effective=STATE, and addon_output=STATE HIGHWAY. The element may also contain an element. The element specifies a string that has a valid form, but must be excluded from the address field. For example, in a element with valid numbers 0*1* (that is, any numeric digits followed by any alphabetic letters), specifying means that any house number with (or without) numeric digits and ending with "TH" must be excluded. 11.5.7 GC_POI_ Table The GC_POI_ table (for example, GC_POI_US) stores point of interest (POI) information for the country or group of countries associated with the table name suffix. POIs include features such as airports, monuments, and parks. This table contains one or more rows for each point of interest. (For example, it can contain multiple rows for a POI if the POI is associated with multiple settlements.) The GC_ POI_ table contains the columns shown in Table 11–13. Table 11–13 GC_POI_ Table Column Name Data Type Description POI_ID NUMBER ID number of the POI. (Required) POI_NAME VARCHAR2(64) Name of the POI. (Required) LANG_CODE VARCHAR2(3) 3-letter ISO national language code for the language for the POI name. (Required) FEATURE_CODE NUMBER Feature code for the POI, if the data vendor classifies POIs by category. (Optional) HOUSE_NUMBER VARCHAR2(10) House number of the POI; may contain non-numeric characters. (Required) STREET_NAME VARCHAR2(80) Road name of the POI. (Required) SETTLEMENT_ID NUMBER(10) ID number of the settlement to which the POI belongs. (Required if the POI is associated with a settlement) MUNICIPALITY_ ID NUMBER(10) ID number of the municipality to which the POI belongs. (Required if the POI is associated with a municipality) REGION_ID NUMBER(10) ID number of the region to which the POI belongs. (Required if the POI is associated with a region) SETTLEMENT_ NAME VARCHAR2(64) Name of the settlement to which the POI belongs. (Required if the POI is associated with a settlement) MUNICIPALITY_ NAME VARCHAR2(64) Name of the municipality to which the POI belongs. (Required if the POI is associated with a municipality) Data Structures for Geocoding Geocoding Address Data 11-23 11.5.8 GC_POSTAL_CODE_ Table The GC_POSTAL_CODE_ table (for example, GC_POSTAL_CODE_US) stores postal code information for the country or group of countries associated with the table-name suffix, if postal codes are used in the address format. This table contains one or more rows for each postal code; it may contain multiple rows for a postal code when the postal code is associated with multiple settlements. The GC_POSTAL_ CODE_ table contains the columns shown in Table 11–14. REGION_NAME VARCHAR2(64) Name of the region to which the POI belongs. (Required if the POI is associated with a region) POSTAL_CODE VARCHAR2(16) Postal code of the POI. (Required) VANITY_CITY VARCHAR2(35) Name of the city popularly associated with the POI, if it is different from the actual city containing the POI. For example, the London Heathrow Airport is actually located in a town named Hayes, which is part of greater London, but people tend to associate the airport only with London. In this case, the VANITY_CITY value is London. (Optional) ROAD_ SEGMENT_ID NUMBER ID of the road segment on which the POI is located. (Required) SIDE VARCHAR2(1) Side of the street on which the POI is located. Possible values: L (left) or R (right). (Required) PERCENT NUMBER Percentage value at which the POI is located on the road. It is computed by dividing the distance from the street segment start point to the POI by the length of the street segment. (Required) TELEPHONE_ NUMBER VARCHAR2(20) Telephone number of the POI. (Optional) LOC_LONG NUMBER Longitude coordinate value of the POI. (Required) LOC_LAT NUMBER Latitude coordinate value of the POI. (Required) COUNTRY_ CODE_2 VARCHAR2(2) 2- letter ISO country code of the country to which the POI belongs. (Required) PARTITION_ID NUMBER Partition key used for partitioning geocoder data by geographic boundaries. If the data is not partitioned, set the value to 1. (Required) Table 11–14 GC_POSTAL_CODE_ Table Column Name Data Type Description POSTAL_CODE VARCHAR2(16) Postal code for the postal code area. (Required) SETTLEMENT_ NAME VARCHAR2(64) Name of the settlement to which the postal code belongs. (Required if the postal code is associated with a settlement) MUNICIPALITY_ NAME VARCHAR2(64) Name of the municipality to which the postal code belongs. (Required if the postal code is associated with a municipality) REGION_NAME VARCHAR2(64) Name of the region to which the postal code belongs. (Required if the postal code is associated with a region) Table 11–13 (Cont.) GC_POI_ Table Column Name Data Type Description Data Structures for Geocoding 11-24 Oracle Spatial Developer's Guide 11.5.9 GC_ROAD_ Table The GC_ROAD_ table (for example, GC_ROAD_US) stores road information for the country associated with the table name suffix. A road is a collection of road segments with the same name in the same settlement area; a road segment is defined in Section 11.5.10. The GC_ROAD_ table contains one or more rows for each road. (For example, it can contain multiple rows for a road if the road is associated with multiple settlements.) The GC_ROAD_ table contains the columns shown in Table 11–15. LANG_CODE VARCHAR2(3) 3-letter ISO national language code for the language associated with the area. (Required) SETTLEMENT_ID NUMBER(10) ID number of the settlement to which the postal code belongs. (Required if the postal code is associated with a settlement) MUNICIPALITY_ ID NUMBER(10) ID number of the municipality to which the postal code belongs. (Required if the postal code is associated with a municipality) REGION_ID NUMBER(10) ID number of the region to which the postal code belongs. (Required if the postal code is associated with a region) CENTER_LONG NUMBER Longitude value of the center of the postal-code area. The center (longitude, latitude) value is set to the start- or end-point of the closest road segment to the center, depending on which point is closer. Oracle recommends that the CENTER_LONG and CENTER_ LAT values be correctly set. If these values are not set, the longitude, latitude values of the geocoded result for an area will be (0,0). (Optional) CENTER_LAT NUMBER Latitude value of the center of the area. (See the explanation for the CENTER_LONG column.) (Optional) ROAD_ SEGMENT_ID NUMBER(10) ID of the road segment to which the area center is set. This value must be set correctly if the geocoder is intended to work with the Oracle Spatial routing engine (described in Chapter 13); otherwise, it can be set to any nonzero value, but it cannot be null. (Required) COUNTRY_ CODE_2 VARCHAR2(2) 2- letter ISO country code of the country to which the area belongs. (Required) PARTITION_ID NUMBER Partition key used for partitioning geocoder data by geographic boundaries. If the data is not partitioned, set the value to 1. (Required) NUM_STREETS NUMBER The number of streets inside this postal code area. (Optional) Table 11–15 GC_ROAD_ Table Column Name Data Type Description ROAD_ID NUMBER ID number of the road. (Required) SETTLEMENT_ID NUMBER(10) ID number of the settlement to which the road belongs. (Required if the road is associated with a settlement) Table 11–14 (Cont.) GC_POSTAL_CODE_ Table Column Name Data Type Description Data Structures for Geocoding Geocoding Address Data 11-25 MUNICIPALITY_ ID NUMBER(10) ID number of the municipality to which the road belongs. (Required if the road is associated with a municipality) PARENT_AREA_ ID NUMBER(10) ID number of the parent area of the municipality to which the road belongs. (Required if the road is associated with a parent area) LANG_CODE VARCHAR2(3) 3-letter ISO national language code for the language for the road name. (Required) NAME VARCHAR2(64) Name of the road, including the type (if any), the prefix (if any), and the suffix (if any). For example, N Main St as NAME. (Required) BASE_NAME VARCHAR2(64) Name of the road, excluding the type (if any), the prefix (if any), and the suffix (if any). For example, N Main St as NAME, with Main as BASE_NAME. (Required) PREFIX VARCHAR2(32) Prefix of the road name. For example, N Main St as NAME, with N as PREFIX. (Required if the road name has a prefix) SUFFIX VARCHAR2(32) Suffix of the road name. For example, Main St NW as NAME, with NW as SUFFIX. (Required if the road name has a suffix) STYPE_BEFORE VARCHAR2(32) Street type that precedes the base name. For example, Avenue Victor Hugo as NAME, with Avenue as STYPE_BEFORE and Victor Hugo as BASE_NAME. (Required if the road type precedes the base name) STYPE_AFTER VARCHAR2(32) Street type that follows the base name. For example, Main St as NAME, with St as STYPE_AFTER and Main as BASE_NAME. (Required if the road type follows the base name) STYPE_ ATTACHED VARCHAR2(1) Contains T if the street type is in the same word with the street name; contains F if the street type is a separate word from the street name. For example, in a German street address of 123 Beethovenstrass, the street type is strass, and it is in the same word with the street name, which is Beethoven. (Required) START_HN NUMBER(5) The lowest house number on the road. It is returned when a specified house number is lower than this value. CENTER_HN NUMBER(5) Leading numerical part of the center house number. The center house number is the left side house number at the start point of the center road segment, which is located in the center of the whole road. (See the explanation of house numbers after Table 11–16 in Section 11.5.10.) It is returned when no house number is specified in an input address. (Required) END_HN NUMBER(5) The highest house number on the road. It is returned when a specified house number is higher than this value. START_HN_SIDE VARCHAR2(1) Side of the road of the lowest house number: L for left or R for right. Table 11–15 (Cont.) GC_ROAD_ Table Column Name Data Type Description Data Structures for Geocoding 11-26 Oracle Spatial Developer's Guide 11.5.10 GC_ROAD_SEGMENT_ Table The GC_ROAD_SEGMENT_ table (for example, GC_ROAD_SEGMENT_US) stores road segment information for the country associated with the table name suffix. A road segment is the portion of a road between two continuous intersections along the road; an intersection occurs when roads meet or cross each other. A road segment can also be the portion of a road between the start (or end) of the road and its closest intersection along the road, or it can be the entire length of a road if there are no intersections along the road. The GC_ROAD_SEGMENT_ table contains one row for each road segment, and it contains the columns shown in Table 11–16. CENTER_HN_ SIDE VARCHAR2(1) Side of the road of the center house number: L for left or R for right. The center house number is the left side house number at the start point of the center road segment, which is located in the center of the whole road. (See the explanation of house numbers after Table 11–16 in Section 11.5.10.) (Required if there are houses on the road) END_HN_SIDE VARCHAR2(1) Side of the road of the highest house number: L for left or R for right. START_LONG NUMBER Longitude value of the lowest house number. START_LAT NUMBER Latitude value of the lowest house number. CENTER_LONG NUMBER Longitude value of the center house number. The center house number is the left side house number at the start point of the center road segment, which is located in the center of the whole road. (See the explanation of house numbers after Table 11–16 in Section 11.5.10.) (Required) CENTER_LAT NUMBER Latitude value of the center house number. (See also the explanation of the CENTER_LONG column.) (Required) END_LONG NUMBER Longitude value of the highest house number. END_LAT NUMBER Latitude value of the highest house number. START_ROAD_ SEG_ID NUMBER(5) ID number of the road segment at the start of the road. CENTER_ROAD_ SEG_ID NUMBER(5) ID number of the road segment at the center point of the road. (Required) END_ROAD_ SEG_ID NUMBER(5) ID number of the road segment at the end of the road. POSTAL_CODE VARCHAR2(16) Postal code for the road. (Required) COUNTRY_ CODE_2 VARCHAR2(2) 2- letter ISO country code of the country to which the road belongs. (Required) PARTITION_ID NUMBER Partition key used for partitioning geocoder data by geographic boundaries. If the data is not partitioned, set the value to 1. (Required) CENTER_HN2 VARCHAR2(10) The second part of the center house number. (See the explanation of house numbers after Table 11–16 in Section 11.5.10.) (Required) Table 11–15 (Cont.) GC_ROAD_ Table Column Name Data Type Description Data Structures for Geocoding Geocoding Address Data 11-27 Table 11–16 GC_ROAD_SEGMENT_ Table Column Name Data Type Description ROAD_ SEGMENT_ID NUMBER ID number of the road segment. (Required) ROAD_ID NUMBER ID number of the road containing this road segment. (Required) L_ADDR_ FORMAT VARCHAR2(1) Left side address format. Specify N if there are one or more house numbers on the left side of the road segment; leave null if there is no house number on the left side of the road segment. (Required) R_ADDR_ FORMAT VARCHAR2(1) Right side address format. Specify N if there are one or more house numbers on the right side of the road segment; leave null if there is no house number on the right side of the road segment. (Required) L_ADDR_ SCHEME VARCHAR2(1) Numbering scheme for house numbers on the left side of the road segment: O (all odd numbers), E (all even numbers), or M (mixture of odd and even numbers). (Required) R_ADDR_ SCHEME VARCHAR2(1) Numbering scheme for house numbers on the right side of the road segment: O (all odd numbers), E (all even numbers), or M (mixture of odd and even numbers). (Required) START_HN NUMBER(5) The lowest house number on this road segment. (Required) END_HN NUMBER(5) The highest house number on this road segment. (Required) L_START_HN NUMBER(5) The leading numerical part of the left side starting house number. (See the explanation of house numbers after this table.) (Required) L_END_HN NUMBER(5) The leading numerical part of the left side ending house number. (See the explanation of house numbers after this table.) (Required) R_START_HN NUMBER(5) The leading numerical part of the right side starting house number. (See the explanation of house numbers after this table.) (Required) R_END_HN NUMBER(5) The leading numerical part of the right side ending house number. (See the explanation of house numbers after this table.) (Required) POSTAL_CODE VARCHAR2(16) Postal code for the road segment. If the left side and right side of the road segment belong to two different postal codes, create two rows for the road segment with identical values in all columns except for POSTAL_ CODE. (Required) GEOMETRY SDO_ GEOMETRY Spatial geometry object representing the road segment. (Required) COUNTRY_ CODE_2 VARCHAR2(2) 2- letter ISO country code of the country to which the road segment belongs. (Required) PARTITION_ID NUMBER Partition key used for partitioning geocoder data by geographic boundaries. If the data is not partitioned, set the value to 1. (Required) Data Structures for Geocoding 11-28 Oracle Spatial Developer's Guide A house number is a descriptive part of an address that helps identify the location of a establishment along a road segment. A house number is divided into two parts: the leading numerical part and the second part, which is the rest of the house number. The leading numerical part is the numerical part of the house number that starts from the beginning of the complete house number string and ends just before the first non-numeric character (if present). If the house number contains non-numeric characters, the second part of the house number is the portion from the first non-numeric character through the last character of the string. For example, if the house number is 123, the leading numerical part is 123 and the second part is null; however, if the house number is 123A23, the leading numerical part is 123 and the second part is A23. The starting house number is the house number at the start point of a road segment; the start point of the road segment is the first shape point of the road segment geometry. The ending house number is the house number at the end point of a road segment; the end point of the road segment is the last shape point of the road segment geometry. The left and right side starting house numbers do not need to be lower than the left and right side ending house numbers. The house number attributes in the data tables follow these conventions in locating establishments along road segments. 11.5.11 Indexes on Tables for Geocoding To use the vendor-supplied tables for geocoding, indexes must be created on many of the tables, and the names of these indexes must follow certain requirements. Example 11–5 lists the format of CREATE INDEX statements that create the required indexes. In each statement, you must use the index name, table name, column names, and (if multiple columns are indexed) sequence of column names as shown in Example 11–5, except that you must replace all occurrences of with the appropriate string (for example, US for the United States). Note that the first index in the example is a spatial index. Optionally, you can also include other valid keywords and clauses in the CREATE INDEX statements. Example 11–5 Required Indexes on Tables for Geocoding CREATE INDEX idx__road_geom ON gc_road_segment_ (geometry) INDEXTYPE IS mdsys.spatial_index; L_START_HN2 VARCHAR2(10) The second part of the left side starting house number. (See the explanation of house numbers after this table.) (Required if the left side starting house number has a second part) L_END_HN2 VARCHAR2(10) The second part of the left side ending house number. (See the explanation of house numbers after this table.) (Required if the left side ending house number has a second part) R_START_HN2 VARCHAR2(10) The second part of the right side starting house number. (See the explanation of house numbers after this table.) (Required if the right side starting house number has a second part) R_END_HN2 VARCHAR2(10) The second part of the right side ending house number. (See the explanation of house numbers after this table.) (Required if the right side ending house number has a second part) Table 11–16 (Cont.) GC_ROAD_SEGMENT_ Table Column Name Data Type Description Installing the Profile Tables Geocoding Address Data 11-29 CREATE INDEX idx__road_seg_rid ON gc_road_segment_ (road_id, start_hn, end_hn); CREATE INDEX idx__road_id ON gc_road_ (road_id); CREATE INDEX idx__road_setbn ON gc_road_ (settlement_id, base_name); CREATE INDEX idx__road_munbn ON gc_road_ (municipality_id, base_name); CREATE INDEX idx__road_parbn ON gc_road_ (parent_area_id, country_code_2, base_ name); CREATE INDEX idx__road_setbnsd ON gc_road_ (settlement_id, soundex(base_name)); CREATE INDEX idx__road_munbnsd ON gc_road_ (municipality_id, soundex(base_name)); CREATE INDEX idx__road_parbnsd ON gc_road_ (parent_area_id, country_code_2, soundex(base_name)); CREATE INDEX idx__inters ON gc_intersection_ (country_code_2, road_id_1, road_id_ 2); CREATE INDEX idx__area_name_id ON gc_area_ (country_code_2, area_name, admin_ level); CREATE INDEX idx__area_id_name ON gc_area_ (area_id, area_name, country_code_2); CREATE INDEX idx__poi_name ON gc_poi_ (country_code_2, name); CREATE INDEX idx__poi_setnm ON gc_poi_ (country_code_2, settlement_id, name); CREATE INDEX idx__poi_ munnm ON gc_poi_ (country_code_2, municipality_id, name); CREATE INDEX idx__poi_ regnm ON gc_poi_ (country_code_2, region_id, name); CREATE INDEX idx__ postcode ON gc_postal_code_ (country_code_2, postal_code); CREATE INDEX idx__addrpt_addr ON gc_address_point_ (road_segment_id, road_id, house_number, side); 11.6 Installing the Profile Tables The Oracle Geocoder profile tables are typically supplied by a data provider. Use the data provider’s profile tables for geocoding whenever they are available. For users building their own geocoder schema, Oracle provides sample GC_COUNTRY_ PROFILE, GC_PARSER_PROFILES, and GC_PARSER_PROFILEAFS tables; however, you should install these Oracle-supplied profile tables only if profile tables are not supplied with the data tables. The Oracle-supplied tables contain parser profiles for a limited number of countries. If profiles for your country or group of countries of interest are not included, you will need to manually add them; and for a quick start, you can copy the parser profiles of a country with a similar address format to your country of interest, and edit these profiles where necessary. If your parser profiles of interest are included in the Oracle-supplied tables, you can use them directly or update them if necessary. No sample country profiles are provided, so you will need to add your own To install and query the Oracle-supplied profile tables, perform the following steps: 1. Log on to your database as the geocoder user. The geocoder user is the user under whose schema the geocoder schema will be loaded. 2. Create the GC_COUNTRY_PROFILE, GC_PARSER_PROFILES, and GC_ PARSER_PROFILEAFS tables by executing the SDO_GCDR.CREATE_PROFILE_ TABLES procedure: SQL> EXECUTE SDO_GCDR.CREATE_PROFILE_TABLES; 3. Populate the GC_PARSER_PROFILES and GC_PARSER_PROFILEAFS tables by running the sdogcprs.sql script in the $ORACLE_HOME/md/admin/ directory. For example: SQL> @$ORACLE_HOME/md/admin/sdogcprs.sql 4. Query the profile tables to determine if parser profiles for your country of interest are supplied, by checking if its country code is included in the output of the following statements: Using the Geocoding Service (XML API) 11-30 Oracle Spatial Developer's Guide SQL> SELECT DISTINCT(country_code) FROM gc_parser_profiles ORDER BY country_ code; SQL> SELECT DISTINCT(country_code) FROM gc_parser_profileafs ORDER BY country_ code; 11.7 Using the Geocoding Service (XML API) In addition to the SQL API, Oracle Spatial also provides an XML API for a geocoding service that enables you to geocode addresses. A Java geocoder application engine performs international address standardization, geocoding, and POI matching, by querying geocoder data stored in the Oracle database. The support for unparsed addresses adds flexibility and convenience to customer applications. This geocoding service is implemented as a Java 2 Enterprise Edition (J2EE) Web application that you can deploy in a WebLogic Server, Oracle Application Server, or standalone Oracle Application Server Containers for J2EE (OC4J) environment. ■ If the geocoding service is deployed in a standalone OC4J, the user name is oc4jadmin and the password is the administrator password you specified when you installed the OC4J instance. ■ If the geocoding service is deployed in a full Oracle Application Server, you must have created a security user in the OC4J instance where the geocoding service is running, and mapped the security user to the geocoding service's built-in security role GC_ADMIN_ROLE. After you have completed these tasks through Enterprise Manager, you can then use that security user's name and password to log in as the geocoding service administrator. Figure 11–1 shows the basic flow of action with the geocoding service: a client locates a remote geocoding service instance, sends a geocoding request, and processes the response returned by the geocoding service instance. Figure 11–1 Basic Flow of Action with the Spatial Geocoding Service As shown in Figure 11–1: 1. The client sends an XML geocoding request, containing one or more input addresses to be geocoded, to the geocoding service using the HTTP protocol. Oracle Spatial Geocoding Service Geocoding Client Geocoding Request: - Input addresses (one or more, formatted or unformatted) Geocoding Response: - Geocoded address or addresses (longitude, latitude, ...) (running in WebLogic Server, Oracle Application Server, or OC4J) Using the Geocoding Service (XML API) Geocoding Address Data 11-31 2. The geocoding service parses the input request and looks up the input address in the database. 3. The geocoding service sends the geocoded result in XML format to the client using the HTTP protocol. After you load the geocoder schema into the database, you must configure the J2EE geocoder before it can be used, as explained in Section 11.7.1 11.7.1 Deploying and Configuring the J2EE Geocoder The J2EE geocoder processes geocoding requests and generates responses. To enable this geocoding service, the geocoder.ear file (in $ORACLE_HOME/md/jlib) must be deployed using the Oracle WebLogic Server, Oracle Application Server (OracleAS), or a standalone installation of Oracle Application Server Containers for J2EE (OC4J). To deploy and configure the geocoding service, follow these steps. 1. Deploy the geocoder using Oracle Application Server or OC4J, or using Oracle WebLogic Server: ■ Using Oracle Application Server or OC4J: Deploy the geocoder.ear file in your $ORACLE_HOME/md/jlib directory using the OracleAS or the standalone OC4J Application Server Control (for example, http://:8888/em). You can deploy the geocoder.ear file in an existing OC4J instance, or you can create a new OC4J instance for the geocoder. In either case, enter geocoder for the Application Name during deployment. ■ Using Oracle WebLogic Server: Unpack the geocoder.ear file in your $ORACLE_HOME/md/jlib directory. Rename the geocoder.ear file and unpack its contents into a directory called ../geocoder.ear . Rename the web.war file now found under the $geocoder.ear/ directory and unpack its contents into a subdirectory called ../web.war . Your directory structure should therefore be $geocoder.ear/web.war/ . After unpacking the geocoder.ear and web.war files, copy the xmlparserv2.jar file in your $ORACLE_HOME/LIB/ directory into the $geocoder.ear/web.war/WEB-INF/lib/ directory. To deploy the geocoder.ear file, log on to the WLS console (for example, http://:7001/console); and from Deployments, install the geocoder.ear file, accepting the name geocoder for the deployment and choosing the option to make the deployment accessible from a specified location. 2. Launch the Oracle Geocoder welcome page in a Web browser using the URL http://:/geocoder . On the welcome page, select the Administration link and enter the administrator (oc4jadmin or weblogic) user name and password. Note: If you are not familiar with application deployment using either OracleAS or standalone OC4J, see the Oracle Application Server Administrator's Guide or the Oracle Containers for J2EE Configuration and Administration Guide. Using the Geocoding Service (XML API) 11-32 Oracle Spatial Developer's Guide 3. Modify the geocoder configuration file (geocodercfg.xml). Uncomment at least one element, and change the element attributes of that element to reflect the configuration of your database. For information about this file, see Section 11.7.1.1. 4. Save the changes to the file, and restart the geocoder. If the welcome page is not displayed, ensure that the newly deployed geocoding service was successfully started. It is assumed that you are running WebLogic Server 10.3.1.0 or later with an Oracle Database Release 11.2 or later geocoder.ear file; or that you are running Oracle AS or OC4J 10.1.3 or later with an Oracle 11g or later geocoder.ear file. 5. Test the database connection by going to the welcome page at URL http://:/geocoder and running the international postal address parsing/geocoding demo and the XML geocoding request page. (These demos require geocoder data for the United States.) Examples are available to demonstrate various capabilities of the geocoding service. Using the examples is the best way to learn the XML API, which is described in Section 11.7.2. 11.7.1.1 Configuring the geocodercfg.xml File You will need to edit the element in the default geocodercfg.xml file that is included with Spatial, to specify the database and schema where the geocoding data is loaded. In this file, each element defines the geocoder for the database in which the geocoder schema resides. The element defines the database connection for the geocoder. In Oracle 11g or later, there are two ways to define a database connection: by providing the JDBC database connection parameters, or by providing the JNDI name (container_ds) of a predefined container data source. Example 11–6 illustrates two different ways in which a element can be defined. The first definition specifies a JDBC connection; the second definition uses the JNDI name of a predefined container data source. Example 11–6 Element Definitions weblogic with your WebLogic Server administrator user name, for example, my_weblogic_admin. Using the Geocoding Service (XML API) Geocoding Address Data 11-33 load_db_parser_profiles="true" /> The attributes of the element are as follows ■ name is a descriptive name for the database connection; it is not used to connect to the database. ■ host, port, and sid identify the database. ■ mode identifies the type of JDBC driver to use for the connection. ■ user and password are the user name and password for the database user under whose schema the geocoding data is stored. ■ load_db_parser_profiles specifies whether to load the address parser profiles from the specified database connection. If true, the address parser-profiles are loaded from the geocoder schema; otherwise, the parser profiles are loaded from the application at ../applications/geocoder/web/WEB-INF/parser_ profiles/.ppr (for example, usa.ppr). Before Oracle 11g, parser profiles were loaded from the application only. This parameter should be set to true. ■ container_ds specifies the JNDI name for a predefined data source. 11.7.2 Geocoding Request XML Schema Definition and Example For a geocoding request (HTTP GET or POST method), it is assumed the request has a parameter named xml_request whose value is a string containing the XML document for the request. The input XML document describes the input addresses that need to be geocoded. One XML request can contain one or more input addresses. Several internationalized address formats are available for describing the input addresses. (The input XML API also supports reverse geocoding, that is, a longitude/latitude point to a street address.) The XML schema definition (XSD) for a geocoding request is as follows: Using the Geocoding Service (XML API) 11-34 Oracle Spatial Developer's Guide Using the Geocoding Service (XML API) Geocoding Address Data 11-35 Example 11–7 is a request to geocode several three addresses (representing two different actual physical addresses), using different address formats and an unformatted address. Example 11–7 Geocoding Request (XML API) Using the Geocoding Service (XML API) 11-36 Oracle Spatial Developer's Guide 11.7.3 Geocoding Response XML Schema Definition and Example A geocoding response contains one or more standardized addresses including longitude/latitude points, the matching code, and possibly multiple match and no match indication and an error message. The XML schema definition (XSD) for a geocoding response is as follows: Using the Geocoding Service (XML API) Geocoding Address Data 11-37 Example 11–8 is the response to the request in Example 11–7 in Section 11.7.2. Example 11–8 Geocoding Response (XML API) Using the Geocoding Service (XML API) 11-38 Oracle Spatial Developer's Guide 12 Business Directory (Yellow Pages) Support 12-1 12 Business Directory (Yellow Pages) Support This chapter describes Oracle Spatial support for OpenLS business directory (Yellow Pages, or YP) services. It includes the following major sections: ■ Section 12.1, "Business Directory Concepts" ■ Section 12.2, "Using the Business Directory Capabilities" ■ Section 12.3, "Data Structures for Business Directory Support" 12.1 Business Directory Concepts Business directory services provide lists of businesses in a given area and matching a specified name or category. Business directory data comes from third-party providers of such data. These providers probably have different business categories, and even different hierarchical structures. A unifying pattern in the various approaches is that businesses are categorized by subject and location. The location component is well understood; for example, for the United States, either a ZIP code or the combination of a city and state, and optionally a specific address, can be used to determine the location from which to start searching. The categorization of businesses, on the other hand, is not uniformly implemented. Some providers offer a flat list of categories, user-selected by simple substring matching. Others offer a 3-level or 4-level hierarchical organization of subcategories, often with a fanout (maximum number of child categories at a level) of 20 to 50, and sometimes more than 100. A user might start the hierarchy traversal at the root of the hierarchy (by default). Alternatively, a user might enter a keyword that is matched to an appropriate starting point within the hierarchy. Such keyword matching might go beyond simple substring matching and result in more intelligent choices. 12.2 Using the Business Directory Capabilities To use the Oracle Spatial business directory capabilities, you must use data provided by a geocoding vendor, and the data must be in the format supported by the Oracle Spatial OpenLS support. For information about getting and loading this data, go to the Spatial page of the Oracle Technology Network (OTN): http://www.oracle.com/technology/products/spatial/ Find the link for business directory (YP) support, and follow the instructions. To submit users’ directory services requests and to return the responses, use the OpenLS Web services API, which is introduced in Section 14.2. For information about directory services requests and responses, with examples, see Section 14.3. Data Structures for Business Directory Support 12-2 Oracle Spatial Developer's Guide 12.3 Data Structures for Business Directory Support After you acquire the business directory data and invoke the appropriate procedure to load it into the database, the procedure populates the following tables, all owned by the MDSYS schema, which are used for business directory support: ■ OPENLS_DIR_BUSINESSES ■ OPENLS_DIR_BUSINESS_CHAINS ■ OPENLS_DIR_CATEGORIES ■ OPENLS_DIR_CATEGORIZATIONS ■ OPENLS_DIR_CATEGORY_TYPES ■ OPENLS_DIR_SYNONYMS In some tables, some rows have null values for some columns, because the information does not apply in this instance or because the data provider did not supply a value. The following sections describe these tables, in alphabetical order by table name. 12.3.1 OPENLS_DIR_BUSINESSES Table The OPENLS_DIR_BUSINESSES table stores information about each business (that is, each business that has an address). If the business is part of a larger business chain, the CHAIN_ID column is a foreign key to the CHAIN_ID column in the OPENLS_DIR_ BUSINESS_CHAINS table (described in Section 12.3.2). The OPENLS_DIR_BUSINESSES table contains one row for each business, and it contains the columns shown in Table 12–1. Table 12–1 OPENLS_DIR_BUSINESSES Table Column Name Data Type Description BUSINESS_ID NUMBER Business ID number. (Required) BUSINESS_NAME VARCHAR2(128) Area name. (Required) CHAIN_ID NUMBER ID number of the business chain (in the OPENLS_ BIR_BUSINESS_CHAIN table), if the business is part of a chain. DESCRIPTION VARCHAR2(1024) Description of the business. PHONE VARCHAR2(64) Phone number, in an appropriate format for the location. COUNTRY VARCHAR2(64) Country code or name. (Required) COUNTRY_ SUBDIVISION VARCHAR2(128) Subdivision of the country, if applicable. COUNTRY_ SECONDARY_ SUBDIVISION VARCHAR2(128) Subdivision within COUNTRY_SUBDIVISION, if applicable. MUNICIPALITY VARCHAR2(128) Municipality name. MUNICIPALITY_ SUBDIVISION VARCHAR2(128) Subdivision within MUNICIPALITY, if applicable. POSTAL_CODE VARCHAR2(32) Postal code (for example, 5-digit ZIP code in the United Stated and Canada). (Required) POSTAL_CODE_ EXT VARCHAR2(32) Postal code extension (for example, 4-digit extension if the 5-4 ZIP code format is used). Data Structures for Business Directory Support Business Directory (Yellow Pages) Support 12-3 12.3.2 OPENLS_DIR_BUSINESS_CHAINS Table The OPENLS_DIR_BUSINESS_CHAINS table stores information about each business chain. A business chain is a business that has multiple associated businesses; for example, a restaurant chain has multiple restaurants that have the same name and offer basically the same menu. If the business is part of a business chain, the row for that business in the OPENLS_DIR_BUSINESSES table (described in Section 12.3.1) contains a CHAIN_ID column value that matches a value in the CHAIN_ID column in the OPENLS_DIR_BUSINESS_CHAINS table. The OPENLS_DIR_BUSINESS_CHAINS table contains one row for each business chain, and it contains the columns shown in Table 12–2. 12.3.3 OPENLS_DIR_CATEGORIES Table The OPENLS_DIR_CATEGORIES table stores information about each category into which a business can be placed. If the data provider uses a category hierarchy, this table contains rows for categories at all levels of the hierarchy, using the PARENT_ID column to indicate the parent category of a child category. For example, a Restaurants category might be the parent of several child categories, one of which might be Chinese. The OPENLS_DIR_CATEGORIES table contains one row for each category, and it contains the columns shown in Table 12–3. STREET VARCHAR2(128) Street address, including house or unit number. (Required) INTERSECTING_ STREET VARCHAR2(128) Name of the street (if any) that intersects STREET at this address. BUILDING VARCHAR2(128) Name of the building that includes this address. PARAMETERS XMLTYPE XML document with additional information about the business. GEOM SDO_GEOMETRY Point geometry representing the address of the business. Table 12–2 OPENLS_DIR_BUSINESS_CHAINS Table Column Name Data Type Description CHAIN_ID NUMBER Business chain ID number. (Required) CHAIN_NAME VARCHAR2(128) Business chain name. Table 12–3 OPENLS_DIR_CATEGORIES Table Column Name Data Type Description CATEGORY_ID VARCHAR2(32) Category ID string. (Required) CATEGORY_ TYPE_ID NUMBER Category type ID number. Must match a value in the CATEGORY_TYPE_ID column of the OPENLS_DIR_ CATEGORY_TYPES table (described in Section 12.3.5). (Required) CATEGORY_ NAME VARCHAR2(128) Category name. (Required) Table 12–1 (Cont.) OPENLS_DIR_BUSINESSES Table Column Name Data Type Description Data Structures for Business Directory Support 12-4 Oracle Spatial Developer's Guide 12.3.4 OPENLS_DIR_CATEGORIZATIONS Table The OPENLS_DIR_CATEGORIZATIONS table stores information about associations of businesses with categories. Each business can be in multiple categories; and the categories for a business can be independent of each other or in a parent-child relationship, or both. For example, a store that sells books and music CDs might be in the categories for Bookstores, Music, and its child category Music Stores, in which case there will be three rows for that business in this table. The OPENLS_DIR_CATEGORIZATIONS table contains one row for each association of a business with a category, and it contains the columns shown in Table 12–4. 12.3.5 OPENLS_DIR_CATEGORY_TYPES Table The OPENLS_DIR_CATEGORY_TYPES table stores information about category types. This table contains the columns shown in Table 12–5. PARENT_ID VARCHAR2(32) CATEGORY_ID value of the parent category, if any, for this category. PARAMETERS XMLTYPE XML document with additional information about the category. Table 12–4 OPENLS_DIR_CATEGORIZATIONS Table Column Name Data Type Description BUSINESS_ID NUMBER Business ID. Must match a value in the BUSINESS_ ID column of the OPENLS_DIR_BUSNESSES table (described in Section 12.3.1). (Required) CATEGORY_ID VARCHAR2(32) Category ID string. The CATEGORY_ID and CATEGORY_TYPE_ID values must match corresponding column values in a single row in the OPENLS_DIR_CATEGORIES table (described in Section 12.3.3). (Required) CATEGORY_TYPE_ ID NUMBER Category type ID number. The CATEGORY_ID and CATEGORY_TYPE_ID values must match corresponding column values in a single row in the OPENLS_DIR_CATEGORIES table (described in Section 12.3.3). (Required) CATEGORIZATION _TYPE VARCHAR2(8) EXPLICIT (the default) or IMPLICIT. USER_SPECIFIC_ CATEGORIZATION VARCHAR2(32) User-specified categorization, if any. PARAMETERS XMLTYPE XML document with additional information about the association of the business with the category. Table 12–5 OPENLS_DIR_CATEGORY_TYPES Table Column Name Data Type Description CATEGORY_TYPE_ID NUMBER Category type ID number. (Required) CATEGORY_TYPE_ NAME VARCHAR2(128) Name of the category type. (Required) PARAMETERS XMLTYPE XML document with additional information about the category type. Table 12–3 (Cont.) OPENLS_DIR_CATEGORIES Table Column Name Data Type Description Data Structures for Business Directory Support Business Directory (Yellow Pages) Support 12-5 12.3.6 OPENLS_DIR_SYNONYMS Table The OPENLS_DIR_SYNONYMS table stores information about synonyms for categories. Synonyms can be created to expand the number of terms (strings) associated with a category, so that users get more complete and meaningful results from a search. The OPENLS_DIR_SYNONYMS table contains one row for each synonym definition, and it contains the columns shown in Table 12–6. Table 12–6 OPENLS_DIR_SYNONYMS Table Column Name Data Type Description STANDARD_ NAME VARCHAR2(128) Standard name of a category, as the user might enter it. CATEGORY VARCHAR2(128) Category name, as it appears in the OPENLS_DIR_ CATEGORIES table (described in Section 12.3.3). AKA VARCHAR2(128) .Additional or alternate name for the category. ("AKA" stands for "also known as.") Data Structures for Business Directory Support 12-6 Oracle Spatial Developer's Guide 13 Routing Engine 13-1 13 Routing Engine The Spatial routing engine enables you to host an XML-based Web service that provides the following features: ■ For an individual route request (a start location and an end location): route information (driving distances, estimated driving times, and directions) between the two locations ■ For a batch route request (multiple routes, with the same start location but different end locations): route information (driving distance and estimated driving time) for each route For any request, the start and end locations are identified by addresses, geocoded results, or longitude/latitude coordinates. The routing engine is implemented as a Java 2 Enterprise Edition (J2EE) Web application that you can deploy in either an Oracle Application Server or standalone Oracle Application Server Containers for J2EE (OC4J) environment. Figure 13–1 shows the basic flow of action with the routing engine: a client locates a remote routing engine instance, sends a route request, and processes the route response returned by the routing engine instance. Figure 13–1 Basic Flow of Action with the Spatial Routing Engine This chapter contains the following major sections: Oracle Spatial Routing Engine Routing Client Route Request: - Preferences - Start Location - End Location or Batch Route Request: - Preferences - Start Location - End Locations Route Response: - Route Information - Segment Information (for each route segment) or Batch Route Response: - Route Information (for each route) (running in Oracle Application Server or OC4J) Deploying and Configuring the Routing Engine 13-2 Oracle Spatial Developer's Guide ■ Section 13.1, "Deploying and Configuring the Routing Engine" ■ Section 13.2, "Routing Engine XML API" ■ Section 13.3, "Data Structures Used by the Routing Engine" 13.1 Deploying and Configuring the Routing Engine To enable the routing engine to process routing requests and to generate responses, you must create a network (Oracle Database network data model network) on top of the routing data, and then deploy the routeserver.ear file using OC4J or the Oracle Application Server. This section describes the basic steps. 1. If a network with the routing data already exists, drop it, to ensure that all structures are "clean" in the network to be created. To drop the existing network, execute a statement in the following form: EXECUTE SDO_ROUTER_PARTITION.DELETE_ROUTER_NETWORK('', ''); is the name of the log file that was specified in the call to SDO_ ROUTER_PARTITION.DELETE_ROUTER_NETWORK to create the network to be dropped. is the name of the network to be dropped. For example: EXECUTE SDO_ROUTER_PARTITION.DELETE_ROUTER_NETWORK('create_sf_net.log', 'ndm_ sf_net'); 2. Create the network for the routing data by executing a statement in the following form: EXECUTE SDO_ROUTER_PARTITION.CREATE_ROUTER_NETWORK('', ''); is the name of the log file to use for this network. is the name of the network to be created. For example: EXECUTE SDO_ROUTER_PARTITION.CREATE_ROUTER_NETWORK('create_sf_net.log', 'ndm_ sf_net'); The log file initially contains messages similar to the following: INFO: creating the Routeserver network: NDM_SF_NET creating indexes creating views generating metadata 3. Add the following element inside the element in your http-web-site.xml or default-web-site.xml file of OC4J: Deploying and Configuring the Routing Engine Routing Engine 13-3 4. Use the Oracle Application Server console to deploy the routeserver.ear file, or add the following element inside the element in the server.xml file of OC4J (replace accordingly): 5. Add the following element inside the element in the server.xml file of OC4J: It is important to limit the number of concurrent requests that the Oracle Route Server can process at any given time to prevent java.lang.OutOfMemoryError errors. 6. Configure the web.xml file, as explained in Section 13.1.1. 7. Start OC4J using the following command options: -server -Xms -Xmx -XX:NewSize= -XX:MaxNewSize= -Dsun.rmi.dgc.server.gcInterval=3600000 -Dsun.rmi.dgc.client.gcInterval=3600000 -verbose:gc (optional) must be at least 512 MB, and has a recommended size of at least 1024 MB (1 GB). Make sure that this memory is physical memory and not virtual memory. should be one-fourth (25%) of the value. -verbose:gc will print all minor and major Java garbage collections. Monitoring these statistics could be useful for memory resource planning. If you find that garbage collections are occurring frequently or are lasting several seconds, you probably need to allocate more physical memory to the Java VM. The following command is an example that starts OC4J. Note that the -config flag is an OC4J command line parameter, not a VM option. c:\jdk1.5.0_06\bin\java -server -Xms1024m -Xmx1024m -XX:NewSize=256m -XX:MaxNewSize=256m -Dsun.rmi.dgc.server.gcInterval=3600000 -Dsun.rmi.dgc.client.gcInterval=3600000 -verbose:gc -jar c:\oc4j\j2ee\home\oc4j.jar Note: The amount of memory the Java VM will need depends mostly on two parameters: the element in the element in server.xml, and the partition_cache_size_limit parameter in web.xml. Deploying and Configuring the Routing Engine 13-4 Oracle Spatial Developer's Guide -config c:\oc4j\j2ee\home\config\server.xml 8. Verify your deployment by visiting the URL in the following format: http://:/routeserver You should see a welcome page. You should also see a message in the console window in which you started OC4J indicating that the Oracle Route Server was successfully initialized. If you do not see a welcome message, the route server is probably not configured properly to run in your environment. In this case, edit the /routeserver/web/WEB-INF/web.xml file to reflect your environment and your preferences. (The web.xml file is inside the routeserver.ear file, and it will not be visible until OC4J expands it into the route server directory structure under .) When you are finished editing, restart OC4J, and verify your deployment. 9. Consult the supplied examples. The page http://:/routeserver/ has links at the bottom in a section named Test Samples. These examples demonstrate various capabilities of the Oracle Route Server. This is the best way to learn the XML API, which is described in Section 13.2. 13.1.1 Configuring the web.xml File You will probably need to make some changes to the default web.xml file that is included with Spatial, especially if you want to use settings from an older web.xml file or if you want to specify a language or use long ID values. You may especially want to edit or add some of the following parameters: ■ routeserver_schema_jdbc_connect_string: Connect string to the database that contains routing data. ■ routeserver_schema_username: Name of the user that was created to access Oracle routing data. ■ routeserver_schema_password: Password for the user that was created to access Oracle routing data. You can obfuscate the password by preceding the password string with an exclamation point (!); if you do this, the password is obfuscated, and the web.xml file is rewritten the next time the routing engine is started. ■ geocoder_type: Type of geocoder being used: httpclient or thinclient for HTTP client or thin client, respectively. Depending on the value of this parameter, examine the settings in the HTTP Client or Thin Client section of the web.xml file, and make any edits as appropriate. For example, if you specified thinclient, you can obfuscate the Oracle Geocoder password in the same way as with the routeserver_schema_password parameter. ■ log_filename: Location and name of the log file. ■ driving_side: R (the default) if traffic drives on the right side of the road, or L if traffic drives on the left side of the road. ■ language: Default language to use to produce driving directions. The supported languages are English (the default), French, German, Italian, and Spanish. Routing Engine XML API Routing Engine 13-5 ■ long_ids: TRUE (the default) causes ID values to have their length stored as LONG and not INTEGER data; FALSE causes ID values to have their length stored as INTEGER and not LONG data. If you have routing data that was partitioned using an Oracle Database release before 11.1, the long_ids parameter value must be FALSE until the data is repartitioned using a current release. ■ local_road_threshold: A number of miles (default = 25, minimum = 10). If the estimated distance in miles between source and destination nodes is less than or equal to this value, local roads are considered as an option; if the distance is greater than this value, local roads are not considered. This parameter enables optimizations for short routes. Lower values can speed the routing engine performance by decreasing the size of the solution set to be searched, but can produce non-optimal short routes by causing the routing engine not to consider viable local road routes. Higher values (above the default of 25) can generate more accurate routes using local roads, but can slow the routing engine performance by increasing the size of the solution set to be searched. 13.2 Routing Engine XML API This section explains how to submit route requests in XML format to the routing engine, and it describes the XML document type definitions (DTDs) for the route requests (input) and responses (output). XML is widely used for transmitting structured documents using the HTTP protocol. If an HTTP request (GET or POST method) is used, it is assumed the request has a parameter named xml_request whose value is a string containing the XML document for the request. A request to the routing engine servlet has the following format: http://hostname:port/route-server-servlet-path?xml_request=xml-request In this format: ■ hostname is the network path of the server on which the routing engine is running. ■ port is the port on which the application server listens. ■ route-server-servlet-path is the routing engine servlet path (for example, routeserver/servlet/RouteServerServlet). ■ xml-request is the URL-encoded XML request submitted using the HTML GET or POST method. The input XML is required for all requests. The output will be an XML document. In a simple route (as opposed to batch route) request, you must specify a route ID, and you can specify one or more of the following attributes: ■ route_preference: fastest or shortest (default) ■ road_preference: highway (default) or local ■ return_driving_directions (whether to return driving directions): true or false (default) ■ return_hierarchical_directions (whether to return hierarchical directions): true or false (default) ■ return_route_geometry (whether to return the line string coordinates for the route): true or false (default) Routing Engine XML API 13-6 Oracle Spatial Developer's Guide ■ return_segment_geometry (whether to return the line string coordinates for each maneuver in the route): true or false (default) ■ return_detailed_geometry: true (default; returns detailed geometries) or false (returns generalized geometries) ■ language: language used to generate driving directions (ENGLISH, FRENCH, GERMAN, ITALIAN, or SPANISH) ■ return_segment_edge_ids (whether to return the edge ID values of the edges of each maneuver in the route): true or false (default) ■ return_route_edge_ids (whether to return the edge ID values of the edges in the route): true or false (default) ■ distance_unit: kilometer, mile (default), or meter ■ time_unit: hour, minute (default), or second ■ pre_geocoded_locations (whether the start and end locations are input locations (address specifications or points) or previously geocoded locations): true (previously geocoded locations) or false (default; input locations) In a batch route request, you must specify a request ID, a start location, and one or more end locations. Each location must have an ID attribute. You can also specify one or more of the following attributes for the batch route request: ■ route_preference: fastest or shortest (default) ■ road_preference: highway (default) or local ■ distance_unit: kilometer, mile (default), or meter ■ time_unit: hour, minute (default), or second ■ sort_by_distance (whether to sort the returned routes in ascending order by distance of the end location from the start location): true or false (default) ■ cutoff_distance (returning only routes where the end location is less than or equal to a specified number of distance units from the start location): (number; default = no limit) ■ pre_geocoded_locations (whether the start and end locations are input locations (address specifications or points) or previously geocoded locations): true (previously geocoded locations) or false (default; input locations) This section contains the following subsections: ■ Section 13.2.1, "Route Request and Response Examples" ■ Section 13.2.2, "Route Request DTD" ■ Section 13.2.3, "Route Response DTD" ■ Section 13.2.4, "Batch Route Request and Response Examples" ■ Section 13.2.5, "Batch Route Request DTD" ■ Section 13.2.6, "Batch Route Response DTD" 13.2.1 Route Request and Response Examples This section contains XML examples of route requests and the responses generated by those requests. One request uses specified addresses, another uses points specified by longitude and latitude coordinates, and another uses previously geocoded locations. Routing Engine XML API Routing Engine 13-7 For reference information about the available elements and attributes, see Section 13.2.2 for requests and Section 13.2.3 for responses. Example 13–1 shows a request for the fastest route, preferably using highways, between two offices at specified addresses (in Waltham, Massachusetts and Nashua, New Hampshire), with driving directions for each segment, and using miles for distances and minutes for times. Example 13–1 Route Request with Specified Addresses Example 13–2 shows the response generated by the request in Example 13–1. (The output is reformatted for readability.) Example 13–2 Route Response with Specified Addresses Routing Engine XML API 13-8 Oracle Spatial Developer's Guide Routing Engine XML API Routing Engine 13-9 Example 13–3 shows a request for the fastest route, preferably using highways, between two locations specified as longitude/latitude points, with driving directions for each segment, and using meters for distances and seconds for times. (The points are associated with two locations in San Francisco, California: the World Trade Center and 100 Flower Street.) Example 13–3 Route Request with Specified Longitude/Latitude Points Example 13–4 shows the response generated by the request in Example 13–3. (The output is reformatted for readability.) Example 13–4 Route Response with Specified Longitude/Latitude Points ?xml version="1.0" encoding="UTF-8" ?> -122.39382,37.79518 -122.39382,37.79518 -122.39454,37.79601 -122.39467,37.79604 -122.39476,37.79604 -122.39484,37.79599 -122.39486,37.79591 -122.39484,37.79579 -122.39462,37.79539 -122.39425,37.79491 -122.39389,37.79462 -122.39338,37.79433 -122.39326,37.79424 -122.39275,37.79384 -122.39263,37.79371 -122.39174,37.79293 -122.39151,37.79274 -122.39142,37.79266 -122.3913,37.7925 -122.3912,37.79233 -122.39102,37.79184 -122.39093,37.79161 -122.39072,37.79128 -122.39049,37.79104 -122.39016,37.79076 -122.38878,37.78967 -122.38861,37.7895 -122.38839,37.7892 -122.38819,37.78877 -122.38813,37.78857 -122.38797,37.78783 -122.38796,37.78758 -122.38801,37.78709 -122.38819,37.78478 -122.38832,37.78477 -122.38841,37.78474 -122.38983,37.78361 -122.39127,37.78246 -122.39206,37.78184 -122.39261,37.78139 -122.39319,37.78094 -122.3943,37.7801 -122.39486,37.77968 -122.39534,37.7793 -122.39654,37.77833 -122.39876,37.77657 -122.39902,37.77639 -122.40033,37.77537 -122.40096,37.77483 -122.40151,37.7744 -122.40205,37.77396 -122.40226,37.7738 -122.40266,37.77349 -122.40321,37.77305 -122.40376,37.77262 -122.40543,37.77129 -122.40578,37.77101 -122.40599,37.77083 -122.40699,37.77006 -122.40767,37.76953 Routing Engine XML API 13-10 Oracle Spatial Developer's Guide -122.40774,37.76947 -122.40781,37.7694 -122.40786,37.76932 -122.40788,37.76922 -122.40788,37.76913 -122.40786,37.76897 -122.40785,37.76883 -122.40779,37.76838 -122.40767,37.7671 -122.40756,37.76577 -122.40743,37.76449 -122.40734,37.76321 -122.40722,37.76193 -122.40709,37.76067 -122.40695,37.75937 -122.40678,37.75776 -122.4067,37.75684 -122.40663,37.75617 -122.40647,37.75458 -122.40644,37.75428 -122.40632,37.75299 -122.4062,37.75174 -122.40617,37.75138 -122.40614,37.75103 -122.40606,37.75066 -122.40565,37.74987 -122.40529,37.74937 -122.40518,37.74924 -122.40506,37.74913 -122.4045,37.74873 -122.4041,37.74845 -122.40393,37.74827 -122.40384,37.74815 -122.40378,37.74801 -122.40375,37.74785 -122.40381,37.74762 -122.40397,37.74719 -122.4043,37.74633 -122.40434,37.74618 -122.40434,37.74603 -122.40431,37.74594 -122.4042,37.74554 -122.40416,37.7453 -122.40417,37.74515 -122.40431,37.74464 -122.40445,37.74427 -122.40461,37.74393 -122.40479,37.74362 -122.40522,37.74304 -122.40482,37.74282 -122.40517,37.74233 -122.40545613036156,37.742431337836386 Example 13–5 shows a request for the route, with driving directions, where the start and end locations are previously geocoded locations that are about one-half mile apart in Boston, Massachusetts. Example 13–5 Route Request with Previously Geocoded Locations 22161661 .5 L 22104391 .5 R Example 13–6 shows the response to the request in Example 13–5. (The output is reformatted for readability.) Example 13–6 Route Response with Previously Geocoded Locations Routing Engine XML API 13-12 Oracle Spatial Developer's Guide 13.2.2 Route Request DTD The following is the complete DTD for a route request. The main elements and attributes of the DTD are explained in sections that follow. %GEOCODERDTD; Routing Engine XML API Routing Engine 13-13 13.2.2.1 route_request Element The element has the following definition: The root element of a route request is always named route_request. The child element specifies the start location for the route, as an address specification, a geocoded address, or longitude/latitude coordinates. The child element specifies the end location for the route, as an address specification, a geocoded address, or longitude/latitude coordinates. In a route request: ■ If is an address specification or longitude/latitude coordinates, can be either an address specification or longitude/latitude coordinate; however, it cannot be a geocoded address. ■ If is a geocoded address, must be a geocoded address 13.2.2.2 route_request Attributes The root element has a number of attributes, most of them optional. The attributes are defined as follows: driving_directions_detail (LOW|MEDIUM|HIGH) #IMPLIED vendor is an optional attribute whose default value identifies the routing provider as Oracle. id is a required attribute that specifies an identification number to be associated with the request. route_preference is an optional attribute that specifies whether you want the route with the lowest estimated driving time (FASTEST) or the route with the shortest driving distance (SHORTEST, the default). road_preference is an optional attribute that specifies whether you want the route to use highways (HIGHWAY, the default) or local roads (LOCAL) when a choice is available. return_driving_directions is an optional attribute that specifies whether you want driving directions for the route. TRUE returns driving directions; FALSE (the default) does not return driving directions. Routing Engine XML API 13-14 Oracle Spatial Developer's Guide return_hierarchical_driving_directions is an optional attribute that specifies whether you want driving directions for the route returned in an expandable and collapsible hierarchy. TRUE returns driving directions in an expandable and collapsible hierarchy; FALSE (the default) returns driving directions in a list with no hierarchy. return_route_geometry is an optional attribute that specifies whether you want the coordinates of each line string that represents a maneuver in the route. TRUE returns the coordinates; FALSE (the default) does not return the coordinates. return_segment_geometry is an optional attribute that specifies whether you want the coordinates of the line string that represents the route. TRUE returns the coordinates; FALSE (the default) does not return the coordinates. If return_ segment_geometry is TRUE, driving directions for the route are returned regardless of the value of the return_route_geometry attribute. return_detailed_geometry is an optional attribute that indicates the level of detail to be included in returned geometries. TRUE (the default) returns detailed geometries; FALSE returns generalized geometries (usually with fewer coordinates). return_route_edge_ids is an optional attribute that specifies whether you want the edge ID values of the edges in the route. TRUE returns the edge ID values; FALSE (the default) does not return the edge ID values. return_segment_edge_ids is an optional attribute that specifies whether you want the edge ID values of the edges of all maneuvers in the route. TRUE returns the edge ID values; FALSE (the default) does not return the edge ID values. If return_ segment_edge_ids is TRUE, edge ID values are returned regardless of the value of the return_route_edge_ids attribute. language is an optional attribute that overrides the default language used to generate the driving directions. The default language for is set in the web.xml file; you can use this attribute to override the default on a per-request basis. The following attribute values are supported: ENGLISH, FRENCH, GERMAN, ITALIAN, and SPANISH. distance_unit is an optional attribute that specifies the unit of measure for distance values that are returned: KM for kilometer, MILE (the default) for mile, or METER for meter. time_unit is an optional attribute that specifies the unit for time values that are returned: HOUR for hour, MINUTE (the default) for minute, or SECOND for second. pre_geocoded_locations is an optional attribute that indicates how the start and end locations are specified. TRUE means that both are previously geocoded locations specified using the element; FALSE (the default) means that both are addresses specified using the element. driving_directions_detail is an optional attribute that influences the level of detail and the number of separate steps in driving instructions. The available values are HIGH (most details and steps), MEDIUM (the default), and LOW (fewest details and steps). For example, LOW might treat a segment as a single step even if it involves slight maneuvers to the right or left. The effect of a value for this attribute on the length of returned driving directions will vary, depending on the exact names of elements and maneuvers. This attribute is ignored if you do not specify TRUE for return_driving_directions or return_hierarchical_driving_ directions. Routing Engine XML API Routing Engine 13-15 13.2.2.3 input_location Element The element specifies an address in a format that satisfies the Oracle Spatial geocoding request DTD, which is described in Section 11.7.2. You can specify the input location using either the element or the element. Example 13–1 in Section 13.2.1 shows the start and end addresses specified using the element and its child element . To use the element, you must ensure that the value of the pre_ geocoded_locations attribute is FALSE (the default) in the element. You can use the and elements together in a request. 13.2.2.4 pre_geocoded_location Element The element specifies a geocoded location in terms of how far along a street (an edge) the address is and on which side of the street. Example 13–5 in Section 13.2.1 shows the start and end addresses specified using the element. To use the element, you must specify pre_ geocoded_locations="TRUE" in the element, and you must use the element to specify both the start and end locations. 13.2.3 Route Response DTD The following is the complete DTD for a route response: %GMLGEOMETRYDTD; Note: The default level of detail has changed in Oracle Database release 11.1, to provide fewer details and steps than before. If you want to have the same level of detail as in the previous release (which did not have the driving_directions_detail attribute), specify HIGH for the driving_directions_detail attribute. Routing Engine XML API 13-16 Oracle Spatial Developer's Guide 13.2.4 Batch Route Request and Response Examples This section contains XML examples of batch route requests and the responses generated by those requests. One request uses specified addresses, and the other request uses previously geocoded locations. For reference information about the available elements and attributes, see Section 13.2.5 for requests and Section 13.2.6 for responses. Example 13–7 shows a batch route request using specified addresses. The request is for the fastest routes, preferably using highways, between an office in Waltham, Massachusetts and three end locations (an Oracle office in Nashua, New Hampshire; the town offices in Concord, Massachusetts; and Boston City Hall), using miles for distances and minutes for times. The request calls for the returned routes to be sorted by distance between the start and end location, and for no routes over 35 miles to be returned. Example 13–7 Batch Route Request with Specified Addresses Routing Engine XML API Routing Engine 13-17 Example 13–8 shows the response generated by the request in Example 13–7. (The output is reformatted for readability.) Example 13–8 Batch Route Response with Specified Addresses Example 13–9 shows a batch route request using previously geocoded locations. The request is for the shortest routes, preferably using highways, between one location and three other locations, using miles for distances and minutes for times. The request calls for the returned routes to be sorted by distance between the start and end location, and for no routes over 50 miles to be returned. Routing Engine XML API 13-18 Oracle Spatial Developer's Guide Example 13–9 Batch Route Request with Previously Geocoded Locations 22161661 .5 L 22104391 .5 R 22160808 .5 L 22325991 .5 R Example 13–10 shows the response to the request in Example 13–9. Only two routes are returned, because the third route is longer than the specified cutoff distance of 50 miles. (The output is reformatted for readability.) Example 13–10 Batch Route Response with Previously Geocoded Locations 13.2.5 Batch Route Request DTD The following is the complete DTD for a batch route request. The main elements and attributes of the DTD are explained in sections that follow. %GEOCODERDTD; 13.2.5.1 batch_route_request Element The element has the following definition: The root element of a route request is always named batch_route_request. Routing Engine XML API 13-20 Oracle Spatial Developer's Guide The child element specifies the start location for the route, as an address specification, a geocoded address, or longitude/latitude point. Each of the one or more child elements specifies the end location for the route, as an address specification, a geocoded address, or longitude/latitude point. 13.2.5.2 batch_route_request Attributes The root element has a number of attributes, most of them optional. The attributes are defined as follows: pre_geocoded_locations (TRUE|FALSE) #IMPLIED> Most attributes have the same meaning as their counterpart attributes, which are explained in Section 13.2.5.2. In addition, the sort_by_distance and cutoff_distance attributes do not apply to single route requests. sort_by_distance is an optional attribute that specifies whether you want the routes returned in ascending order by distance of the end location from the start location. TRUE sorts the returned routes by distance; FALSE (the default) does not sort the returned routes by distance. cutoff_distance is an optional attribute that causes routes to be returned only where the end location is less than or equal to a specified distance from the start location. By default, all routes are returned. 13.2.6 Batch Route Response DTD The following is the complete DTD for a batch route response: element in the response (see Section 13.2.6), the route is removed from the response and not shown. Data Structures Used by the Routing Engine Routing Engine 13-21 error_msg CDATA #IMPLIED> 13.3 Data Structures Used by the Routing Engine Each database user of the routing engine must have the following tables in its schema: ■ EDGE ■ NODE ■ PARTITION ■ SIGN_POST The EDGE and NODE tables store edge and node information about the street network used by the routing engine. To understand how edges and nodes are used to represent street segments, intersections, and other entities in a street network, you must be familiar with the Oracle Spatial network data model, which is described in Oracle Spatial Topology and Network Data Models Developer's Guide. The following sections describe the tables used by the routing engine, in alphabetical order by table name. 13.3.1 EDGE Table The EDGE table contains one row for each directed edge in a street network. Each street segment (a part of a road between two nodes) is an undirected edge that corresponds to one or more directed edges in the EDGE table. The EDGE table contains the columns shown in Table 13–1. Table 13–1 EDGE Table Column Name Data Type Description EDGE_ID NUMBER Edge ID number. START_NODE_ ID NUMBER Node ID number of the start node of this edge. END_NODE_ID NUMBER Node ID number of the end node of this edge. PARTITION_ID NUMBER Partition ID number of the network partition that contains this edge. FUNC_CLASS NUMBER Functional road class: a number from 1 through 5, with 1 indicating a large, high-speed, high-volume road, and each successive class generally smaller in size, speed, and volume. Class 2 roads have consistent speeds and are used to get traffic to and from class 1 roads. Class 3 roads have high volume and are used to connect class 2 roads. Class 4 roads move volumes of traffic between neighborhoods (for example, a busy main road in a city). Class 5 roads are all other roads (for example, a small, low-volume street in a neighborhood). LENGTH NUMBER Length of this edge, in meters. SPEED_LIMIT NUMBER Assigned speed limit for this edge, in meters per second. GEOMETRY SDO_ GEOMETRY Line string geometry representing this edge, with the coordinates ordered from the start node to the end node. NAME VARCHAR2(128) Name of this edge. Data Structures Used by the Routing Engine 13-22 Oracle Spatial Developer's Guide 13.3.2 NODE Table The NODE table contains one row for each node that is the start node or end node of one or more edges in the street network. A node often corresponds to an intersection (the intersection of two edges); however, a node can be independent of any intersection (for example, the end of a "dead end" or "no outlet" street). The NODE table contains the columns shown in Table 13–2. 13.3.3 PARTITION Table The PARTITION table is generated by Oracle based on the contents of the EDGE and NODE tables. The PARTITION table contains the columns shown in Table 13–3. 13.3.4 SIGN_POST Table The SIGN_POST table stores sign information that is used to generate driving directions. For example, a sign might indicate that Exit 33A on US Route 3 South goes toward Winchester. A SIGN_POST row might correspond to a physical sign at an exit DIVIDER VARCHAR2(1) A value of N indicates that the edge is not divided; other values indicate whether, where, and how turns are allowed on the divided edge. (The routing engine currently considers only whether the edge is divided or not.) Table 13–2 NODE Table Column Name Data Type Description NODE_ID NUMBER Node ID number. GEOMETRY SDO_ GEOMETRY Point geometry representing this node. PARTITION_ID NUMBER Partition ID number of the network partition that contains this node. Table 13–3 PARTITION Table Column Name Data Type Description PARTITION_ID NUMBER Partition ID number. SUBNETWORK BLOB Part of the network included in this partition. NUM_NODES NUMBER Number of nodes in this partition. NUM_NON_ BOUNDARY_EDGES NUMBER Number of edges in this partition that are edges that are completely contained within the partition. NUM_OUTGOING_ BOUNDARY_EDGES NUMBER Number of edges in this partition that start in this partition and terminate in another partition. (An edge cannot be in more that two partitions; for example, an edge cannot start in one partition, go through a second partition, and end in a third partition.) NUM_INCOMING_ BOUNDARY_EDGES NUMBER Number of edges in this partition that start in another partition and terminate in this partition. (An edge cannot be in more that two partitions; for example, an edge cannot start in one partition, go through a second partition, and end in a third partition.) Table 13–1 (Cont.) EDGE Table Column Name Data Type Description Data Structures Used by the Routing Engine Routing Engine 13-23 ramp on a highway, but it does not need to correspond to a physical sign. The SIGN_ POST table contains the columns shown in Table 13–4. Table 13–4 SIGN_POST Table Column Name Data Type Description FROM_EDGE_ID NUMBER Edge ID number of the edge to which this sign applies (for example, the street segment containing the exit ramp). TO_EDGE_ID NUMBER Edge ID number of the edge to which this sign points (for example, the street segment to which the exit ramp leads). RAMP VARCHAR2(64) Ramp text (for example, US-3 SOUTH). EXIT VARCHAR2(8) Exit number (for example, 33A). TOWARD VARCHAR2(64) Text indicating where the exit is heading (for example, WINCHESTER). Data Structures Used by the Routing Engine 13-24 Oracle Spatial Developer's Guide 14 OpenLS Support 14-1 14 OpenLS Support This chapter describes the Oracle Spatial support for Web services based on the Open Location Services Initiative (OpenLS) of the Open GeoSpatial Consortium (OGC), versions 1.0 and 1.1. For a description of OpenLS, see http://www.opengeospatial.org/standards/ols, which includes links for downloads and schemas. This chapter includes the following major sections: ■ Section 14.1, "Supported OpenLS Services" ■ Section 14.2, "OpenLS Application Programming Interfaces" ■ Section 14.3, "OpenLS Service Support and Examples" 14.1 Supported OpenLS Services Spatial supports the following OGC OpenLS services: ■ Location Utility Service (geocoding) ■ Presentation Service (mapping) ■ Route Service (driving directions) ■ Directory Service (YP, or "Yellow Pages") Spatial does not currently support the OGC OpenLS Gateway Service (mobile positioning). For all supported services except Directory Service (YP, or Yellow Pages), you must first perform certain operations, which might included acquiring and loading third-party data, as well as configuring and deploying underlying technology on which the Spatial OpenLS service is based. Table 14–1 lists the Spatial OpenLS services, and the chapter or manual that documents the requirements and underlying technologies. Note: Before you use OpenLS, be sure that you understand the concepts described in Chapter 10, "Introduction to Spatial Web Services", and that you have performed any necessary configuration work as described in that chapter. Table 14–1 Spatial OpenLS Services Dependencies Spatial OpenLS Service Depends On Documented In Geocoding Geocoding metadata and data Chapter 11, "Geocoding Address Data" OpenLS Application Programming Interfaces 14-2 Oracle Spatial Developer's Guide 14.2 OpenLS Application Programming Interfaces Two application programming interfaces (APIs) are provided using Spatial OpenLS services: a Web services API and a PL/SQL API. The Web services API uses the same SOAP envelope as Web feature services (described in Chapter 15). You enable authentication and authorization using WSS and proxy authentication and user management. The PL/SQL API is a convenient alternative to Web services. Authentication and authorization are enabled through the database connection that you use to call a PL/SQL subprogram to submit an OpenLS request and return the result. The PL/SQL API is implemented in the SDO_OLS package, which is documented in Chapter 27. 14.3 OpenLS Service Support and Examples This section describes the support provided for geocoding, mapping, routing, and directory service (YP). It also contains examples of OpenLS Web services API requests and responses. 14.3.1 OpenLS Geocoding An OpenLS geocoding element includes the methodName attribute with a value of either GeocodeRequest or ReverseGeocodeRequest, and corresponding a top-level element named or . If the methodName attribute value is GeocodeRequest, the element contains an
element that can specify a free-form address, a street address, or an intersection address, with zero or more elements and an optional element. The
element has the required attribute countryCode, and several optional attributes. If the methodName attribute value is GeocodeRequest, the element contains a element for identifying the location to be reverse geocoded, and an optional element for specifying the information to be returned (default = a street address). Example 14–1 is a request to geocode two addresses in San Francisco, California. Example 14–1 OpenLS Geocoding Request Mapping Oracle MapViewer Oracle Fusion Middleware User's Guide for Oracle MapViewer Driving directions Routing engine Chapter 13, "Routing Engine" Business directory (YP, or Yellow Pages) Data from an external provider Chapter 12, "Business Directory (Yellow Pages) Support" Table 14–1 (Cont.) Spatial OpenLS Services Dependencies Spatial OpenLS Service Depends On Documented In OpenLS Service Support and Examples OpenLS Support 14-3
Post Street CA San Francisco 94102
Winston Drive CA San Francisco 94132
Example 14–2 is the response to the request in Example 14–1. The longitude and latitude coordinates are returned for the two addresses (-122.4083257 37.788208 for the first, -122.4753965 37.7269066 for the second). Example 14–2 OpenLS Geocoding Response -122.4083257 37.788208 POST ST CA SAN FRANCISCO 94102 OpenLS Service Support and Examples 14-4 Oracle Spatial Developer's Guide -122.4753965 37.7269066 WINSTON DR CA SAN FRANCISCO 94132 14.3.2 OpenLS Mapping An OpenLS mapping element includes the methodName attribute with a value of PortrayMapRequest, and a top-level element named . The element contains an element that specifies the output of the map to be generated, including the center point of the map. The element can contain a element specifying a MapViewer base map and one or more themes, and zero or more elements, each specifying information to be overlaid on the base map. Example 14–3 is a request to portray a map image. The image is to be centered at a specified longitude/latitude point, to use a base map and two MapViewer themes, and identify three points on the map. Example 14–3 OpenLS Mapping Request OpenLS Service Support and Examples OpenLS Support 14-5 -122.2615 37.5266 50000 -122.4083257 37.788208
Winston Drive CA San Francisco 94132
-122.8053965 37.388208
Example 14–4 is the response to the request in Example 14–3.; however, in an actual response, the line Actual URL replaced with constant string for test would contain the actual URL of the map image. Example 14–4 OpenLS Mapping Response Actual URL replaced with constant string for test -122.86037685607968 37.07744235794024 -121.66262314392031 37.97575764205976 14.3.3 OpenLS Routing An OpenLS routing element includes the methodName attribute with a value of DetermineRouteRequest, and a top-level element named . The element contains a element that specifies the route preference and points to be included (and optionally avoided) in the route, with at least the start and end points. The element can also contain zero or more of the following elements: to return the line string geometry representing the route, to request a map image of the route, and to request driving directions for the route. Example 14–5 is a request for the route geometry and map image for the fastest route between an address in Cambridge, Massachusetts and an address in Nashua, New Hampshire. Example 14–5 OpenLS Routing Request Fastest
OpenLS Service Support and Examples OpenLS Support 14-7 Cambridgeside Pl MA Cambridge 02141
Oracle Dr New Hampshire Nashua 03062
Example 14–6 is part of the response to the request in Example 14–5. Example 14–6 shows the total estimated driving time, the total distance, the lower-left and upper-right longitude/latitude coordinates of the minimum bounding rectangle that encloses the route, and the longitude/latitude coordinates of the first few points along the line geometry representing the route. Example 14–6 OpenLS Routing Response P0DT0H42M26S -71.45937289088023 42.36694 -71.06754 42.70824 OpenLS Service Support and Examples 14-8 Oracle Spatial Developer's Guide -71.07444,42.36792 -71.07162,42.37082 -71.06954,42.37333 . . . 14.3.4 OpenLS Directory Service (YP) An OpenLS directory service element includes the methodName attribute with a value of DirectoryRequest, and a top-level element named . The element contains a element that specifies the location of a point of interest, that is, the center point from which to compute distances of returned businesses. The element also contains a element that specifies one or more elements, each of which contains a name attribute identifying a property and a value attribute identifying the value for the property. The name attribute can specify any of the following strings: ID, POIName, PhoneNumber, Keyword, NAICS_type, NAICS_subType, NAICS_category, SIC_ type, SIC_subType, SIC_category, SIC_code, or other. Example 14–7 is a request for information about business that have either or both of two specified SIC (Standard Industrial Classification) codes. For this example, the two SIC codes (1234567890 and 1234567891) are fictitious, and they are being used with a limited test data set in which these codes have been applied to categories (Book stores and Cafes & Cafeterias) that do not have these SIC codes in the real world. Example 14–7 OpenLS Directory Service (YP) Request
OpenLS Service Support and Examples OpenLS Support 14-9
Example 14–8 is the response to the request in Example 14–7. The response contains information about two businesses for which either or both of the specific SIC codes apply. Example 14–8 OpenLS Directory Service (YP) Response -122.4753965 37.7269066 Winston Drive CA San Francisco 94132 -122.4083257 37.788208 Post St Powell St CA San Francisco 94102 15 Web Feature Service (WFS) Support 15-1 15 Web Feature Service (WFS) Support This chapter describes Web Feature Service (WFS) support in Oracle Spatial It includes the following major sections: ■ Section 15.1, "WFS Engine" ■ Section 15.2, "Managing Feature Types" ■ Section 15.3, "Request and Response XML Examples" ■ Section 15.4, "Java API for WFS Administration" ■ Section 15.5, "Using WFS with Oracle Workspace Manager" 15.1 WFS Engine This section describes the Web Feature Service engine, including its relationship to clients and to the database server. WFS is implemented as a Web service and can be deployed in Oracle Containers for Java (OC4J), which is included with Oracle Application Server. WFS has a metadata layer, which stores in the database the metadata needed to reply to the WFS requests. The metadata includes spatial columns, which can be queried and processed using Oracle Spatial interfaces. The metadata also stores the association of nonspatial and spatial attributes of features, as well as the services that the Web Feature Service provides to its clients. Figure 15–1 shows the WFS architecture. Note: Before you use WFS, be sure that you understand the concepts described in Chapter 10, "Introduction to Spatial Web Services", and that you have performed any necessary configuration work as described in that chapter. If you have data from a previous release that was indexed using one or more SYS.XMLTABLEINDEX indexes, you must drop the associated indexes before the upgrade and re-create the indexes after the upgrade, as described in Section A.2. Managing Feature Types 15-2 Oracle Spatial Developer's Guide Figure 15–1 Web Feature Service Architecture As shown in Figure 15–1: ■ WFS is part of a container in the Oracle Application Server middle tier. ■ WFS can communicate with a Web service client using WFS requests and responses in SOAP/XML format. ■ WFS performs spatial data and metadata access through JDBC calls to the database. ■ The database includes Oracle Spatial with WFS metadata and data. Web Service Security (WSS) is implemented using secure transport. User identities and user labels are managed in LDAP, and the middle tier and WSS combine to perform authentication. Oracle label-based security is used for managing user privileges at the feature level. For more information about WSS, see Chapter 17. 15.2 Managing Feature Types WFS supports relational and document-based feature types: ■ Relational feature types expose the content of database tables as feature instances. Relational feature types are well suited for those who use Oracle Spatial to manage their geospatial data and use Oracle Database to manage other business data. The Spatial WFS implementation provides ways to access the data, especially in service-oriented architecture (SOA) systems implemented using Web services. Use PL/SQL application programming interfaces (APIs) to manage relational feature types. The PL/SQL packages SDO_WFS_LOCK and SDO_WFS_PROCESS (described in Chapter 33 and Chapter 34, respectively) enable you to manage relational feature types. ■ Document-based feature types expose XML schema-based XML content as feature instances. Document-based feature types are well suited for those who use XML as their main data source and who might not currently use Oracle Spatial with such data. For this data, the Spatial WFS implementation extracts the geometry components and stores them using the SDO_GEOMETRY type; it stores the Web Feature Service Client Middle Tier (Oracle Application Server) Database JDBC WFS Request &Response (SOAP/XML) Web Service Clients Spatial DB with WFS metadata & data Container Managing Feature Types Web Feature Service (WFS) Support 15-3 remaining XML components in Oracle XDB and builds appropriate XMLIndex indexes for them. Use Java APIs (described in Section 15.4) to manage document-based feature types. These APIs enable you to perform operations that include: ■ Publishing feature types ■ Dropping (unpublishing) feature types ■ Granting to users and revoking from users privileges of WFS metadata and feature types ■ For relational feature types: lock-enabling and lock-disabling feature tables (with lock-enabling on by default for document-based feature types) 15.2.1 Capabilities Documents A capabilities document describes an instance of a capability. The document specifies a feature type (such as roads or rivers) and the type of operations supported (such as insert and delete). A capabilities document is generated by the WFS server in response to a GetCapabilities request. The WFS server uses a capabilities template, and adds information about the feature type and operations to this template to create the capabilities document. The client can use the HTTP GET method to access this capabilities document using either the SOAP interface or the XML interface: ■ For the SOAP interface, use oracle.spatial.ws.servlet.WFSServlet, which can be accessed at an address in the following format: http://machine-name:port/SpatialWS-SpatialWS-context-root/wfsservlet?request=Ge tCapabilities&service=WFS&version=1.0.0 ■ For the XML interface, use oracle.spatial.ws.servlet.WFSXMLServlet, which can be accessed at an address in the following format: http://machine-name:port/SpatialWS-SpatialWS-context-root/xmlwfsservlet?request =GetCapabilities&service=WFS&version=1.0.0 In the preceding formats: ■ machine-name is the name of the system where the OC4J server is running. ■ port is the port number where the OC4J server is running. ■ SpatialWS-SpatialWS-context-root is the default root where the Spatial Web services application is mounted. ■ wfsservlet is the servlet-mapping url-pattern for oracle.spatial.ws.servlet.WFSServlet, as specified by default in the web.xml file. ■ xmlwfsservlet is the servlet-mapping url-pattern for oracle.spatial.ws.servlet.WFSXMLServlet, as specified by default in the web.xml file. Request and Response XML Examples 15-4 Oracle Spatial Developer's Guide 15.3 Request and Response XML Examples This section presents some feature requests to the WFS engine, and the response to each request, for each of the following operations: ■ GetCapabilities ■ DescribeFeatureType ■ GetFeature ■ GetFeatureWithLock ■ LockFeature ■ Transaction, with a subelement specifying the transaction type: – Insert – Update – Delete The XML request and response formats are similar for both relational and document-based features. Several examples in this section refer to relational features based on the COLA_MARKETS_CS table used in Example 6–17 in Section 6.13, where the MKT_ID column contains the unique numeric ID of each feature, the NAME column contains each feature’s name (cola_a, cola_b, cola_c, or cola_d), and the SHAPE column contains the geometry associated with each feature. Example 15–1 is a request to get the capabilities of the WFS server named WFS at a specified namespace URL. T.his request will return a capabilities document, as explained in Section 15.2.1 Example 15–1 GetCapabilities Request Example 15–2 is an excerpt of the response from the request in Example 15–1. Example 15–2 GetCapabilities Response Oracle WFS Oracle Web Feature Service Web Feature Service maintained by Oracle http://localhost:8888/SpatialWS-SpatialWS-context-root/wfsservlet< /OnlineResource> Request and Response XML Examples Web Feature Service (WFS) Support 15-5 myns:COLA LIST OF COLA MARKETS SDO:8307 myns:COLAVIEW1 LIST OF COLA MARKET VIEW SDO:8307 myns:SampleFeature SAMPLE FEATURE EPSG:32615 Example 15–3 is a request to describe the feature type named COLA. Request and Response XML Examples Web Feature Service (WFS) Support 15-7 Example 15–3 DescribeFeatureType Request myns:COLA Example 15–4 is the response from the request in Example 15–3. The response is an XML schema definition (XSD). Example 15–4 DescribeFeatureType Response Example 15–5 is a request to get the MKT_ID, NAME, and SHAPE properties of the feature or features of type COLA where the MKT_ID value is greater than 2 and the NAME value is equal to cola_c, or where the MKT_ID value is greater than 3 and the NAME value is equal to cola_d. Request and Response XML Examples 15-8 Oracle Spatial Developer's Guide Example 15–5 GetFeature Request myns:MKT_ID myns:NAME myns:SHAPE myns:COLA/myns:MKT_ID 2 myns:COLA/myns:NAME cola_c myns:COLA/myns:MKT_ID 3 myns:COLA/myns:NAME cola_d Example 15–6 is the response from the request in Example 15–5. Example 15–6 GetFeature Response 3.0,3.0 6.0,5.0 3 cola_c 3.0,3.0 6.0,3.0 6.0,5.0 4.0,5.0 3.0,3.0 Example 15–7 is a request to get the MKT_ID, NAME, and SHAPE properties of the feature of type COLA where the MKT_ID value is greater than 2 and the NAME value is equal to cola_c, or where the MKT_ID value is equal to 3, and to lock that feature. Example 15–7 GetFeatureWithLock Request myns:MKT_ID myns:NAME myns:SHAPE myns:COLA/myns:MKT_ID 3 Example 15–8 is the response from the request in Example 15–7. Request and Response XML Examples 15-10 Oracle Spatial Developer's Guide Example 15–8 GetFeatureWithLock Response 3.0,3.0 6.0,5.0 3 cola_c 3.0,3.0 6.0,3.0 6.0,5.0 4.0,5.0 3.0,3.0 Example 15–9 is a request to lock the feature where the MKT_ID value is equal to 2. Example 15–9 LockFeature Request myns:COLA/myns:MKT_ID 2 Example 15–10 is the response from the request in Example 15–9. Example 15–10 LockFeature Response 2 Request and Response XML Examples Web Feature Service (WFS) Support 15-11 Example 15–11 is a request to insert a feature, with MKT_ID = 5 and NAME = cola_e, into the table associated with the WFS service named WFS. Example 15–11 Insert Request 5 cola_e 1.0,3.0 6.0,3.0 6.0,5.0 4.0,5.0 1.0,3.0 Example 15–12 is the response from the request in Example 15–11. Example 15–12 Insert Response Example 15–13 is a request to update the feature, where MKT_ID is greater than 2 and less than 4 and where NAME is not null, in the table associated with the WFS service named WFS. This request specifies that the NAME value of the specified feature is to be set to cola_cl. Example 15–13 Update Request Request and Response XML Examples 15-12 Oracle Spatial Developer's Guide myns:COLA/myns:NAME cola_c1 myns:COLA/myns:MKT_ID 2 myns:COLA/myns:MKT_ID 4 myns:COLA/myns:NAME Example 15–14 is the response from the request in Example 15–13. Example 15–14 Update Response Example 15–15 is a request to delete the feature, where MKT_ID is greater than 3 and NAME is equal to cola_e and is not null, in the table associated with the WFS service named WFS. Example 15–15 Delete Request myns:COLA/myns:MKT_ID 3 Java API for WFS Administration Web Feature Service (WFS) Support 15-13 myns:COLA/myns:NAME cola_e myns:COLA/myns:NAME Example 15–16 is the response from the request in Example 15–15. Example 15–16 Delete Response 15.4 Java API for WFS Administration In addition to the PL/SQL APIs in the SDO_WFS_PROCESS and SDO_WFS_LOCK packages, you can use a Java API to publish and drop feature types, and to grant and revoke access to feature types and WFS metadata tables. This section provides basic reference information about the methods in the oracle.spatial.wfs.WFSAdmin class. The methods are presented in alphabetical order. 15.4.1 createXMLTableIndex method The createXMLTableIndex method creates an index of XDB.XMLINDEX on document-based feature type instances. This method has the following format: public static void createXMLTableIndex( OracleConnection conn, String ftNSUrl, String ftName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. ftNSUrl is the URL of the namespace of the feature type. ftName is the name of the feature type. 15.4.2 dropFeatureType method The dropFeatureType method deletes a feature type from the WFS repository. This method has the following format: Java API for WFS Administration 15-14 Oracle Spatial Developer's Guide public static void dropFeatureType( OracleConnection conn, String ftNSUrl, String ftName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. ftNSUrl is the URL of the namespace of the feature type. ftName is the name of the feature type. 15.4.3 dropXMLTableIndex method The dropXMLTableIndex method drops an index of type XDB.XMLINDEX that was created on document-based feature type instances. This method has the following format: public static void dropXMLTableIndex( OracleConnection conn, String ftNSUrl, String ftName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. ftNSUrl is the URL of the namespace of the feature type. ftName is the name of the feature type. 15.4.4 getIsXMLTableIndexCreated method The getIsXMLTableIndexCreated method returns a Boolean TRUE if an index of type XDB.XMLINDEX has been created on a document-based feature type, or a Boolean FALSE if such an index has not been created. This method has the following format: public static boolean getIsXMLTableIndexCreated( OracleConnection conn, String ftNSUrl, String ftName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. ftNSUrl is the URL of the namespace of the feature type. ftName is the name of the feature type. 15.4.5 grantFeatureTypeToUser method The grantFeatureTypeToUser method grants access to a feature type to a database user. This method has the following format: public static void grantFeatureTypeToUser( OracleConnection conn, String typeNS, String typeName, String usrName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNS is the URL of the namespace of the feature type. typeName is the name of the feature type. Java API for WFS Administration Web Feature Service (WFS) Support 15-15 usrName is the name of the database user. 15.4.6 grantMDAccessToUser method The grantMDAccessToUser method grants access to the WFS metadata to a database user. This method has the following format: public static void grantMDAccessToUser( OracleConnection conn, String usrName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. usrName is the name of the database user. 15.4.7 publishFeatureType method The publishFeatureType method publishes a document-based feature type; that is, it registers metadata related to the feature type. This method has the following formats: public static void publishFeatureType(OracleConnection conn, XMLType featureTypeMD) throws SQLException , WFSException; public static void publishFeatureType(OracleConnection conn, XMLType schemaDocXt, XMLType featureDescXt, ArrayList docIdPaths, String primarySpatialPath, String featureMemberNS, String featureMemberName, String ftNSUrl, String ftName, ArrayList spatialPaths, ArrayList mandatoryPaths, ArrayList tsPaths, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias) throws SQLException; public static void publishFeatureType(OracleConnection conn, XMLType schemaDocXt, XMLType featureDescXt, ArrayList docIdPaths, String primarySpatialPath, String featureMemberNS, String featureMemberName, String ftNSUrl, String ftName, ArrayList spatialPaths, ArrayList mandatoryPaths, ArrayList tsPaths, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String ftXSDRefId) throws SQLException; public static void publishFeatureType(OracleConnection conn, XMLType schemaDocXt, XMLType featureDescXt, Java API for WFS Administration 15-16 Oracle Spatial Developer's Guide ArrayList docIdPaths, String primarySpatialPath, String featureMemberNS, String featureMemberName, String ftNSUrl, String ftName, ArrayList spatialPaths, ArrayList mandatoryPaths, ArrayList tsPaths, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String ftXSDRefId, boolean genSpatialIndex, boolean lockEnable) throws SQLException; public static void publishFeatureType(OracleConnection conn, XMLType schemaDocXt, XMLType featureDescXt, ArrayList docIdPaths, String primarySpatialPath, String featureMemberNS, String featureMemberName, String ftNSUrl, String ftName, ArrayList spatialPaths, ArrayList mandatoryPaths, ArrayList tsPaths, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String ftXSDRefId, boolean genSpatialIndex, boolean lockEnable, ArrayList numPaths, ArrayList idxPaths, ArrayList idxPathTypes, boolean genXMLIndex) throws SQLException; public static void publishFeatureType(OracleConnection conn, XMLType schemaDocXt, XMLType featureDescXt, ArrayList docIdPaths, String primarySpatialPath, String featureMemberNS, String featureMemberName, String ftNSUrl, String ftName, ArrayList spatialPaths, ArrayList mandatoryPaths, ArrayList tsPaths, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String ftXSDRefId, boolean genSpatialIndex, boolean lockEnable, ArrayList numPaths, ArrayList idxPaths, ArrayList idxPathTypes, Java API for WFS Administration Web Feature Service (WFS) Support 15-17 boolean genXMLIndex, String featureCollectionNS, String featureCollectionName, boolean isGML3) throws SQLException; public static void publishFeatureType(OracleConnection conn, XMLType schemaDocXt, XMLType featureDescXt, ArrayList docIdPaths, String primarySpatialPath, String featureMemberNS, String featureMemberName, String ftNSUrl, String ftName, ArrayList spatialPaths, ArrayList mandatoryPaths, ArrayList tsPaths, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String ftXSDRefId, boolean genSpatialIndex, boolean lockEnable, ArrayList numPaths, ArrayList idxPaths, ArrayList idxPathTypes, boolean genXMLIndex, String featureCollectionNS, String featureCollectionName, boolean isGML3, CollectionPathInfo collPathInfo) throws SQLException; public static void publishFeatureType(OracleConnection conn, XMLType schemaDocXt, XMLType featureDescXt, ArrayList docIdPaths, String primarySpatialPath, String featureMemberNS, String featureMemberName, String ftNSUrl, String ftName, ArrayList spatialPaths, ArrayList mandatoryPaths, ArrayList tsPaths, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String ftXSDRefId, boolean genSpatialIndex, boolean lockEnable, ArrayList numPaths, ArrayList idxPaths, ArrayList idxPathTypes, boolean genXMLIndex, String featureCollectionNS, String featureCollectionName, boolean isGML3, CollectionPathInfo collPathInfo, boolean hasMultipleSRSNS) throws SQLException; Java API for WFS Administration 15-18 Oracle Spatial Developer's Guide conn is an Oracle Database connection for a user that has been granted the DBA role. featureTypeMD is the feature type path registration metadata. This metadata must conform to the featureTypeMd element definition as specified in the wstype_ md.xsd file. An example of feature type path registration metadata XML is provided in ft_metadata.xml. These files are included in the ws_client.jar demo file (described in Section 10.4) under the src/data/ path. For information about using the example to publish a feature type, see the Readme.txt file, which is included in ws_client.jar under the src/ path. schemaDocXt is the XML schema definition (XSD) of the feature type. featureDescXt is the XML schema definition (XSD) of the feature type description, to be included in the Capabilities document. docIdPaths is a list of document ID path elements where each element is a String. primarySpatialPath is the primary spatial path that will be used to compute the bounding box in the result. featureMemberNS is the namespace of the feature member. featureMemberName is the name of the feature member. ftNSUrl is the URL of the namespace of the feature type. ftName is the name of the feature type. spatialPaths is a list of spatial paths in the feature type. It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 15.4.7.1. mandatoryPaths is a list of mandatory paths in the feature type. It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 15.4.7.1. tsPaths is a list of time-related paths in the feature type (for example, date, dateTime, gYear, gMonth, gDay, gMonthDay, and gYearMonth). It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 15.4.7.1. sdoMetaInfo is the spatial metadata information for spatial paths. It is an ArrayList of class oracle.spatial.ws.GeomMetaInfo, which is described in Section 15.4.7.1. srsNS is the user-defined namespace of the spatial reference system (coordinate system) associated with the data in the spatial paths. This namespace (if specified) is also used to generate the srsName attribute in the element of the FeatureCollection result generated for the GetFeature request. srsNSAlias is the namespace alias of the spatial reference system (coordinate system) associated with the data in the spatial paths. ftXSDRefId is the group feature type XML schema definition file name (as a string), for cases where multiple feature types are defined in a single XSD file. This parameter is used to store the group XSD definition once in the WFS metadata, and then refer to it from multiple feature types whose schema definitions are present in the group feature type XSD file. genSpatialIndex is a Boolean value: TRUE causes a spatial index to be created on the feature type at type creation time; FALSE does not cause a spatial index to be created. lockEnable is a Boolean value: TRUE causes the feature type table (the underlying system-generated table where instances of this feature type are stored) to be lock-enabled at type creation time; FALSE does not cause the feature type table to be Java API for WFS Administration Web Feature Service (WFS) Support 15-19 lock-enabled. If lockEnable is TRUE, this will WFS-transaction lock enable the WFS data table for the feature type. (This data table is automatically generated when the feature type is published.) numPaths is a list of numeric (NUMBER, INTEGER, and so on) related paths in the feature type. It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 15.4.7.1. idxPaths is the index path list. It is list of paths on which to create an index of type XDB.XMLINDEX when that index is created. It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 15.4.7.1. idxPathTypes specifies information about each index path, where each element of string[3] contains the following: string[0] is the type name, string[1] is the type format (such as the type length), and string[2] specifies whether a Btree or unique index, or no index, should be created (WFSAdmin.BTREE, WFSAdmin.UNIQUE, or null). genXMLIndex is a Boolean value: TRUE causes an index of type XDB.XMLINDEX to be created on the document-based feature type; FALSE does not cause an index of type XDB.XMLINDEX to be created on the document-based feature type. If you choose not to create the index now, you can create it later using the createXMLTableIndex method (described in Section 15.4.1). featureCollectionNS is the namespace of the feature collection. featureCollectionName is the name of the feature collection. isGML3 is a Boolean value: TRUE means that the geometries inside instances of this feature type are GML3.1.1 compliant; FALSE means that the geometries inside instances of this feature type are GML 2.1.2 compliant. collPathInfo is spatial collection path information. hasMultipleSRSNS is a Boolean value: TRUE means that this feature type refers to multiple user-defined spatial reference system namespaces; FALSE means that this feature type does not refer to multiple user-defined spatial reference system namespaces. 15.4.7.1 Related Classes for publishFeatureType This section describes some classes used in the definition of parameters of the publishFeatureType method. oracle.spatial.ws.PathElement is a Java class that contains a pair of String objects: the PathElement namespace am the PathElement name. This class includes the getValue() method, which returns a string format of the PathElement object. This class has the following format: public class PathElement { // Set namespace and name information for a PathElement. public void set(String ns, String name); //Get a string value for the PathElement object. public String getValue() ; } oracle.spatial.ws.Path is a Java class that contains an ordered list of PathElement objects that constitute the path. For example, if an XPath is myns:A/myns:B, then myns:A and myns:B are PathElement objects. This class includes the getValue() method, which returns a string format of the Path object. This class has the following format: public class Path { Java API for WFS Administration 15-20 Oracle Spatial Developer's Guide //Add a PathElement. public void add(PathElement p) ; //Get a string Value for the Path object. public String getValue() ; } oracle.spatial.ws.PathInfo is a container class that contains information about a path or list of paths, including their association and metadata information. This class has the following format: public class PathInfo { // Set number of occurrences for the Path. Default value is 1. Number of // occurrences > 1 in case of arrays. public void setNumOfOccurrences(int i) ; // Get number of occurrences for the Path. public int getNumOfOccurrences(); // Add a path, in case PathInfo has multiple paths associated via a // choice association public void addPath(Path p) ; // Add path type information. This is relevant for time-related Paths // (for example, date, dateTime, gDay, gMonth, gYear, gMonthDay, // gYearMonth, duration, or time). public void addPathType(String t) ; // Add a PathInfo type. This can be PathInfo.CHOICE or // PathInfo.DEFAULT or PathInfo.COLLECTION. // PathInfo.CHOICE - means that the list of paths in this PathInfo are // related to each other via choice association. For example, we may have // a list of Spatial Paths, which are associated with one another via choice. // So, only one of these path can occur in a feature instance/document. // PathInfo.COLLECTION - means the list of paths in this PathInfo are part // of a collection (currently spatial collections are // supported) which will be indexed. // Default value is PathInfo.DEFAULT for one Path or a finite array Paths. // @param t PathInfo type information. PathInfo.CHOICE or // PathInfo.DEFAULT or PathInfo.COLLECTION public void addPathInfoType(int t) ; // Returns a string representation for PathInfo content. public String getPathContent() ; // Returns Path type information (for example, date, dateTime, gDay, gMonth, // gYear, gMonthDay, gYearMonth, duration, or time). public String getPathType() ; // Returns a string representation for PathInfo path content. // param i The index of the path in the PathInfo whose path content needs to // be returned // @return a string representation for PathInfo path content public String getCollectionPathContent(int i); // Returns number of paths in the PathInfo. // @return number of paths in the PathInfo which is of type PathInfo.COLLECTION // if PathInfo is not of type PathInfo.COLLECTION returns -1 public int getCollectionPathContentSize(); } Java API for WFS Administration Web Feature Service (WFS) Support 15-21 oracle.spatial.ws.CollectionPathInfo is a container class that contains information about a collection of PathInfo objects. Each PathInfo object in this collection, represents a group of spatial paths that will be indexed and searched on. This class will be used to register paths referring to spatial collection-based content in feature and record types. This class has the following format: public class CollectionPathInfo { /** * Add a PathInfo. * @param p PathInfo to be added * @param g geometry related metadata for PathInfo to be added */ public void addPathInfo(PathInfo p, GeomMetaInfo g) ; /** * Get a PathInfo. * @param i index of the PathInfo to be retrieved */ public PathInfo getPathInfo(int i) ; /** * Get geometry related metadata for a certain PathInfo. * @param i index of the PathInfo whose geomMetaInfo is to be retrieved */ public GeomMetaInfo getGeomMetaInfo(int i) ; /** * Get all PathInfo objects in this CollectionPathInfo. */ public ArrayList getPathInfos() ; } oracle.spatial.ws.GeomMetaInfo is a class that contains dimension-related information corresponding to a spatial path in a feature type. This information includes the dimension name, the lower and upper bounds, the tolerance, and the coordinate system (SRID). This class has the following format: public class GeomMetaInfo { // Default constructor. Creates a GeomMetaInfo object with number of // dimensions equal to 2. public GeomMetaInfo() ; // Creates a GeomMetaInfo object of a specified number of dimensions. // Parameter numOfDimensions is the number of dimensions represented // in the GeomMetaInfo object. // Note: max number of dimensions supported is 4. public GeomMetaInfo(int numOfDimensions) throws ArrayIndexOutOfBoundsException ; //Set Dimension Name. // Parameter index represents the dimension index which needs to be set. // Parameter val is dimension name value. public void setDimName(int index, String val) throws ArrayIndexOutOfBoundsException ; // Set Dimension Lower Bound. // Parameter index represents the dimension index which needs to be set. // Parameter val is dimension lower bound value. Java API for WFS Administration 15-22 Oracle Spatial Developer's Guide public void setLB(int index, double val) throws ArrayIndexOutOfBoundsException ; // Set Dimension Upper Bound // Parameter index represents the dimension index which needs to be set. // Parameter val is dimension upper bound value public void setUB(int index, double val) throws ArrayIndexOutOfBoundsException ; // Set Dimension tolerance value. // Parameter index represents the dimension index which needs to be set. // Parameter val is dimension tolerance value. public void setTolerance(int index, double val) throws ArrayIndexOutOfBoundsException ; // Set Coordinate Reference System Identifier public void setSRID (int val) ; // Get dimension Name. // Parameter index represents the dimension index whose name needs to be // returned. This method returns the dimension name for the given index. public String getDimName(int index) throws ArrayIndexOutOfBoundsException ; // Get dimension lower bound. // Parameter index represents the dimension index whose lower bound needs // to be returned. // This method returns the lower bound for the given index. public double getLB(int index) throws ArrayIndexOutOfBoundsException ; // Get dimension upper bound. // Parameter index represents the dimension index whose upper bound needs // to be returned. // This method returns the upper bound for the given index. public double getUB(int index) throws ArrayIndexOutOfBoundsException ; // Get dimension tolerance. // Parameter index represents the dimension index whose tolerance needs // to be returned. // This method returns the tolerance value for the given index. public double getTolerance(int index) throws ArrayIndexOutOfBoundsException ; // Get coordinate system (spatial reference system) identifier. public int getSRID () ; // Get number of dimensions represented by this GeomMetaInfo object. public int getNumOfDimensions() ; // Sets the spatial index dimension parameter. By default it is 2. // return Coordinate Reference System Identifier value public int setSpatialIndexDimension(int d) ; // Get the spatial index dimension parameter. // return number of dimensions public int getSpatialIndexDimension() ; // Sets the user spatial srs namespace refered by this GeomMetaInfo object. // Needs to be specified if multiple srs namespace are refered within the same //feature or record type. Java API for WFS Administration Web Feature Service (WFS) Support 15-23 public void setSRSNS(String s) ; // Gets the user defined spatial srs namespace refered by this // GeomMetaInfo object. public String getSRSNS() ; // Sets the user defined spatial srs namespace alias refered by this // GeomMetaInfo object. public void setSRSNSAlias (String s) ; // Gets the user defined spatial srs namespace alias refered by this // GeomMetaInfo object. public String getSRSNSAlias () ; } 15.4.8 revokeFeatureTypeFromUser method The revokeFeatureTypeFromUser method revokes access to a feature type from a database user. This method has the following format: public static void revokeFeatureTypeFromUser( OracleConnection conn, String typeNS, String typeName, String usrName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNS is the URL of the namespace of the feature type. typeName is the name of the feature type. usrName is the name of the database user. 15.4.9 revokeMDAccessFromUser method The revokeMDAccessFromUser method revokes access to the WFS metadata from a database user. This method has the following format: public static void revokeMDAccessFromUser( OracleConnection conn, String usrName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. usrName is the name of the database user. 15.4.10 setXMLTableIndexInfo method The setXMLTableIndexInfo method updates the XMLTableIndex index information for a document-based feature type, with the option of creating the index. This method has the following format: public static void setXMLTableIndexInfo(OracleConnection conn, String ftNSUrl, Note: If the XMLTableIndex index already exists, you must drop it (using the dropXMLTableIndex method) before you call the setXMLTableIndexInfo method. Using WFS with Oracle Workspace Manager 15-24 Oracle Spatial Developer's Guide String ftName, ArrayList idxPaths, ArrayList idxPathTypes, boolean genXMLIndex) throws SQLException , WFSException; conn is an Oracle Database connection for a user that has been granted the DBA role. ftNSUrl is the URL of the namespace of the feature type. ftName is the name of the feature type. idxPaths is the index path list. It is list of paths on which to create an index of type XDB.XMLINDEX when that index is created. It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 15.4.7.1. idxPathTypes specifies information about each index path, where each element of string[3] contains the following: string[0] is the type name, string[1] is the type format (such as the type length), and string[2] specifies whether a Btree or unique index, or no index, should be created (WFSAdmin.BTREE, WFSAdmin.UNIQUE, or null). genXMLIndex is a Boolean value: TRUE causes an index of type XDB.XMLINDEX to be created on the document-based feature type; FALSE does not cause an index of type XDB.XMLINDEX to be created on the document-based feature type. If you choose not to create the index now, you can create it later using the createXMLTableIndex method (described in Section 15.4.1). 15.5 Using WFS with Oracle Workspace Manager You can use Oracle Workspace Manager to version-enable a WFS table with relational features. To do so, first register the WFS table using the SDO_WFS_ LOCK.RegisterFeatureTable procedure; then execute the DBMS_WM.EnableVersioning procedure. (For information about Workspace Manager, including reference documentation for the DBMS_WM PL/SQL package, see Oracle Database Workspace Manager Developer's Guide.) You can create workspaces and perform transactional WFS changes to these workspaces by using the WFS-T (Web Feature Services transaction) interfaces. However, to use interfaces other than WFS-T, you must use a SQL*Plus session for which database transactions are enabled on the WFS tables. These database transactions include the following: ■ Update and delete operations on WFS tables ■ Workspace maintenance operations, such as refreshing a workspace or merging workspaces To enable database transactions on the WFS tables, call the SDO_WFS_ LOCK.EnableDBTxns procedure (documented in Chapter 33). After you execute this procedure, database transactions are permitted on the WFS tables and WFS-T semantics are maintained for WFS transactions, until the end of the session. 16 Catalog Services for the Web (CSW) Support 16-1 16 Catalog Services for the Web (CSW) Support This chapter describes the Oracle Spatial implementation of the Open GIS Consortium specification for catalog services. According to this specification: "Catalogue services support the ability to publish and search collections of descriptive information (metadata) for data, services, and related information objects. Metadata in catalogues represent resource characteristics that can be queried and presented for evaluation and further processing by both humans and software. Catalogue services are required to support the discovery and binding to registered information resources within an information community." The Oracle Spatial implementation will be referred to as Catalog Services for the Web, or CSW This chapter includes the following major sections: ■ Section 16.1, "CSW Engine and Architecture" ■ Section 16.2, "CSW APIs and Configuration" ■ Section 16.3, "Request and Response XML Examples" ■ Section 16.4, "Java API for CSW Administration" 16.1 CSW Engine and Architecture This section describes CSW, including its relationship to clients and to the database server. CSW is implemented as a Web service and can be deployed in Oracle Containers for Java (OC4J), which is included with Oracle Application Server. CSW has a metadata layer, which stores in the database the metadata needed to reply to catalog requests. The metadata includes spatial columns, which can be queried and processed using Oracle Spatial interfaces. The metadata also stores the association of nonspatial and spatial attributes of records, as well as the services that the catalog service provides to its clients. Note: Before you use CSW, be sure that you understand the concepts described in Chapter 10, "Introduction to Spatial Web Services", and that you have performed any necessary configuration work as described in that chapter. If you have data from a previous release that was indexed using one or more SYS.XMLTABLEINDEX indexes, you must drop the associated indexes before the upgrade and re-create the indexes after the upgrade, as described in Section A.2. CSW APIs and Configuration 16-2 Oracle Spatial Developer's Guide Figure 16–1 shows the CSW architecture. Figure 16–1 CSW Architecture As shown in Figure 16–1: ■ CSW is part of a container in the Oracle Application Server middle tier. ■ CSW can communicate with a Web service client using CSW requests and responses in SOAP/XML format. ■ CSW performs spatial data and metadata access through JDBC calls to the database. ■ The database includes Oracle Spatial with CSW metadata and data. CSW security is implemented using secure transport. User identities and user labels are managed in LDAP, and the middle tier and CSW security combine to perform authentication. Oracle label-based security is used for managing user privileges at the record level. 16.2 CSW APIs and Configuration The CSW APIs enable you to perform operations that include: ■ Specifying information about record type domains and record view transformations ■ Publishing record types ■ Dropping (unpublishing) record types ■ Granting to users and revoking from users privileges on CSW record types Chapter 22 describes the PL/SQL API (SDO_CSW_PROCESS package), Section 16.3 provides examples of XML requests and responses, and Section 16.4 describes the Java API. Client Middle Tier (Oracle Application Server) Database JDBC Oracle CSW Request &Response (SOAP/XML) Application Using Catalog Spatial DB with CSW Metadata Container Catalog Service Resource or Service OGC Service Interfaces describes CSW APIs and Configuration Catalog Services for the Web (CSW) Support 16-3 16.2.1 Capabilities Documents A capabilities document describes an instance of a capability. The document specifies a record type and the type of operations supported (such as insert and delete). A capabilities document is generated by the CSW server in response to a GetCapabilities request. The CSW server uses a capabilities template, and adds information about the record type and operations to this template to create the capabilities document. The client can use the HTTP GET method to access this capabilities document using either the SOAP interface or the XML interface: ■ For the SOAP interface, use oracle.spatial.ws.servlet.CSWServlet, which can be accessed at an address in the following format: http:///machine-name:port/SpatialWS-SpatialWS-context-root/cswservlet?request=G etCapabilities&service=CSW&acceptversion=2.0.0&outputFormat=text/xml ■ For the XML interface, use oracle.spatial.ws.servlet.CSWXMLServlet, which can be accessed at an address in the following format: http:///machine-name:port/SpatialWS-SpatialWS-context-root/xmlcswservlet?reques t=GetCapabilities&service=CSW&acceptversion=2.0.0&outputFormat=text/xml In the preceding formats: ■ machine-name is the name of the system where the OC4J server is running. ■ port is the port number where the OC4J server is running. ■ SpatialWS-SpatialWS-context-root is the default root where the Spatial Web services application is mounted. ■ cswservlet is the servlet-mapping url-pattern for oracle.spatial.ws.servlet.CSWServlet, as specified by default in the web.xml file. ■ xmlcswservlet is the servlet-mapping url-pattern for oracle.spatial.ws.servlet.CSWXMLServlet, as specified by default in the web.xml file. 16.2.2 Spatial Path Extractor Function (extractSDO) If you need CSW to process any spatial content that is not in GML format, you must create a user-defined function named extractSDO to extract the spatial path information. This function must be implemented for each record type that has spatial content in non-GML format and on which you want to create a spatial index. (This function is not needed if all spatial content for a record type is in GML format.) This function must be registered, as explained in Section 16.2.2.1, so that the Oracle Spatial CSW server can find and invoke this function when it needs to extract spatial path content that is not in GML format. The extractSDO function has the following format: extractSDO( xmlData IN XMLType, srsNs IN VARCHAR2, spPathsSRSNSList IN MDSYS.STRINGLISTLIST); ) RETURN MDSYS.SDO_GEOM_PATH_INFO; CSW APIs and Configuration 16-4 Oracle Spatial Developer's Guide Parameters xmlData Data of the record instance from which spatial path information needs to be extracted. srsNs User-defined namespace of the spatial reference system (coordinate system) associated with the spatial data for the feature type. This namespace (if specified) is also used to generate the srsName attribute in the element of the FeatureCollection result generated for the GetFeature request. spPathsSRSNSList If a record type has multiple user-defined spatial reference system namespaces associated with different spatial paths, this parameter specifies the list of spatial reference system namespace information corresponding to the different spatial paths specified during type registration. It is an object of type MDSYS.STRINGLISTLIST, which is defined as VARRAY(1000000) OF MDSYS.STRINGLIST, and where MDSYS.STRINGLIST is defined as VARRAY(1000000) OF VARCHAR2(4000). If a record type does not have multiple user-defined spatial reference system namespaces associated with different spatial columns, this parameter should be null. In each MDSYS.STRINGLIST object, the first element is the spatial reference system namespace, and second element is the spatial reference system namespace alias (if any). Usage Notes This function parses the non-GML spatial content and returns an object of type MDSYS.SDO_GEOM_PATH_INFO, which is defined as follows: (path MDSYS.STRINGLIST, geom SDO_GEOMETRY, arrindex NUMBER) The path attribute specifies path to the spatial content that is to be extracted and stored in the geom attribute. It is an object of MDSYS.STRINGLIST, which is defined as: VARRAY(1000000) OF VARCHAR2(4000). The path attribute has the following pattern: MDSYS.STRINGLIST('pe_namespace1','pe_name1', 'pe_ namespace2','pe_name2',...); where: ■ pe_namespace1 is the namespace of the first path element. ■ pe_name1 is the name of the first path element. ■ pe_namespace2 is the namespace of the second path element. ■ pe_name2 is the name of the second path element. ■ and so on, for any remaining namespace and name pairs. In the path, /typeNameNSAlias:typeName/pe_namespace1_Alias:pe_ name1/pe_namespace2_Alias:pe_name2... is an XPath representation of spatial content, in non-GML format, that will be extracted by the user-defined function extractSDO: ■ typeNameNSAlias is an alias to record type name namespace. ■ typeName is the type name of the record type. ■ pe_namespace1_Alias is a namespace alias for namespace pe_namespace1 ■ pe_namespace2_Alias is a namespace alias for namespace pe_namespace2. Request and Response XML Examples Catalog Services for the Web (CSW) Support 16-5 The geom attribute is the spatial content (corresponding to the path parameter) extracted as an SDO_GEOMETRY object. The extracted geometry can then be indexed using a spatial index. The arrindex attribute is not currently used, and should be set to 1. (It is reserved for future use as an array index of paths.) 16.2.2.1 Registering and Unregistering the extractSDO Function After you create the extractSDO function, you must register it to enable it to be used for processing spatial path content in record types that is not in GML format. To register the function, call the SDO_CSW_PROCESS.InsertPluginMap procedure. For example: BEGIN SDO_CSW_PROCESS.insertPluginMap('http://www.opengis.net/cat/csw', 'Record', 'csw_admin_usr.csw_RT_1_package'); END; / If you no longer want the extractSDO function to be used for processing spatial path content that is not in GML format, you can unregister the function by calling the SDO_ CSW_PROCESS.DeletePluginMap procedure. For example: BEGIN SDO_CSW_PROCESS.deletePluginMap('http://www.opengis.net/cat/csw', 'Record'); END; / 16.3 Request and Response XML Examples This section presents some record requests to the CSW engine, and the response to each request, for each of the following operations: ■ GetCapabilities ■ DescribeRecord ■ GetRecords ■ GetDomain ■ GetRecordById ■ Transaction, with a subelement specifying the transaction type: – Insert – Update – Delete Example 16–1 is a request to get the capabilities of the CSW server named CSW at a specified namespace URL. T.his request will return a capabilities document, as explained in Section 16.2.1 Example 16–1 GetCapabilities Request 2.0.0 Request and Response XML Examples 16-6 Oracle Spatial Developer's Guide text/xml Example 16–2 is an excerpt of the response from the request in Example 16–1. Example 16–2 GetCapabilities Response CSW 2.0.0 Company CSW A catalogue service that conforms to the HTTP protocol binding of the OpenGIS Catalogue Service specification version 2.0.0. CSW Company Name geospatial catalogue NONE NONE Company Name Contact Person Name Staff 999-999-9999 999-999-9999 1 Street Name CityName StateName 09999 USA contact.person@example.com Request and Response XML Examples Catalog Services for the Web (CSW) Support 16-7 ns0:SampleRecordns1:Record text/xml XMLSCHEMA ns0:SampleRecordns1:Record text/xml OGCCORE hits results validate brief summary full Filter Request and Response XML Examples 16-8 Oracle Spatial Developer's Guide brief summary full GetRecords.resultType GetRecords.outputFormat GetRecords.outputRecType GetRecords.typeNames GetRecords.ElementSetName GetRecords.ElementName GetRecords.CONSTRAINTLANGUAGE GetRecordById.ElementSetName DescribeRecord.typeName DescribeRecord.schemaLanguage CSW 2.0.0 Request and Response XML Examples Catalog Services for the Web (CSW) Support 16-9 Example 16–3 is a request to describe the record with the type name Record for a specified namespace. Example 16–3 DescribeRecord Request Record Example 16–4 is the response from the request in Example 16–3. The response is an XML schema definition (XSD). See the elements in the response for explanatory comments. Example 16–4 DescribeRecord Response http://schemas.opengis.net/csw/2.0.0/record This schema defines the basic record types that are common to all CSW implementations. An application profile may extend AbstractRecordType to represent model-specific content. Request and Response XML Examples 16-10 Oracle Spatial Developer's Guide This type encapsulates all of the standard DCMI metadata terms, including the Dublin Core refinements; these terms may be mapped to the profile-specific information model. This type defines a brief representation of the common record format. It extends AbstractRecordType to include only the dc:identifier and dc:type properties. This type defines a summary representation of the common record format. It extends AbstractRecordType to include the core properties. Request and Response XML Examples Catalog Services for the Web (CSW) Support 16-11 This type extends DCMIRecordType to add ows:BoundingBox; it may be used to specify a bounding envelope for the catalogued resource. Example 16–5 is a request to get records where the contributor is equal to Raja. Example 16–5 GetRecords Request /csw:Record/dc:identifier /csw:Record/dc:contributor /csw:Record/dc:contributor Raja Note: Spatial Catalog Service in Oracle Database Release 11.1 supports only synchronous processing of GetRecords requests. Request and Response XML Examples 16-12 Oracle Spatial Developer's Guide Example 16–6 is the response from the request in Example 16–5. Example 16–6 GetRecords Response 4 Raja REC-1 Example 16–7 is a request to get domain information related to a record type. Example 16–7 GetDomain Request GetRecords.resultType Example 16–8 is the response from the request in Example 16–7. Example 16–8 GetDomain Response GetRecords.resultType hits results validate GetRecords.resultType hits results validate Request and Response XML Examples Catalog Services for the Web (CSW) Support 16-13 Example 16–9 is a request to get the record with the record ID value REC-1. Example 16–9 GetRecordById Request REC-1 brief Example 16–10 is the response from the request in Example 16–9. Example 16–10 GetRecordById Response REC-1 Example 16–11 is a request to insert a record for contributor John. The record has an ID value of REC-2, and has the spatial attribute of the specified bounding box (optimized rectangle: lower-left and upper-right coordinates). Example 16–11 Insert Request John REC-2 12 12 102 102 Example 16–12 is the response from the request in Example 16–11. Request and Response XML Examples 16-14 Oracle Spatial Developer's Guide Example 16–12 Insert Response 1 Example 16–13 is a request to update the contributor value to Jane in the record where the current contributor value is John (that is, change the value from John to Jane). Example 16–13 Update Request /csw:Record/dc:contributor Jane /csw:Record/dc:contributor John Example 16–14 is the response from the request in Example 16–13. Example 16–14 Update Response 1 Example 16–15 is a request to delete the record where the contributor value is equal to Jane. Example 16–15 Delete Request /csw:Record/dc:contributor Jane Example 16–16 is the response from the request in Example 16–15. Example 16–16 Delete Response 1 16.4 Java API for CSW Administration In addition to the PL/SQL APIs in the SDO_CSW_PROCESS package, you can use a Java API to publish and drop record types, and to grant and revoke access to record types and CSW metadata tables. This section provides basic reference information about the methods in the oracle.spatial.csw.CSWAdmin class. The methods are presented in alphabetical order. 16.4.1 createXMLTableIndex method The createXMLTableIndex method creates an index of XDB.XMLINDEX on record type instances. This method has the following format: public static void createXMLTableIndex( OracleConnection conn, String typeNS, String typeName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNS is the URL of the namespace of the record type. typeName is the name of the record type. 16.4.2 deleteDomainInfo method The deleteDomainInfo method deletes domain information related to the record type. This method has the following format: public static void deleteDomainInfo( OracleConnection conn, Java API for CSW Administration 16-16 Oracle Spatial Developer's Guide int recordTypeId, String parameterName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. recordTypeId is the ID of the record type. parameterName is the name of the domain parameter to be deleted. 16.4.3 deleteRecordViewMap method The deleteRecordViewMap method deletes information related to record view transformation. This method has the following format: public static void deleteRecordViewMap( OracleConnection conn, String recordTypeNS, String viewSrcName, String targetTypeName, String mapType) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. recordTypeNS is the URL of the namespace of the record type. viewSrcName is the name of the source of the record type. targetTypeName is the name of the destination of the record type. mapType is the map type (brief, summary, and so on). 16.4.4 disableVersioning method The disableVersioning method disables versioning for a record type. This method has the following format: public static void disableVersioning( OracleConnection conn, String rtNSUrl, String rtName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. rtNSUrl is the URL of the namespace of the record type. rtName is the name of the record type. 16.4.5 dropRecordType method The dropRecordType method deletes a record type from the CSW repository. This method has the following format: public static void dropRecordType( OracleConnection conn, String rtNSUrl, String rtName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. rtNSUrl is the URL of the namespace of the record type. rtName is the name of the record type. Java API for CSW Administration Catalog Services for the Web (CSW) Support 16-17 16.4.6 dropXMLTableIndex method The dropXMLTableIndex method drops an index of type XDB.XMLINDEX that was created on record type instances. This method has the following format: public static void dropXMLTableIndex( OracleConnection conn, String typeNS, String typeName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNS is the URL of the namespace of the record type. typeName is the name of the record type. 16.4.7 enableVersioning method The enableVersioning method enables versioning for a record type. This method has the following format: public static void enableVersioning( OracleConnection conn, String rtNSUrl, String rtName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. rtNSUrl is the URL of the namespace of the record type. rtName is the name of the record type. 16.4.8 getIsXMLTableIndexCreated method The getIsXMLTableIndexCreated method returns a Boolean TRUE if an index of type XDB.XMLINDEX has been created on a record type, or a Boolean FALSE if such an index has not been created. This method has the following format: public static boolean getIsXMLTableIndexCreated( OracleConnection conn, String typeNS, String typeName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNS is the URL of the namespace of the record type. typeName is the name of the record type. 16.4.9 getRecordTypeId method The getRecordTypeId method returns the record type ID for a specified combination of namespace and record type. This method has the following format: public static boolean getIRecordTypeId( OracleConnection conn, String typeNamespace, String typeName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNamespace is the URL of the namespace of the record type. Java API for CSW Administration 16-18 Oracle Spatial Developer's Guide typeName is the name of the record type. 16.4.10 grantMDAccessToUser method The grantMDAccessToUser method grants access to the CSW metadata to a database user. This method has the following format: public static void grantMDAccessToUser( OracleConnection conn, String usrName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. usrName is the name of the database user. 16.4.11 grantRecordTypeToUser method The grantRecordTypeToUser method grants access to a record type to a database user. This method has the following format: public static void grantRecordTypeToUser( OracleConnection conn, String typeNS, String typeName, String usrName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNS is the URL of the namespace of the record type. typeName is the name of the record type. usrName is the name of the database user. 16.4.12 publishRecordType method The publishRecordType method publishes a record type; that is, it registers metadata related to the record type. This method has the following formats: public static void publishRecordType(OracleConnection conn, XMLType recordTypeMD) throws SQLException , CSWException; public static void publishRecordType(OracleConnection conn, String typeNS, String typeName, ArrayList idPaths, ArrayList spatialPaths, ArrayList tsPaths, XMLType schemaDoc, XMLType briefXSLPattern, XMLType summaryXSLPattern, XMLType dcmiXSLPattern, ArrayList srsPaths, String idExtractorType, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias) throws SQLException ; public static void publishRecordType(OracleConnection conn, String typeNS, String typeName, ArrayList idPaths, ArrayList spatialPaths, Java API for CSW Administration Catalog Services for the Web (CSW) Support 16-19 ArrayList tsPaths, XMLType schemaDoc, XMLType briefXSLPattern, XMLType summaryXSLPattern, XMLType dcmiXSLPattern, ArrayList srsPaths, String idExtractorType, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String rtXSDRefId, boolean genSpatialIndex, boolean setDomainInfo, Hashtable> domainInfo, boolean setRecordViewMap, ArrayList> recordViewMap) throws SQLException ; public static void publishRecordType(OracleConnection conn, String typeNS, String typeName, ArrayList idPaths, ArrayList spatialPaths, ArrayList tsPaths, XMLType schemaDoc, XMLType briefXSLPattern, XMLType summaryXSLPattern, XMLType dcmiXSLPattern, ArrayList srsPaths, String idExtractorType, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String rtXSDRefId, boolean genSpatialIndex, boolean setDomainInfo, Hashtable> domainInfo, boolean setRecordViewMap, ArrayList> recordViewMap, ArrayList numPaths, ArrayList idxPaths, ArrayList idxPathTypes, boolean genXMLIndex) throws SQLException ; public static void publishRecordType(OracleConnection conn, String typeNS, String typeName, ArrayList idPaths, ArrayList spatialPaths, ArrayList tsPaths, XMLType schemaDoc, XMLType briefXSLPattern, XMLType summaryXSLPattern, XMLType dcmiXSLPattern, ArrayList srsPaths, String idExtractorType, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String rtXSDRefId, boolean genSpatialIndex, boolean setDomainInfo, Hashtable> domainInfo, boolean setRecordViewMap, ArrayList> recordViewMap, Java API for CSW Administration 16-20 Oracle Spatial Developer's Guide ArrayList numPaths, ArrayList idxPaths, ArrayList idxPathTypes, boolean genXMLIndex, boolean isGML3) throws SQLException ; public static void publishRecordType(OracleConnection conn, String typeNS, String typeName, ArrayList idPaths, ArrayList spatialPaths, ArrayList tsPaths, XMLType schemaDoc, XMLType briefXSLPattern, XMLType summaryXSLPattern, XMLType dcmiXSLPattern, ArrayList srsPaths, String idExtractorType, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String rtXSDRefId, boolean genSpatialIndex, boolean setDomainInfo, Hashtable> domainInfo, boolean setRecordViewMap, ArrayList> recordViewMap, ArrayList numPaths, ArrayList idxPaths, ArrayList idxPathTypes, boolean genXMLIndex, boolean isGML3, CollectionPathInfo collPathInfo) throws SQLException; public static void publishRecordType(OracleConnection conn, String typeNS, String typeName, ArrayList idPaths, ArrayList spatialPaths, ArrayList tsPaths, XMLType schemaDoc, XMLType briefXSLPattern, XMLType summaryXSLPattern, XMLType dcmiXSLPattern, ArrayList srsPaths, String idExtractorType, ArrayList sdoMetaInfo, String srsNS, String srsNSAlias, String rtXSDRefId, boolean genSpatialIndex, boolean setDomainInfo, Hashtable> domainInfo, boolean setRecordViewMap, ArrayList> recordViewMap, ArrayList numPaths, ArrayList idxPaths, ArrayList idxPathTypes, boolean genXMLIndex, boolean isGML3, CollectionPathInfo collPathInfo, boolean hasMultipleSRSNS) throws SQLException; Java API for CSW Administration Catalog Services for the Web (CSW) Support 16-21 conn is an Oracle Database connection for a user that has been granted the DBA role. recordTypeMD is the record type registration metadata. This metadata must conform to the recordTypeMd element definition as specified in the wstype_md.xsd file. Examples of record type path registration metadata XML are provided in rt_ metadata1.xml and rt_metadata2.xml. These files are included in the ws_ client.jar demo file (described in Section 10.4) under the src/data/ path. For information about using the examples to publish record types, see the Readme.txt file, which is included in ws_client.jar under the src/ path. typeNS is the URL of the namespace of the record type. typeName is the name of the record type. idPaths is a list of record ID path elements where each element is a String. spatialPaths is a list of spatial paths in the record type. It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 16.4.12.1. tsPaths is a list of time-related paths in the record type (for example, date, dateTime, gYear, gMonth, gDay, gMonthDay, and gYearMonth). It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 16.4.12.1. schemaDoc is the XML schema definition (XSD) of the record type. briefXSLPattern is the XSLT mapping for transforming the record structure from full to brief format. summaryXSLPattern is the XSLT mapping for transforming the record structure from summary to brief format. dcmiXSLPattern is the XSLT mapping for transforming the record structure from dcmi to brief format. srsPaths is a list of paths representing spatial reference system information. idExtractorType is Identifier extractor method information (XPATH, USER_FUNC, or NONE). XPATH means that the record identifier will be extracted using an XPath as specified in the idPaths parameter. USER_FUNC means that the record identifier will be extracted by a user-defined function invocation, as specified in the idPaths parameter, to which the entire record document instance will be passed. NONE means that the record identifier will be a system-generated identifier. sdoMetaInfo is the spatial metadata information for spatial paths. It is an ArrayList of class oracle.spatial.ws.GeomMetaInfo, which is described in Section 16.4.12.1. srsNS is the user-defined namespace of the spatial reference system (coordinate system) associated with the data in the spatial paths. srsNSAlias is the namespace alias of the spatial reference system (coordinate system) associated with the data in the spatial paths. rtXSDRefId is the group record type XML schema definition file name (as a string), for cases where multiple record types are defined in a single XSD file. This parameter is used to store the group XSD definition once in the CSW metadata, and then refer to it from multiple record types whose schema definitions are present in the group record type XSD file. genSpatialIndex is a Boolean value: TRUE causes a spatial index to be created on the record type at type creation time; FALSE does not cause a spatial index to be created. Java API for CSW Administration 16-22 Oracle Spatial Developer's Guide setDomainInfo is a Boolean value: TRUE causes domain information for this record type to be set at type creation time; FALSE does not cause domain information for this record type to be set. domainInfo is domain information. setRecordViewMap is a Boolean value: TRUE causes the record view transformation map to be set at type creation time; FALSE does not cause the record view transformation map to be set. recordViewMap is the record view transformation map information (brief to full, summary to full, and dcmi to full). It is of type ArrayList> where the content of each ArrayList is: Object[0] = (String) recordTypeNS, Object[1] = (String) viewSrcName, Object[2] = (String) targetTypeName, Object[3]= (oracle.xdb.XMLType) mapInfo, Object[4] = (String) mapType numPaths is a list of numeric (NUMBER, INTEGER, and so on) related paths in the record type. It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 16.4.12.1. idxPaths is the index path list. It is list of paths on which to create an index of type XDB.XMLINDEX when that index is created. It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 16.4.12.1. idxPathTypes specifies information about each index path, where each element of string[3] contains the following: string[0] is the type name, string[1] is the type format (such as the type length), and string[2] specifies whether a Btree or unique index, or no index, should be created (CSWAdmin.BTREE, CSWAdmin.UNIQUE, or null). genXMLIndex is a Boolean value: TRUE causes an index of type XDB.XMLINDEX to be created on the document-based record type; FALSE does not cause an index of type XDB.XMLINDEX to be created on the document-based record type. If you choose not to create the index now, you can create it later using the createXMLTableIndex method (described in Section 16.4.1). isGML3 is a Boolean value: TRUE means that the geometries inside instances of this record type are GML3.1.1 compliant; FALSE means that the geometries inside instances of this record type are GML 2.1.2 compliant. collPathInfo is spatial collection path information. hasMultipleSRSNS is a Boolean value: TRUE means that this record type refers to multiple user-defined spatial reference system namespaces; FALSE means that this record type does not refer to multiple user-defined spatial reference system namespaces. 16.4.12.1 Related Classes for publishRecordType This section describes some classes used in the definition of parameters of the publishRecordType method. oracle.spatial.ws.PathElement is a Java class that contains a pair of String objects: the PathElement namespace am the PathElement name. This class includes the getValue() method, which returns a string format of the PathElement object. This class has the following format: public class PathElement { // Set namespace and name information for a PathElement. public void set(String ns, String name); //Get a string value for the PathElement object. public String getValue() ; Java API for CSW Administration Catalog Services for the Web (CSW) Support 16-23 } oracle.spatial.ws.Path is a Java class that contains an ordered list of PathElement objects that constitute the path. For example, if an XPath is myns:A/myns:B, then myns:A and myns:B are PathElement objects. This class includes the getValue() method, which returns a string format of the Path object. This class has the following format: public class Path { //Add a PathElement. public void add(PathElement p) ; //Get a string Value for the Path object. public String getValue() ; } oracle.spatial.ws.PathInfo is a container class that contains information about a path or list of paths, including their association and metadata information. This class has the following format: public class PathInfo { // Set number of occurrences for the Path. Default value is 1. Number of // occurrences > 1 in case of arrays. public void setNumOfOccurrences(int i) ; // Get number of occurrences for the Path. public int getNumOfOccurrences(); // Add a path, in case PathInfo has multiple paths associated via a // choice association public void addPath(Path p) ; // Add path type information. This is relevant for time-related Paths // (for example, date, dateTime, gDay, gMonth, gYear, gMonthDay, // gYearMonth, duration, or time). public void addPathType(String t) ; // Add a PathInfo type. This can be PathInfo.CHOICE or // PathInfo.DEFAULT or PathInfo.COLLECTION. // PathInfo.CHOICE - means that the list of paths in this PathInfo are // related to each other via choice association. For example, we may have // a list of Spatial Paths, which are associated with one another via choice. // So, only one of these path can occur in a feature instance/document. // PathInfo.COLLECTION - means the list of paths in this PathInfo are part // of a collection (currently spatial collections are // supported) which will be indexed. // Default value is PathInfo.DEFAULT for one Path or a finite array Paths. // @param t PathInfo type information. PathInfo.CHOICE or // PathInfo.DEFAULT or PathInfo.COLLECTION public void addPathInfoType(int t) ; // Returns a string representation for PathInfo content. public String getPathContent() ; // Returns Path type information (for example, date, dateTime, gDay, gMonth, // gYear, gMonthDay, gYearMonth, duration, or time). public String getPathType() ; // Returns a string representation for PathInfo path content. // param i The index of the path in the PathInfo whose path content needs to Java API for CSW Administration 16-24 Oracle Spatial Developer's Guide // be returned // @return a string representation for PathInfo path content public String getCollectionPathContent(int i); // Returns number of paths in the PathInfo. // @return number of paths in the PathInfo which is of type PathInfo.COLLECTION // if PathInfo is not of type PathInfo.COLLECTION returns -1 public int getCollectionPathContentSize(); } oracle.spatial.ws.CollectionPathInfo is a container class that contains information about a collection of PathInfo objects. Each PathInfo object in this collection, represents a group of spatial paths that will be indexed and searched on. This class will be used to register paths referring to spatial collection-based content in feature and record types. This class has the following format: public class CollectionPathInfo { /** * Add a PathInfo. * @param p PathInfo to be added * @param g geometry related metadata for PathInfo to be added */ public void addPathInfo(PathInfo p, GeomMetaInfo g) ; /** * Get a PathInfo. * @param i index of the PathInfo to be retrieved */ public PathInfo getPathInfo(int i) ; /** * Get geometry related metadata for a certain PathInfo. * @param i index of the PathInfo whose geomMetaInfo is to be retrieved */ public GeomMetaInfo getGeomMetaInfo(int i) ; /** * Get all PathInfo objects in this CollectionPathInfo. */ public ArrayList getPathInfos() ; } oracle.spatial.ws.GeomMetaInfo is a class that contains dimension-related information corresponding to a spatial path in a record type. This information includes the dimension name, the lower and upper bounds, the tolerance, and the coordinate system (SRID). This class has the following format: public class GeomMetaInfo { // Default constructor. Creates a GeomMetaInfo object with number of // dimensions equal to 2. public GeomMetaInfo() ; // Creates a GeomMetaInfo object of a specified number of dimensions. // Parameter numOfDimensions is the number of dimensions represented // in the GeomMetaInfo object. // Note: max number of dimensions supported is 4. public GeomMetaInfo(int numOfDimensions) throws ArrayIndexOutOfBoundsException ; Java API for CSW Administration Catalog Services for the Web (CSW) Support 16-25 //Set Dimension Name. // Parameter index represents the dimension index which needs to be set. // Parameter val is dimension name value. public void setDimName(int index, String val) throws ArrayIndexOutOfBoundsException ; // Set Dimension Lower Bound. // Parameter index represents the dimension index which needs to be set. // Parameter val is dimension lower bound value. public void setLB(int index, double val) throws ArrayIndexOutOfBoundsException ; // Set Dimension Upper Bound // Parameter index represents the dimension index which needs to be set. // Parameter val is dimension upper bound value public void setUB(int index, double val) throws ArrayIndexOutOfBoundsException ; // Set Dimension tolerance value. // Parameter index represents the dimension index which needs to be set. // Parameter val is dimension tolerance value. public void setTolerance(int index, double val) throws ArrayIndexOutOfBoundsException ; // Set Coordinate Reference System Identifier public void setSRID (int val) ; // Get dimension Name. // Parameter index represents the dimension index whose name needs to be // returned. This method returns the dimension name for the given index. public String getDimName(int index) throws ArrayIndexOutOfBoundsException ; // Get dimension lower bound. // Parameter index represents the dimension index whose lower bound needs // to be returned. // This method returns the lower bound for the given index. public double getLB(int index) throws ArrayIndexOutOfBoundsException ; // Get dimension upper bound. // Parameter index represents the dimension index whose upper bound needs // to be returned. // This method returns the upper bound for the given index. public double getUB(int index) throws ArrayIndexOutOfBoundsException ; // Get dimension tolerance. // Parameter index represents the dimension index whose tolerance needs // to be returned. // This method returns the tolerance value for the given index. public double getTolerance(int index) throws ArrayIndexOutOfBoundsException ; // Get coordinate system (spatial reference system) identifier. public int getSRID () ; // Get number of dimensions represented by this GeomMetaInfo object. public int getNumOfDimensions() ; // Sets the spatial index dimension parameter. By default it is 2. // return Coordinate Reference System Identifier value Java API for CSW Administration 16-26 Oracle Spatial Developer's Guide public int setSpatialIndexDimension(int d) ; // Get the spatial index dimension parameter. // return number of dimensions public int getSpatialIndexDimension() ; // Sets the user spatial srs namespace referred to by this GeomMetaInfo object. // Needs to be specified if multiple srs namespace are referred to within // the same feature or record type. public void setSRSNS(String s) ; // Gets the user defined spatial srs namespace referred to by // this GeomMetaInfo object. public String getSRSNS() ; // Sets the user defined spatial srs namespace alias referred to // by this GeomMetaInfo object. public void setSRSNSAlias (String s) ; // Gets the user defined spatial srs namespace alias // referred to by this GeomMetaInfo object. public String getSRSNSAlias () ; } 16.4.13 registerTypePluginMap method The registerTypePluginMap method registers a plugin for processing and extracting spatial content for a record type. This method has the following format: public static boolean registerTypePluginMap( OracleConnection conn, String typeNamespace, String typeName, String packageName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNS is the URL of the namespace of the record type. typeName is the name of the record type. packageName is the name of the PL/SQL package object for the plugin (for example, scott.my_plugin_pkg). 16.4.14 revokeMDAccessFromUser method The revokeMDAccessFromUser method revokes access to the CSW metadata from a database user. This method has the following format: public static void revokeMDAccessFromUser( OracleConnection conn, String usrName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. usrName is the name of the database user. 16.4.15 revokeRecordTypeFromUser method The revokeRecordTypeFromUser method revokes access to a record type from a database user. This method has the following format: Java API for CSW Administration Catalog Services for the Web (CSW) Support 16-27 public static void revokeRecordTypeFromUser( OracleConnection conn, String typeNS, String typeName, String usrName) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNS is the URL of the namespace of the record type. typeName is the name of the record type. usrName is the name of the database user. 16.4.16 setCapabilitiesInfo method The setCapabilitiesInfo method populates the capabilities related information. (For information about capabilities documents, see Section 16.2.1.) This method has the following format: public static void setCapabilitiesInfo(OracleConnection conn, XMLType capabilitiesTemplate) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. capabilitiesTemplate is the Catalog services capabilities document. 16.4.17 setDomainInfo method The setDomainInfo method sets domain information related to the record type. This method has the following format: public static void setDomainInfo(OracleConnection conn, int recordTypeId, String propertyName, String parameterName, ArrayList values) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. recordTypeId is the ID of the record type. propertyName is the name of a domain property. parameterName is the name of a domain parameter. values specifies values for the domain parameter. 16.4.18 setRecordViewMap method The setRecordViewMap method populates information related to record view transformation (for example, from BriefRecord to Record). This method has the following format: public static void setRecordViewMap(OracleConnection conn, String recordTypeNS, String viewSrcName, String targetTypeName, oracle.xdb.XMLType mapInfo, String mapType) throws SQLException; conn is an Oracle Database connection for a user that has been granted the DBA role. Java API for CSW Administration 16-28 Oracle Spatial Developer's Guide recordTypeNS is the URL of the namespace of the record type. viewSrcName is the name of the source of the record type. targetTypeName is the name of the destination of the record type. mapInfo is the XSLT definition of the mapping. mapType is the map type (brief, summary, and so on). 16.4.19 setXMLTableIndexInfo method The setXMLTableIndexInfo method updates the XMLTableIndex index information for a record type, with the option of creating the index. This method has the following format: public static void setXMLTableIndexInfo(OracleConnection conn, String typeNS, String ftName, ArrayList idxPaths, ArrayList idxPathTypes, boolean genXMLIndex) throws SQLException , CSWException; conn is an Oracle Database connection for a user that has been granted the DBA role. typeNS is the URL of the namespace of the record type. ftName is the name of the record type. idxPaths is the index path list. It is list of paths on which to create an index of type XMLTABLEINDEX when that index is created. It is an ArrayList of class oracle.spatial.ws.PathInfo, which is described in Section 16.4.12.1. idxPathTypes specifies information about each index path, where each element of string[3] contains the following: string[0] is the type name, string[1] is the type format (such as the type length), and string[2] specifies whether a Btree or unique index, or no index, should be created (CSWAdmin.BTREE, CSWAdmin.UNIQUE, or null). genXMLIndex is a Boolean value: TRUE causes an index of type XDB.XMLINDEX to be created on the record type; FALSE does not cause an index of type XDB.XMLINDEX to be created on the record type. If you choose not to create the index now, you can create it later using the createXMLTableIndex method (described in Section 16.4.1). Note: If the XMLTableIndex index already exists, you must drop it (using the dropRecordType method) before you call the setXMLTableIndexInfo method. 17 Security Considerations for Spatial Web Services 17-1 17 Security Considerations for Spatial Web Services For Spatial Web services, you will want to make the connection to the database as secure as possible. Security in this context includes the following considerations: ■ Confidentiality: a guarantee that no third party can intercept and decrypt messages between a user and the server ■ Authenticity: a guarantee that no third party can convincingly impersonate another user when connected to the server ■ Integrity: a guarantee that no third party can alter a message between a user and the server without the alteration being detected After authentication reliably determines each user’s identity, users also expect flexible and fine-grained authorization, limiting their access to data and features based on their identity and any privileges associated with that identify. However, many current XML and SOAP interfaces do not adequately cover these aspects of security. This chapter includes the following major sections: ■ Section 17.1, "User Management" ■ Section 17.2, "Access Control and Versioning" ■ Section 17.3, "Deploying and Configuring the .ear File" ■ Section 17.4, "Interfaces for Spatial Web Services" See also the wsclient.jar demo file (described in Section 10.4) for instructions and samples related to security with Spatial Web services. 17.1 User Management For Spatial Web services, several forms of user management are available, affecting how administrators manage external users (that is, the users making SOAP/XML requests) and database users, as well as how users’ credentials are controlled (and thus which data and Web service features these users can access). In the database, a user can be either a database/enterprise user (managed by the system) or an application user (managed in a table). In addition, OC4J might share the user definition of an enterprise user, or it might define an LDAP-managed user separate from any database user (such as using the same name as an existing database user but not necessarily the same authentication as that database user). Generally, a user will make SOAP requests, for example, by providing the user name John and the authentication secret. In this scenario, John must be an OC4J user. User Management 17-2 Oracle Spatial Developer's Guide (The administrator can use LDAP, LDAP/XML, and other methods for OC4J user management.) User management in the database is linked to identity propagation, which is described in Section 17.1.1. 17.1.1 Identity Propagation to the Database The SpatialWS service in OC4J will propagate the user’s identify to the database through one of several options, which are linked to user management in the database, and thus provide administrators with flexibility in controlling user authorization and auditing. The following identity propagation options are available: ■ Proxy authentication: Uses a JDBC connection to the database user through a proxy user. For example, user John in the database and user John in OC4J might be set up independently, perhaps even with different passwords; or user John might be set up as an enterprise user shared by OC4J and the database; or database user John can be set up for use through proxy authentication but not through a direct SQL connection. ■ Application user management: Manages users in a database table as opposed to through database users, providing more flexibility for administrators. With this approach, when using a virtual private database (see Section 17.2.1), you cannot determine the user’s identity by entering SELECT USER FROM DUAL, but must instead query the system context, as follows: SELECT SYS_CONTEXT('APP_CTX', 'APP_USER_ID') FROM DUAL; For example, user John in the database and user John in OC4J might be set up independently, perhaps even with different passwords; or OC4J can be configured to share the application users in the database table. ■ Single application user: Uses a single application user for connections to the database. This approach is acceptable if applications do not need to distinguish among specific users, as long as they are authorized to use Spatial Web services. In this case, the specific users use the same credentials of the single application user, and they are not separately audited. To specify the identify propagation option, insert one of the following subelements in the element in the WSConfig.xml file (described in Section 10.3): ■ to specify proxy authentication ■ to specify application user management ■ to use a single application user 17.1.2 Caching and User Administration Any handler in the Spatial Web services framework can choose to use caching in OC4J. For example, WFS caches feature tables. The OC4J cache must comply with any authorization restrictions set up in the database, such as the use of a virtual private database (VPD). It is not feasible to replicate the entire database authorization framework locally; therefore, you must verify the applicable authorization restrictions with the database for each query. For WFS, this means that queries must be by ID values only rather than by actual data values in other columns. For example, a query might specify SELECT id FROM... instead of SELECT col1, col2 FROM... In such cases, the actual data is already Access Control and Versioning Security Considerations for Spatial Web Services 17-3 cached, and the query just verifies row-level authorization. This approach also usually results in a performance benefit, especially for large data records (as is often the case with spatial data). However, this approach will not work for some forms of column-level VPDs. For example, column-level VPDs might be configured so that user John can see only generalized geometries, whereas user Jane can see the original detailed geometries. Both users access the same data records, but for John the geometry column level gets "obfuscated," which in this example might mean a geometry generalization. As another example, obfuscation might make Social Security numbers visible only to authorized users, but showing the obfuscated value ********* to other users. For the Spatial network data model, caching does not verify authorization restrictions (due to performance considerations related to network query patterns). Therefore, the network data model uses the single application user option for identify propagation (see Section 17.1.1), which limits an administrator’s options for controlling the authorization of users. 17.2 Access Control and Versioning Authorization and versioning are primarily performed in the database rather than in OC4J, although the administrator can configure OC4J to perform some authorization restrictions. Oracle Database enables common grants on select, insert, and update operations, as well as a virtual private database (VPD), to be configured. Workspace Manager operations are also supported. As mentioned in Section 17.1.2, any caching in OC4J should be consistent with the database configuration. However, if the caching is not consistent, you should use the single application user approach described in Section 17.1.1, because then it will not be an issue that all human users of the application will be able to see the same data. 17.2.1 Virtual Private Databases An administrator can restrict users’ access by implementing virtual private databases (VPDs). When proxy authentication or application user management is used for identity propagation (see Section 17.1.1), SOAP requests are executed in the context of VPD policies for the current user, as specified in the WSS section of each SOAP request. When a single application user is used for identity propagation, SOAP requests are executed in the context of the generic single user, making all SOAP requests fundamentally anonymous to the database. (OC4J will still recognize the user by the user name in the WSS section of the SOAP message, and thus OC4J could be configured for auditing; however, the database does not share that knowledge of the user name.) 17.2.2 Workspace Manager You can execute any SOAP request in the context of a workspace by specifying the workspace ID in an element, as in the following example: Note: OpenLS mapping and routing services cannot operate with virtual private databases (VPDs) or with other forms of user-specific authorization (such as granting SELECT privilege on a table to a specified user). Deploying and Configuring the .ear File 17-4 Oracle Spatial Developer's Guide See also oracle.spatial.ws.svrproxy.TestYPWithWorkspace.java under src/oracle/spatial/ws/svrproxy/ in the wsclient.jar demo file (described in Section 10.4). 17.3 Deploying and Configuring the .ear File After you deploy the .ear file, you must configure it. The general configuration includes the following files, but excludes any service-specific setup, such as the WFS-specific portions of the WSConfig.xml file: ■ data-sources.xml contains the database connection for each service (Catalog, OpenLS, WFS, and so on). For example: . . . . . . ■ WSConfig.xml contains, beside WFS-specific parameters, the definition of handlers: name, implementation, and user management. For example: oracle.spatial.ws.openls.OpenLsHandler SpatialWsXmlUser . . . oracle.spatial.network.xml.NetworkWSHandler . . . The data-sources.xml file contains a database connection for each services handler, such as WFS. There are three scenarios, based on the method of user identity propagation (described in Section 17.1.1): Deploying and Configuring the .ear File Security Considerations for Spatial Web Services 17-5 ■ Proxy authentication: The connection specified refers to the proxy user, which is different from the actual SOAP user. ■ Application user management: The connection specified refers to the proxy user, connected as the user to which the system context is set. ■ Single application user: The connection specified refers to the final user (APP_ USER). There is no proxying, no changing of the system context, and no reconnecting as a different user. The WSConfig.xml file includes a part that declares handlers: ■ , the first parameter, specifies the implementation of the service handler. This Java class implements the interface oracle.spatial.ws.SpatialWSHandler. This implementing class can be made available to OC4J in a shared library, specified in the server.xml file. For example: . . . The administrator must give the SpatialWS .ear file access to that shared library. This can be done globally in application.xml, as in the following example: . . . , the second parameter, specifies the database identity of users connecting through the simple non-SOAP XML interface as opposed to the SOAP interface. (For more information, see Section 17.4.2.) ■ , the third parameter, specifies method of propagating the user’s identity to the database. Possible values are , , and . The most typical selection will probably be . In addition, when deploying and configuring the .ear file, be sure to check for any security-related information in the material about deploying a J2EE application (EAR) in Oracle Containers for J2EE Configuration and Administration Guide, as well as the information about configuring a secure Web site in OC4J. 17.3.1 Adding Spatial Service Handlers By default, Spatial Web services include support for CSW, OpenLS, and WFS. However, you can add support for additional service handlers by implementing and deploying an interface for each desired handler. To include support for a service handler, implement the interface oracle.spatial.ws.SpatialWSHandler and deploy it into a .jar file. The implementation contains the following function that determines whether the current request is meant for this service: public boolean canHandle(Element request) Interfaces for Spatial Web Services 17-6 Oracle Spatial Developer's Guide To deploy the interface, perform the following actions. (You can perform the steps in any order.) 1. Make the .jar file accessible to OC4J. The administrator might do so by creating a new shared library (see the information in Section 17.3 about updating server.xml and application.xml), or by adding the .jar file to the existing shared sdows library (a quick approach). 2. Declare the service in a element in the WSConfig.xml file, which includes specifying the implementation class name. (See the example for the OpenLS and Network handlers in Section 17.3.) 3. Declare the data source in a element in the data-sources.xml file, which includes specifying the connection JNDI name. (See the example for jdbc/NdmProxyConnectionCoreDS in Section 17.3.) The implementation contains the following function that determines the connection JNDI name: public String getConnectionJndiName() This name must match the JNDI name specified in the data-sources.xml file. 17.4 Interfaces for Spatial Web Services Spatial Web services can be accessed through different interfaces, each having implications for security. For all services, a SOAP/WSS interface is available, as well as a simple XML (non-SOAP) interface. For OpenLS, there also is a PL/SQL interface, because the OpenLS implementation itself is in PL/SQL. 17.4.1 SOAP/WSS Interface The SOAP/WSS interface is probably the best choice in most cases for accessing Spatial Web services. This interface offers the end-to-end security of WSS, and integration with other Web services. However, a simple XML interface is also available as an alternative, as explained in Section 17.4.2. The default URL for the SOAP/WSS interface has the following form: http://hostname:port/SpatialWS-SpatialWS-context-root/SpatialWSS oapHttpPort 17.4.2 XML (Non-SOAP) Interface Sometimes you might prefer the simple non-SOAP XML interface to Spatial Web services. Specifically, this XML interface: ■ Integrates easily with existing software. For example, it is easier to make JMeter connect to an XML servlet than to SOAP, particularly when WSS is used. ■ Provides better performance through lower overhead. SOAP adds overhead for parsing and for encryption/signing, due to WSS. (However, the overhead is reduced if the XML service is accessed through SSL.) The default URL for the non-SOAP XML interface has the following form: http://hostname:port/SpatialWS-SpatialWS-context-root/SpatialWSX mlServlet This XML interface is set up to not expect a user identity or authentication. Consequently, for XML requests, the SpatialWS service will connect to the database Interfaces for Spatial Web Services Security Considerations for Spatial Web Services 17-7 under a generic identity, common to all XML users. This identity is defined in the WSConfig.xml file as . This approach is similar to using the option in the WSConfig.xml file, which causes OC4J to keep the user anonymous as far as the database is concerned. That is, OC4J could still perform auditing or JAAS-based authorization restrictions, but database-side user authorization and auditing are limited. However, for the non-SOAP XML interface, the user is anonymous even to OC4J. 17.4.3 PL/SQL Interface (OpenLS Only) OpenLS has a PL/SQL interface, in addition to SOAP and non-SOAP XML interfaces. If you connect through SQL and use the PL/SQL API directly, the following security considerations are different than for the apply differently than for the SOAP and non-SOAP XML APIs: ■ Proxy authentication and application user management are not required, because the connection is directly between the user and the database. ■ OC4Jauthentication, authorization, and caching are not required, because OC4J is not involved. 17.4.4 Level of Security, by Interface The PL/SQL interface provides the same level of security as the SOAP interface, but in different environments. However, the non-SOAP XML provides a lower security (less secure) level, mainly because users remain anonymous to the database (except as the generic APP_USER). The non-SOAP XML interface could be used with SSL and user authentication and authorization, thus enabling identity propagation to the database; however, this would probably outweigh any perceived advantages to choosing the simple XML interface option. If you do not need the non-SOAP XML interface and want to make it unavailable for use, you can deactivate the servlet at a URL in the following form: http://hostname:port/SpatialWS-SpatialWS-context-root/SpatialWSX mlServlet Interfaces for Spatial Web Services 17-8 Oracle Spatial Developer's Guide Part III Part III Reference Information This document has the following parts: ■ Part I provides conceptual and usage information about Oracle Spatial. ■ Part II provides conceptual and usage information about Oracle Spatial Web services. ■ Part III provides reference information about Oracle Spatial operators, functions, and procedures. ■ Part IV provides supplementary information (appendixes and a glossary). Part III contains the following chapters with reference information: ■ Chapter 18, "SQL Statements for Indexing Spatial Data" ■ Chapter 19, "Spatial Operators" ■ Chapter 20, "Spatial Aggregate Functions" ■ Chapter 21, "SDO_CS Package (Coordinate System Transformation)" ■ Chapter 22, "SDO_CSW_PROCESS Package (CSW Processing)" ■ Chapter 23, "SDO_GCDR Package (Geocoding)" ■ Chapter 24, "SDO_GEOM Package (Geometry)" ■ Chapter 25, "SDO_LRS Package (Linear Referencing System)" ■ Chapter 26, "SDO_MIGRATE Package (Upgrading)" ■ Chapter 27, "SDO_OLS Package (OpenLS)" ■ Chapter 28, "SDO_PC_PKG Package (Point Clouds)" ■ Chapter 29, "SDO_SAM Package (Spatial Analysis and Mining)" ■ Chapter 30, "SDO_TIN_PKG Package (TINs)" ■ Chapter 31, "SDO_TUNE Package (Tuning)" ■ Chapter 32, "SDO_UTIL Package (Utility)" ■ Chapter 33, "SDO_WFS_LOCK Package (WFS)" ■ Chapter 34, "SDO_WFS_PROCESS Package (WFS Processing)" To understand the examples in the reference chapters, you must understand the conceptual and data type information in Chapter 2, "Spatial Data Types and Metadata", especially Section 2.2, "SDO_GEOMETRY Object Type". 18 SQL Statements for Indexing Spatial Data 18-1 18 SQL Statements for Indexing Spatial Data This chapter describes the SQL statements used when working with the spatial object data type. The statements are listed in Table 18–1. This chapter focuses on using these SQL statements with spatial indexes. For complete reference information about any statement, see Oracle Database SQL Language Reference. Bold italic text is often used in the Keywords and Parameters sections in this chapter to identify a grouping of keywords, followed by specific keywords in the group. For example, INDEX_PARAMS identifies the start of a group of index-related keywords. Table 18–1 Spatial Index Creation and Usage Statements Statement Description ALTER INDEX Alters specific parameters for a spatial index. ALTER INDEX REBUILD Rebuilds a spatial index or a specified partition of a partitioned index. ALTER INDEX RENAME TO Changes the name of a spatial index or a partition of a spatial index. CREATE INDEX Creates a spatial index on a column of type SDO_GEOMETRY. DROP INDEX Deletes a spatial index. ALTER INDEX 18-2 Oracle Spatial Developer's Guide ALTER INDEX Purpose Alters specific parameters for a spatial index. Syntax ALTER INDEX [schema.]index PARAMETERS ('index_params [physical_storage_params]' ) [{ NOPARALLEL | PARALLEL [ integer ] }] ; Keywords and Parameters Value Description INDEX_PARAMS Changes the characteristics of the spatial index. sdo_indx_dims Specifies the number of dimensions to be indexed. For example, a value of 2 causes only the first two dimensions to be indexed. Must be less than or equal to the number of actual dimensions. For usage information related to three-dimensional geometries, see Section 1.11. Data type is NUMBER. Default = 2. sdo_rtr_pctfree Specifies the minimum percentage of slots in each index tree node to be left empty when the index is created. Slots that are left empty can be filled later when new data is inserted into the table. The value can range from 0 to 50. The default value is best for most applications; however, a value of 0 is recommended if no updates will be performed to the geometry column. Data type is NUMBER. Default = 10. PHYSICAL_STORAGE_ PARAMS Determines the storage parameters used for altering the spatial index data table. A spatial index data table is a standard Oracle table with a prescribed format. Not all physical storage parameters that are allowed in the STORAGE clause of a CREATE TABLE statement are supported. The following is a list of the supported subset. tablespace Specifies the tablespace in which the index data table is created. This parameter is the same as TABLESPACE in the STORAGE clause of a CREATE TABLE statement. initial Is the same as INITIAL in the STORAGE clause of a CREATE TABLE statement. next Is the same as NEXT in the STORAGE clause of a CREATE TABLE statement. minextents Is the same as MINEXTENTS in the STORAGE clause of a CREATE TABLE statement. maxextents Is the same as MAXEXTENTS in the STORAGE clause of a CREATE TABLE statement. pctincrease Is the same as PCTINCREASE in the STORAGE clause of a CREATE TABLE statement. ALTER INDEX SQL Statements for Indexing Spatial Data 18-3 Prerequisites ■ You must have EXECUTE privileges on the index type and its implementation type. ■ The spatial index to be altered is not marked in-progress. Usage Notes Use this statement to change the parameters of an existing index. See the Usage Notes for the CREATE INDEX statement for usage information about many of the other available parameters. Examples The following example modifies the tablespace for partition IP2 of the spatial index named BGI. ALTER INDEX bgi MODIFY PARTITION ip2 PARAMETERS ('tablespace=TBS_3'); Related Topics ■ ALTER INDEX REBUILD ■ ALTER INDEX RENAME TO ■ CREATE INDEX ■ ALTER TABLE (clauses for partition maintenance) in Oracle Database SQL Language Reference { NOPARALLEL | PARALLEL [ integer ] } Controls whether serial (NOPARALLEL) execution or parallel (PARALLEL) execution is used for subsequent queries and DML operations that use the index. For parallel execution you can specify an integer value of degree of parallelism. See the Usage Notes for the CREATE INDEX statement for guidelines and restrictions that apply to the use of the PARALLEL keyword. Default = NOPARALLEL. (If PARALLEL is specified without an integer value, the Oracle database calculates the optimum degree of parallelism.) Value Description ALTER INDEX REBUILD 18-4 Oracle Spatial Developer's Guide ALTER INDEX REBUILD Syntax ALTER INDEX [schema.]index REBUILD [PARAMETERS ('rebuild_params [physical_storage_params]' ) ] [{ NOPARALLEL | PARALLEL [ integer ] }] ; or ALTER INDEX [schema.]index REBUILD ONLINE [PARAMETERS ('rebuild_params [physical_storage_params]' ) ] [{ NOPARALLEL | PARALLEL [ integer ] }] ; or ALTER INDEX [schema.]index REBUILD PARTITION partition [PARAMETERS ('rebuild_params [physical_storage_params]' ) ]; Purpose Rebuilds a spatial index or a specified partition of a partitioned index. Keywords and Parameters Value Description REBUILD_PARAMS Specifies in a command string the index parameters to use in rebuilding the spatial index. index_status=cleanup For an online rebuild operation (ALTER INDEX REBUILD ONLINE), performs cleanup operations on tables associated with the older version of the index. layer_gtype Checks to ensure that all geometries are of a specified geometry type. The value must be from the Geometry Type column of Table 2–1 in Section 2.2.1 (except that UNKNOWN_GEOMETRY is not allowed). In addition, specifying POINT allows for optimized processing of point data. Data type is VARCHAR2. sdo_dml_batch_size Specifies the number of index updates to be processed in each batch of updates after a commit operation. The default value is 1000. For example, if you insert 3500 rows into the spatial table and then perform a commit operation, the updates to the spatial index table are performed in four batches of insert operations (1000, 1000, 1000, and 500). See the Usage Notes for the CREATE INDEX statement for more information. Data type is NUMBER. Default = 1000. sdo_indx_dims Specifies the number of dimensions to be indexed. For example, a value of 2 causes only the first two dimensions to be indexed. Must be less than or equal to the number of actual dimensions. For usage information related to three-dimensional geometries, see Section 1.11. Data type is NUMBER. Default = 2. ALTER INDEX REBUILD SQL Statements for Indexing Spatial Data 18-5 Prerequisites ■ You must have EXECUTE privileges on the index type and its implementation type. ■ The spatial index to be altered is not marked in-progress. Usage Notes An ALTER INDEX REBUILD 'rebuild_params' statement rebuilds the index using supplied parameters. Spatial index creation involves creating and inserting index data, for each row in the underlying table column being spatially indexed, into a table with a prescribed format. All rows in the underlying table are processed before the insertion of index data is committed, and this requires adequate rollback segment space. The ONLINE keyword rebuilds the index without blocking the index; that is, queries can use the spatial index while it is being rebuilt. However, after all queries issued during the rebuild operation have completed, you must clean up the old index information (in the MDRT tables) by entering a SQL statement in the following form: sdo_rtr_pctfree Specifies the minimum percentage of slots in each index tree node to be left empty when the index is created. Slots that are left empty can be filled later when new data is inserted into the table. The value can range from 0 to 50. Data type is NUMBER. Default = 10. PHYSICAL_STORAGE_ PARAMS Determines the storage parameters used for rebuilding the spatial index data table. A spatial index data table is a regular Oracle table with a prescribed format. Not all physical storage parameters that are allowed in the STORAGE clause of a CREATE TABLE statement are supported. The following is a list of the supported subset. tablespace Specifies the tablespace in which the index data table is created. Same as TABLESPACE in the STORAGE clause of a CREATE TABLE statement. initial Is the same as INITIAL in the STORAGE clause of a CREATE TABLE statement. next Is the same as NEXT in the STORAGE clause of a CREATE TABLE statement. minextents Is the same as MINEXTENTS in the STORAGE clause of a CREATE TABLE statement. maxextents Is the same as MAXEXTENTS in the STORAGE clause of a CREATE TABLE statement. pctincrease Is the same as PCTINCREASE in the STORAGE clause of a CREATE TABLE statement. { NOPARALLEL | PARALLEL [ integer ] } Controls whether serial (NOPARALLEL) execution or parallel (PARALLEL) execution is used for the rebuilding of the index and for subsequent queries and DML operations that use the index. For parallel execution you can specify an integer value of degree of parallelism. See the Usage Notes for the CREATE INDEX statement for guidelines and restrictions that apply to the use of the PARALLEL keyword. Default = NOPARALLEL. (If PARALLEL is specified without an integer value, the Oracle database calculates the optimum degree of parallelism.) Value Description ALTER INDEX REBUILD 18-6 Oracle Spatial Developer's Guide ALTER INDEX [schema.]index REBUILD ONLINE PARAMETERS (’index_status=cleanup’); The following limitations apply to the use of the ONLINE keyword: ■ Only query operations are permitted while the index is being rebuilt. Insert, update, and delete operations that would affect the index are blocked while the index is being rebuilt; and an online rebuild is blocked while any insert, update, or delete operations that would affect the index are being performed. ■ You cannot use the ONLINE keyword for a rebuild operation if the index was created using the ’sdo_non_leaf_tbl=TRUE’ parameter. ■ You cannot use the ONLINE keyword for a partitioned spatial index. The ALTER INDEX REBUILD statement does not use any previous parameters from the index creation. All parameters should be specified for the index you want to rebuild. For more information about using the layer_gtype keyword to constrain data in a layer to a geometry type, see Section 5.1.1. With a partitioned spatial index, you must use a separate ALTER INDEX REBUILD statement for each partition to be rebuilt. If you want to use a local partitioned spatial index, follow the procedure in Section 5.1.3.1. See also the Usage Notes for the CREATE INDEX statement for usage information about many of the available parameters and about the use of the PARALLEL keyword. Examples The following example rebuilds OLDINDEX and specifies the tablespace in which to create the index data table. ALTER INDEX oldindex REBUILD PARAMETERS('tablespace=TBS_3'); Related Topics ■ CREATE INDEX ■ DROP INDEX ■ ALTER TABLE and ALTER INDEX (clauses for partition maintenance) in Oracle Database SQL Language Reference ALTER INDEX RENAME TO SQL Statements for Indexing Spatial Data 18-7 ALTER INDEX RENAME TO Syntax ALTER INDEX [schema.]index RENAME TO ; ALTER INDEX [schema.]index PARTITION partition RENAME TO ; Purpose Changes the name of a spatial index or a partition of a spatial index. Keywords and Parameters Prerequisites ■ You must have EXECUTE privileges on the index type and its implementation type. ■ The spatial index to be altered is not marked in-progress. Usage Notes None. Examples The following example renames OLDINDEX to NEWINDEX. ALTER INDEX oldindex RENAME TO newindex; Related Topics ■ CREATE INDEX ■ DROP INDEX Value Description new_index_name Specifies the new name of the index. new_partition_name Specifies the new name of the partition. CREATE INDEX 18-8 Oracle Spatial Developer's Guide CREATE INDEX Syntax CREATE INDEX [schema.]index ON [schema.]table (column) INDEXTYPE IS MDSYS.SPATIAL_INDEX [PARAMETERS ('index_params [physical_storage_params]' )] [{ NOPARALLEL | PARALLEL [ integer ] }]; Purpose Creates a spatial index on a column of type SDO_GEOMETRY. Keywords and Parameters Value Description INDEX_PARAMS Determines the characteristics of the spatial index. layer_gtype Checks to ensure that all geometries are of a specified geometry type. The value must be from the Geometry Type column of Table 2–1 in Section 2.2.1 (except that UNKNOWN_GEOMETRY is not allowed). In addition, specifying POINT allows for optimized processing of point data. Data type is VARCHAR2. sdo_dml_batch_size Specifies the number of index updates to be processed in each batch of updates after a commit operation. The default value is 1000. For example, if you insert 3500 rows into the spatial table and then perform a commit operation, the updates to the spatial index table are performed in four batches of insert operations (1000, 1000, 1000, and 500). See the Usage Notes for more information. Data type is NUMBER. Default = 1000. sdo_indx_dims Specifies the number of dimensions to be indexed. For example, a value of 2 causes only the first two dimensions to be indexed. Must be less than or equal to the number of actual dimensions. For usage information related to three-dimensional geometries, see Section 1.11. Data type is NUMBER. Default = 2. sdo_non_leaf_tbl 'sdo_non_leaf_tbl=TRUE' creates a separate index table (with a name in the form MDNT_...$) for nonleaf nodes of the index, in addition to creating an index table (with a name in the form MDRT_...$) for leaf nodes. 'sdo_non_leaf_tbl=FALSE' creates a single table (with a name in the form MDRT_...$) for both leaf nodes and nonleaf nodes of the index. See the Usage Notes for more information. Data type is VARCHAR2. Default = FALSE sdo_rtr_pctfree Specifies the minimum percentage of slots in each index tree node to be left empty when the index is created. Slots that are left empty can be filled later when new data is inserted into the table. The value can range from 0 to 50. Data type is NUMBER. Default = 10. CREATE INDEX SQL Statements for Indexing Spatial Data 18-9 Prerequisites ■ All current SQL CREATE INDEX prerequisites apply. ■ You must have EXECUTE privilege on the index type and its implementation type. ■ The USER_SDO_GEOM_METADATA view must contain an entry with the dimensions and coordinate boundary information for the table column to be spatially indexed. Usage Notes For information about spatial indexes, see Section 1.7. Before you create a spatial index, be sure that the rollback segment size and the SORT_ AREA_SIZE parameter value are adequate, as described in Section 5.1. If an R-tree index is used on linear referencing system (LRS) data and if the LRS data has four dimensions (three plus the M dimension), the sdo_indx_dims parameter must be used and must specify 3 (the number of dimensions minus one), to avoid the default sdo_indx_dims value of 2, which would index only the X and Y dimensions. For example, if the dimensions are X, Y, Z, and M, specify sdo_indx_dims=3 to PHYSICAL_STORAGE_ PARAMS Determines the storage parameters used for creating the spatial index data table. A spatial index data table is a regular Oracle table with a prescribed format. Not all physical storage parameters that are allowed in the STORAGE clause of a CREATE TABLE statement are supported. The following is a list of the supported subset. tablespace Specifies the tablespace in which the index data table is created. Same as TABLESPACE in the STORAGE clause of a CREATE TABLE statement. initial Is the same as INITIAL in the STORAGE clause of a CREATE TABLE statement. next Is the same as NEXT in the STORAGE clause of a CREATE TABLE statement. minextents Is the same as MINEXTENTS in the STORAGE clause of a CREATE TABLE statement. maxextents Is the same as MAXEXTENTS in the STORAGE clause of a CREATE TABLE statement. pctincrease Is the same as PCTINCREASE in the STORAGE clause of a CREATE TABLE statement. work_tablespace Specifies the tablespace for temporary tables used in creating the index. (Applies only to creating spatial R-tree indexes, and not to other types of indexes.) { NOPARALLEL | PARALLEL [ integer ] } Controls whether serial (NOPARALLEL) execution or parallel (PARALLEL) execution is used for the creation of the index and for subsequent queries and DML operations that use the index. For parallel execution you can specify an integer value of degree of parallelism. See the Usage Notes for more information about parallel index creation. Default = NOPARALLEL. (If PARALLEL is specified without an integer value, the Oracle database calculates the optimum degree of parallelism.) Value Description CREATE INDEX 18-10 Oracle Spatial Developer's Guide index the X, Y, and Z dimensions, but not the measure (M) dimension. (The LRS data model, including the measure dimension, is explained in Section 7.2.) A partitioned spatial index can be created on a partitioned table. See Section 5.1.3 for more information about partitioned spatial indexes, including benefits and restrictions. If you want to use a local partitioned spatial index, follow the procedure in Section 5.1.3.1. A spatial index cannot be created on an index-organized table. You can specify the PARALLEL keyword to cause the index creation to be parallelized. For example: CREATE INDEX cola_spatial_idx ON cola_markets(shape) INDEXTYPE IS MDSYS.SPATIAL_INDEX PARALLEL; For information about using the PARALLEL keyword, see the description of the parallel_clause in the section on the CREATE INDEX statement in Oracle Database SQL Language Reference. In addition, the following notes apply to the use of the PARALLEL keyword for creating or rebuilding (using the ALTER INDEX REBUILD statement) spatial indexes: ■ The performance cost and benefits from parallel execution for creating or rebuilding an index depend on system resources and load. If the CPUs or disk controllers are already heavily loaded, you should not specify the PARALLEL keyword. ■ Specifying PARALLEL for creating or rebuilding an index on tables with simple geometries, such as point data, usually results in less performance improvement than on tables with complex geometries. Other options available for regular indexes (such as ASC and DESC) are not applicable for spatial indexes. Spatial index creation involves creating and inserting index data, for each row in the underlying table column being spatially indexed, into a table with a prescribed format. All rows in the underlying table are processed before the insertion of index data is committed, and this requires adequate rollback segment space. If a tablespace name is provided in the parameters clause, the user (underlying table owner) must have appropriate privileges for that tablespace. For more information about using the layer_gtype keyword to constrain data in a layer to a geometry type, see Section 5.1.1. The sdo_dml_batch_size parameter can improve application performance, because Spatial can preallocate system resources to perform multiple index updates more efficiently than successive single index updates; however, to gain the performance benefit, you must not perform commit operations after each insert operation or at intervals less than or equal to the sdo_dml_batch_size value. You should not specify a value greater than 10000 (ten thousand), because the cost of the additional memory and other resources required will probably outweigh any marginal performance increase resulting from such a value. Specifying 'sdo_non_leaf_tbl=TRUE' can help query performance with large data sets if the entire R-tree table may not fit in the KEEP buffer pool. In this case, you must also cause Oracle to buffer the MDNT_...$ table in the KEEP buffer pool, for example, by using ALTER TABLE and specifying STORAGE (BUFFER_POOL KEEP). For partitioned indexes, the same sdo_non_leaf_tbl value must be used for all partitions. Any physical storage parameters, except for tablespace, are applied only CREATE INDEX SQL Statements for Indexing Spatial Data 18-11 to the MDRT_...$ table. The MDNT_...$ table uses only the tablespace parameter, if specified, and default values for all other physical storage parameters. If you are creating a function-based spatial index, the number of parameters must not exceed 32. For information about using function-based spatial indexes, see Section 9.2. To determine if a CREATE INDEX statement for a spatial index has failed, check to see if the DOMIDX_OPSTATUS column in the USER_INDEXES view is set to FAILED. This is different from the case of regular indexes, where you check to see if the STATUS column in the USER_INDEXES view is set to FAILED. If the CREATE INDEX statement fails because of an invalid geometry, the ROWID of the failed geometry is returned in an error message along with the reason for the failure. If the CREATE INDEX statement fails for any reason, then the DROP INDEX statement must be used to clean up the partially built index and associated metadata. If DROP INDEX does not work, add the FORCE parameter and try again. Examples The following example creates a spatial R-tree index named COLA_SPATIAL_IDX. CREATE INDEX cola_spatial_idx ON cola_markets(shape) INDEXTYPE IS MDSYS.SPATIAL_INDEX; Related Topics ■ ALTER INDEX ■ DROP INDEX DROP INDEX 18-12 Oracle Spatial Developer's Guide DROP INDEX Syntax DROP INDEX [schema.]index [FORCE]; Purpose Deletes a spatial index. Keywords and Parameters Prerequisites You must have EXECUTE privileges on the index type and its implementation type. Usage Notes Use DROP INDEX indexname FORCE to clean up after a failure in the CREATE INDEX statement. Examples The following example deletes a spatial index named OLDINDEX and forces the deletion to be performed even if the index is marked in-process or an error occurs. DROP INDEX oldindex FORCE; Related Topics ■ CREATE INDEX Value Description FORCE Causes the spatial index to be deleted from the system tables even if the index is marked in-progress or some other error condition occurs. 19 Spatial Operators 19-1 19 Spatial Operators This chapter describes the operators that you can use when working with the spatial object data type. For an overview of spatial operators, including how they differ from spatial procedures and functions, see Section 1.9. Table 19–1 lists the main operators. Table 19–2 lists operators, provided for convenience, that perform an SDO_RELATE operation of a specific mask type. Table 19–1 Main Spatial Operators Operator Description SDO_FILTER Specifies which geometries may interact with a given geometry. SDO_JOIN Performs a spatial join based on one or more topological relationships. SDO_NN Determines the nearest neighbor geometries to a geometry. SDO_NN_DISTANCE Returns the distance of an object returned by the SDO_NN operator. SDO_RELATE Determines whether or not two geometries interact in a specified way. (See also Table 19–2 for convenient alternative operators for performing specific mask value operations.) SDO_WITHIN_DISTANCE Determines if two geometries are within a specified distance from one another. Table 19–2 Convenience Operators for SDO_RELATE Operations Operator Description SDO_ANYINTERACT Checks if any geometries in a table have the ANYINTERACT topological relationship with a specified geometry. SDO_CONTAINS Checks if any geometries in a table have the CONTAINS topological relationship with a specified geometry. SDO_COVEREDBY Checks if any geometries in a table have the COVEREDBY topological relationship with a specified geometry. SDO_COVERS Checks if any geometries in a table have the COVERS topological relationship with a specified geometry. SDO_EQUAL Checks if any geometries in a table have the EQUAL topological relationship with a specified geometry. SDO_INSIDE Checks if any geometries in a table have the INSIDE topological relationship with a specified geometry. 19-2 Oracle Spatial Developer's Guide The rest of this chapter provides reference information on the operators, listed in alphabetical order. For information about using operators with topologies, see Oracle Spatial Topology and Network Data Models Developer's Guide. SDO_ON Checks if any geometries in a table have the ON topological relationship with a specified geometry. SDO_ OVERLAPBDYDISJOINT Checks if any geometries in a table have the OVERLAPBDYDISJOINT topological relationship with a specified geometry. SDO_ OVERLAPBDYINTERSECT Checks if any geometries in a table have the OVERLAPBDYINTERSECT topological relationship with a specified geometry. SDO_OVERLAPS Checks if any geometries in a table overlap (that is, have the OVERLAPBDYDISJOINT or OVERLAPBDYINTERSECT topological relationship with) a specified geometry. SDO_TOUCH Checks if any geometries in a table have the TOUCH topological relationship with a specified geometry. Table 19–2 (Cont.) Convenience Operators for SDO_RELATE Operations Operator Description SDO_ANYINTERACT Spatial Operators 19-3 SDO_ANYINTERACT Format SDO_ANYINTERACT(geometry1, geometry2); Description Checks if any geometries in a table have the ANYINTERACT topological relationship with a specified geometry. Equivalent to specifying the SDO_RELATE operator with 'mask=ANYINTERACT'. See the section on the SDO_RELATE operator in this chapter for information about the operations performed by this operator and for usage requirements. Keywords and Parameters Returns The expression SDO_ANYINTERACT(geometry1,geometry2) = 'TRUE' evaluates to TRUE for object pairs that have the ANYINTERACT topological relationship, and FALSE otherwise. Usage Notes See the Usage Notes for the SDO_RELATE operator in this chapter. For an explanation of the topological relationships and the nine-intersection model used by Spatial, see Section 1.8. For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Examples The following example finds geometries that have the ANYINTERACT relationship with a query window (here, a rectangle with lower-left, upper-right coordinates 4,6, 8,8). (The example uses the definitions and data described in Section 2.1 and illustrated in Figure 2–1.) SELECT c.mkt_id, c.name FROM cola_markets c WHERE SDO_ANYINTERACT(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(4,6, 8,8)) ) = 'TRUE'; Value Description geometry1 Specifies a geometry column in a table. The column must be spatially indexed. Data type is SDO_GEOMETRY. geometry2 Specifies either a geometry from a table or a transient instance of a geometry. (Specified using a bind variable or SDO_GEOMETRY constructor.) Data type is SDO_GEOMETRY. SDO_ANYINTERACT 19-4 Oracle Spatial Developer's Guide MKT_ID NAME ---------- -------------------------------- 2 cola_b 1 cola_a 4 cola_d SDO_CONTAINS Spatial Operators 19-5 SDO_CONTAINS Format SDO_CONTAINS(geometry1, geometry2); Description Checks if any geometries in a table have the CONTAINS topological relationship with a specified geometry. Equivalent to specifying the SDO_RELATE operator with 'mask=CONTAINS'. See the section on the SDO_RELATE operator in this chapter for information about the operations performed by this operator and for usage requirements. Keywords and Parameters Returns The expression SDO_CONTAINS(geometry1,geometry2) = 'TRUE' evaluates to TRUE for object pairs that have the CONTAINS topological relationship, and FALSE otherwise. Usage Notes See the Usage Notes for the SDO_RELATE operator in this chapter. For an explanation of the topological relationships and the nine-intersection model used by Spatial, see Section 1.8. For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Examples The following example finds geometries that have the CONTAINS relationship with a query window (here, a rectangle with lower-left, upper-right coordinates 2,2, 4,6). (The example uses the definitions and data described in Section 2.1 and illustrated in Figure 2–1.) In this example, only cola_a contains the query window geometry. SELECT c.mkt_id, c.name FROM cola_markets c WHERE SDO_CONTAINS(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(2,2, 4,6)) ) = 'TRUE'; Value Description geometry1 Specifies a geometry column in a table. The column must be spatially indexed. Data type is SDO_GEOMETRY. geometry2 Specifies either a geometry from a table or a transient instance of a geometry. (Specified using a bind variable or SDO_GEOMETRY constructor.) Data type is SDO_GEOMETRY. SDO_CONTAINS 19-6 Oracle Spatial Developer's Guide MKT_ID NAME ---------- -------------------------------- 1 cola_a SDO_COVEREDBY Spatial Operators 19-7 SDO_COVEREDBY Format SDO_COVEREDBY(geometry1, geometry2); Description Checks if any geometries in a table have the COVEREDBY topological relationship with a specified geometry. Equivalent to specifying the SDO_RELATE operator with 'mask=COVEREDBY'. See the section on the SDO_RELATE operator in this chapter for information about the operations performed by this operator and for usage requirements. Keywords and Parameters Returns The expression SDO_COVEREDBY(geometry1,geometry2) = 'TRUE' evaluates to TRUE for object pairs that have the COVEREDBY topological relationship, and FALSE otherwise. Usage Notes See the Usage Notes for the SDO_RELATE operator in this chapter. For an explanation of the topological relationships and the nine-intersection model used by Spatial, see Section 1.8. For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Examples The following example finds geometries that have the COVEREDBY relationship with a query window (here, a rectangle with lower-left, upper-right coordinates 1,1, 5,8). (The example uses the definitions and data described in Section 2.1 and illustrated in Figure 2–1.) In this example, only cola_a is covered by the query window geometry. SELECT c.mkt_id, c.name FROM cola_markets c WHERE SDO_COVEREDBY(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(1,1, 5,8)) ) = 'TRUE'; Value Description geometry1 Specifies a geometry column in a table. The column must be spatially indexed. Data type is SDO_GEOMETRY. geometry2 Specifies either a geometry from a table or a transient instance of a geometry. (Specified using a bind variable or SDO_GEOMETRY constructor.) Data type is SDO_GEOMETRY. SDO_COVEREDBY 19-8 Oracle Spatial Developer's Guide MKT_ID NAME ---------- -------------------------------- 1 cola_a SDO_COVERS Spatial Operators 19-9 SDO_COVERS Format SDO_COVERS(geometry1, geometry2); Description Checks if any geometries in a table have the COVERS topological relationship with a specified geometry. Equivalent to specifying the SDO_RELATE operator with 'mask=COVERS'. See the section on the SDO_RELATE operator in this chapter for information about the operations performed by this operator and for usage requirements. Keywords and Parameters Returns The expression SDO_COVERS(geometry1,geometry2) = 'TRUE' evaluates to TRUE for object pairs that have the COVERS topological relationship, and FALSE otherwise. Usage Notes See the Usage Notes for the SDO_RELATE operator in this chapter. For an explanation of the topological relationships and the nine-intersection model used by Spatial, see Section 1.8. For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Examples The following example finds geometries that have the COVERS relationship with a query window (here, a rectangle with lower-left, upper-right coordinates 1,1, 4,6). (The example uses the definitions and data described in Section 2.1 and illustrated in Figure 2–1.) In this example, only cola_a covers the query window geometry. SELECT c.mkt_id, c.name FROM cola_markets c WHERE SDO_COVERS(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(1,1, 4,6)) ) = 'TRUE'; MKT_ID NAME ---------- -------------------------------- Value Description geometry1 Specifies a geometry column in a table. The column must be spatially indexed. Data type is SDO_GEOMETRY. geometry2 Specifies either a geometry from a table or a transient instance of a geometry. (Specified using a bind variable or SDO_GEOMETRY constructor.) Data type is SDO_GEOMETRY. SDO_COVERS 19-10 Oracle Spatial Developer's Guide 1 cola_a SDO_EQUAL Spatial Operators 19-11 SDO_EQUAL Format SDO_EQUAL(geometry1, geometry2); Description Checks if any geometries in a table have the EQUAL topological relationship with a specified geometry. Equivalent to specifying the SDO_RELATE operator with 'mask=EQUAL'. See the section on the SDO_RELATE operator in this chapter for information about the operations performed by this operator and for usage requirements. Keywords and Parameters Returns The expression SDO_EQUAL(geometry1,geometry2) = 'TRUE' evaluates to TRUE for object pairs that have the EQUAL topological relationship, and FALSE otherwise. Usage Notes See the Usage Notes for the SDO_RELATE operator in this chapter. For an explanation of the topological relationships and the nine-intersection model used by Spatial, see Section 1.8. For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Examples The following example finds geometries that have the EQUAL relationship with a query window (here, a rectangle with lower-left, upper-right coordinates 1,1, 5,7). (The example uses the definitions and data described in Section 2.1 and illustrated in Figure 2–1.) In this example, cola_a (and only cola_a) has the same boundary and interior as the query window geometry. SELECT c.mkt_id, c.name FROM cola_markets c WHERE SDO_EQUAL(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(1,1, 5,7)) ) = 'TRUE'; Value Description geometry1 Specifies a geometry column in a table. The column must be spatially indexed. Data type is SDO_GEOMETRY. geometry2 Specifies either a geometry from a table or a transient instance of a geometry. (Specified using a bind variable or SDO_GEOMETRY constructor.) Data type is SDO_GEOMETRY. SDO_EQUAL 19-12 Oracle Spatial Developer's Guide MKT_ID NAME ---------- -------------------------------- 1 cola_a SDO_FILTER Spatial Operators 19-13 SDO_FILTER Format SDO_FILTER(geometry1, geometry2, param); Description Uses the spatial index to identify either the set of spatial objects that are likely to interact spatially with a given object (such as an area of interest), or pairs of spatial objects that are likely to interact spatially. Objects interact spatially if they are not disjoint. This operator performs only a primary filter operation. The secondary filtering operation, performed by the SDO_RELATE operator, can be used to determine with certainty if objects interact spatially. Keywords and Parameters Returns The expression SDO_FILTER(geometry1,geometry2) = 'TRUE' evaluates to TRUE for object pairs that are non-disjoint, and FALSE otherwise. Usage Notes The SDO_FILTER operator must always be used in a WHERE clause and the condition that includes the operator should be an expression of the form SDO_FILTER(arg1, arg2) = 'TRUE'. geometry2 can come from a table or be a transient SDO_GEOMETRY object, such as a bind variable or SDO_GEOMETRY constructor. Value Description geometry1 Specifies a geometry column in a table. The column must be spatially indexed. Data type is SDO_GEOMETRY. geometry2 Specifies either a geometry from a table or a transient instance of a geometry. (Specified using a bind variable or SDO_GEOMETRY constructor.) Data type is SDO_GEOMETRY. param Optionally specifies either or both of the min_resolution and max_ resolution keywords. Data type is VARCHAR2. The min_resolution keyword includes only geometries for which at least one side of the geometry's MBR is equal to or greater than the specified value. For example, min_resolution=10 includes only geometries for which the width or the height (or both) of the geometry's MBR is at least 10. (This keyword can be used to exclude geometries that are too small to be of interest.) The max_resolution keyword includes only geometries for which at least one side of the geometry's MBR is less than or equal to the specified value. For example, max_resolution=10 includes only geometries for which the width or the height (or both) of the geometry's MBR is less than or equal to 10. (This keyword can be used to exclude geometries that are too large to be of interest.) SDO_FILTER 19-14 Oracle Spatial Developer's Guide ■ If the geometry2 column is not spatially indexed, the operator indexes the query window in memory and performance is very good. ■ If two or more geometries from geometry2 are passed to the operator, the ORDERED optimizer hint must be specified, and the table in geometry2 must be specified first in the FROM clause. If geometry1 and geometry2 are based on different coordinate systems, geometry2 is temporarily transformed to the coordinate system of geometry1 for the operation to be performed, as described in Section 6.10.1. For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Examples The following example selects the geometries that are likely to interact with a query window (here, a rectangle with lower-left, upper-right coordinates 4,6, 8,8). (The example uses the definitions and data described in Section 2.1 and illustrated in Figure 2–1.) SELECT c.mkt_id, c.name FROM cola_markets c WHERE SDO_FILTER(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(4,6, 8,8)) ) = 'TRUE'; MKT_ID NAME ---------- -------------------------------- 2 cola_b 1 cola_a 4 cola_d The following example is the same as the preceding example, except that it includes only geometries where at least one side of the geometry's MBR is equal to or greater than 4.1. In this case, only cola_a and cola_b are returned, because their MBRs have at least one side with a length greater than or equal to 4.1. The circle cola_d is excluded, because its MBR is a square whose sides have a length of 4. SELECT c.mkt_id, c.name FROM cola_markets c WHERE SDO_FILTER(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(4,6, 8,8)), 'min_resolution=4.1' ) = 'TRUE'; MKT_ID NAME ---------- -------------------------------- 2 cola_b RLS Restriction: If the DBMS_RLS.ADD_POLICY procedure has been used to add a fine-grained access control policy to a table or view, and if the specified policy function uses a spatial operator, the operator must be SDO_FILTER. No other spatial operators are supported in that context. SDO_FILTER Spatial Operators 19-15 1 cola_a The following example selects the GID values from the POLYGONS table where the GEOMETRY column objects are likely to interact spatially with the GEOMETRY column object in the QUERY_POLYS table that has a GID value of 1. SELECT A.gid FROM Polygons A, query_polys B WHERE B.gid = 1 AND SDO_FILTER(A.Geometry, B.Geometry) = 'TRUE'; The following example selects the GID values from the POLYGONS table where the GEOMETRY column object is likely to interact spatially with the geometry stored in the aGeom variable. Select A.Gid FROM Polygons A WHERE SDO_FILTER(A.Geometry, :aGeom) = 'TRUE'; The following example selects the GID values from the POLYGONS table where the GEOMETRY column object is likely to interact spatially with the specified rectangle having the lower-left coordinates (x1,y1) and the upper-right coordinates (x2, y2). Select A.Gid FROM Polygons A WHERE SDO_FILTER(A.Geometry, sdo_geometry(2003,NULL,NULL, sdo_elem_info_array(1,1003,3), sdo_ordinate_array(x1,y1,x2,y2)) ) = 'TRUE'; The following example selects the GID values from the POLYGONS table where the GEOMETRY column object is likely to interact spatially with any GEOMETRY column object in the QUERY_POLYS table. In this example, the ORDERED optimizer hint is used and the QUERY_POLYS (geometry2) table is specified first in the FROM clause, because multiple geometries from geometry2 are involved (see the Usage Notes). SELECT /*+ ORDERED */ A.gid FROM query_polys B, polygons A WHERE SDO_FILTER(A.Geometry, B.Geometry) = 'TRUE'; Related Topics ■ SDO_RELATE SDO_INSIDE 19-16 Oracle Spatial Developer's Guide SDO_INSIDE Format SDO_INSIDE(geometry1, geometry2); Description Checks if any geometries in a table have the INSIDE topological relationship with a specified geometry. Equivalent to specifying the SDO_RELATE operator with 'mask=INSIDE'. See the section on the SDO_RELATE operator in this chapter for information about the operations performed by this operator and for usage requirements. Keywords and Parameters Returns The expression SDO_INSIDE(geometry1,geometry2) = 'TRUE' evaluates to TRUE for object pairs that have the INSIDE topological relationship, and FALSE otherwise. Usage Notes See the Usage Notes for the SDO_RELATE operator in this chapter. For an explanation of the topological relationships and the nine-intersection model used by Spatial, see Section 1.8. For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Examples The following example finds geometries that have the INSIDE relationship with a query window (here, a rectangle with lower-left, upper-right coordinates 5,6, 12,12). (The example uses the definitions and data described in Section 2.1 and illustrated in Figure 2–1.) In this example, only cola_d (the circle) is inside the query window geometry. SELECT c.mkt_id, c.name FROM cola_markets c WHERE SDO_INSIDE(c.shape, SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1,1003,3), SDO_ORDINATE_ARRAY(5,6, 12,12)) ) = 'TRUE'; Value Description geometry1 Specifies a geometry column in a table. The column must be spatially indexed. Data type is SDO_GEOMETRY. geometry2 Specifies either a geometry from a table or a transient instance of a geometry. (Specified using a bind variable or SDO_GEOMETRY constructor.) Data type is SDO_GEOMETRY. SDO_INSIDE Spatial Operators 19-17 MKT_ID NAME ---------- -------------------------------- 4 cola_d SDO_JOIN 19-18 Oracle Spatial Developer's Guide SDO_JOIN Format SDO_JOIN(table_name1, column_name1, table_name2, column_name2, params, preserve_join_order, table1_partition, table2_partition) RETURN SDO_ROWIDSET; Description Performs a spatial join based on one or more topological relationships. Keywords and Parameters Returns SDO_JOIN returns an object of SDO_ROWIDSET, which consists of a table of objects of SDO_ROWIDPAIR. Oracle Spatial defines the type SDO_ROWIDSET as: CREATE TYPE sdo_rowidset as TABLE OF sdo_rowidpair; Value Description table_name1 Name of the first table to be used in the spatial join operation. The table must have a column of type SDO_GEOMETRY. Data type is VARCHAR2. column_name1 Name of the spatial column of type SDO_GEOMETRY in table_name1. A spatial R-tree index must be defined on this column. Data type is VARCHAR2. table_name2 Name of the second table to be used in the spatial join operation. (It can be the same as or different from table_name1. If table_name2 is the same as table_name1, see "Optimizing Self-Joins" in this section.) The table must have a column of type SDO_GEOMETRY. Data type is VARCHAR2. column_name2 Name of the spatial column of type SDO_GEOMETRY in table_name2. A spatial R-tree index must be defined on this column. Data type is VARCHAR2. params Optional parameter string of keywords and values; available only if mask=ANYINTERACT. Determines the behavior of the operator. See Table 19–3 in the Usage Notes for information about the available keywords. Data type is VARCHAR2. Default is NULL. preserve_join_ order Optional parameter to specify if the join order is guaranteed to be preserved during processing of the operator. If the value is 0 (the default), the order of the tables might be changed; if the value is 1, the order of the tables is not changed. Data type is NUMBER. Default is 0. table1_partition Name of the table partition in table_name1. Must be specified if the table has a partitioned spatial index; must be null if the table does not have a partitioned spatial index. (For information about using partitioned spatial indexes, see Section 5.1.3.) Data type is VARCHAR2. Default is null. table2_partition Name of the table partition in table_name2. Must be specified if the table has a partitioned spatial index; must be null if the table does not have a partitioned spatial index. (For information about using partitioned spatial indexes, see Section 5.1.3.) Data type is VARCHAR2. Default is null. SDO_JOIN Spatial Operators 19-19 Oracle Spatial defines the object type SDO_ROWIDPAIR as: CREATE TYPE sdo_rowidpair AS OBJECT (rowid1 VARCHAR2(24), rowid2 VARCHAR2(24)); In the SDO_ROWIDPAIR definition, rowid1 refers to a rowid from table_name1, and rowid2 refers to a rowid from table_name2. Usage Notes SDO_JOIN is technically not an operator, but a table function. (For an explanation of table functions, see Oracle Database PL/SQL Language Reference.) However, it is presented in the chapter with Spatial operators because its usage is similar to that of the operators, and because it is not part of a package with other functions and procedures. This table function is recommended when you need to perform full table joins. The geometries in column_name1 and column_name2 must have the same SRID (coordinate system) value and the same number of dimensions. For best performance, use the /*+ ORDERED */ optimizer hint, and specify the SDO_ JOIN table function first in the FROM clause. If a table is version-enabled (using the Workspace Manager feature), you must specify the _LT table created by Workspace Manager. For example, if the COLA_MARKETS table is version-enabled and you want to perform a spatial join operation on that table, specify COLA_MARKETS_LT (not COLA_MARKETS) with the SDO_JOIN table function. (However, for all other Spatial functions, procedures, and operators, do not use the _LT name.) Table 19–3 shows the keywords for the params parameter. Table 19–3 params Keywords for the SDO_JOIN Operator Keyword Description mask The topological relationship of interest.Valid values are 'mask=' where is one or more of the mask values valid for the SDO_RELATE operator (TOUCH, OVERLAPBDYDISJOINT, OVERLAPBDYINTERSECT, EQUAL, INSIDE, COVEREDBY, CONTAINS, COVERS, ANYINTERACT, ON), or FILTER, which checks if the MBRs (the filter-level approximations) intersect. Multiple masks are combined with the logical Boolean operator OR (for example, 'mask=inside+touch'); however, FILTER cannot be combined with any other mask. If this parameter is null or contains an empty string, mask=FILTER is assumed. distance Specifies a numeric distance value that is added to the tolerance value (explained in Section 1.5.5) before the relationship checks are performed. For example, if the tolerance is 10 meters and you specify 'distance=100 unit=meter', two objects are considered to have spatial interaction if they are within 110 meters of each other. If you specify distance but not unit, the unit of measurement associated with the data is assumed. SDO_JOIN 19-20 Oracle Spatial Developer's Guide Before you call SDO_JOIN, you must commit any previous DML statements in your session. Otherwise, the following error will be returned: ORA-13236: internal error in R-tree processing: [SDO_Join in active txns not supported] For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Optimizing Self-Joins If you are performing a self-join (that is, if table_name1 and table_name2 specify the same table), you can improve the performance by optimizing the self-join. If SDO_JOIN is called without a mask (for example, ANYINTERACT) or distance specification, it compares only the index structure of the two geometry columns being joined. This can quickly identify geometry pairs that are "likely" to interact. If SDO_ JOIN is called with a mask or distance specification, after the index is used to identify geometry pairs that are likely to interact, geometry coordinates are also compared to see if the geometry pairs actually do interact. Coordinate comparison is the most expensive part of the SDO_JOIN operation. In a self-join, where the same geometry column is compared to itself, each geometry pair is returned twice in the result set. For example: ■ For the geometry pair with ID values (1,2), the pair (2,1) is also returned. The undesired effect in SDO_JOIN is that the coordinates of the same geometry pair are compared twice, instead of once. ■ ID pairs that are equal are returned twice. For example, a table with 50,000 rows will return ID pair (1,1) twice, ID pair (2,2) twice, and so on. This is also an undesired effect. When calling SDO_JOIN in a self-join scenario, you can eliminate the undesired effects by eliminating duplicate comparison of geometry pairs and all coordinate comparisons where the ID values of the pairs match. This optimization uses SDO_ JOIN for the primary filter only, and calls the SDO_GEOM.RELATE function to compare geometry coordinates. The following statement accomplishes this optimization by adding "AND b.rowid < c.rowid" as a predicate to the WHERE clause. SQL> set autotrace trace explain SQL> SELECT /*+ ordered use_nl (a,b) use_nl (a,c) */ b.id, c.id FROM TABLE(sdo_join('GEOD_STATES','GEOM','GEOD_STATES','GEOM')) a, GEOD_STATES b, GEOD_STATES c WHERE a.rowid1 = b.rowid AND a.rowid2 = c.rowid AND b.rowid < c.rowid unit Specifies a unit of measurement to be associated with the distance value (for example, 'distance=100 unit=meter'). See Section 2.10 for more information about unit of measurement specification. If you specify unit, you must also specify distance. Data type is VARCHAR2. Default = unit of measurement associated with the data. For geodetic data, the default is meters. Table 19–3 (Cont.) params Keywords for the SDO_JOIN Operator Keyword Description SDO_JOIN Spatial Operators 19-21 AND SDO_GEOM.RELATE (b.geom, 'ANYINTERACT', c.geom, .05) = 'TRUE' Execution Plan ---------------------------------------------------------- Plan hash value: 1412731386 --------------------------------------------------------------------------------------------------- | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | --------------------------------------------------------------------------------------------------- | 0 | SELECT STATEMENT | | 1 | 1124 | 12787 (1)| 00:02:34 | | 1 | NESTED LOOPS | | 1 | 1124 | 12787 (1)| 00:02:34 | | 2 | NESTED LOOPS | | 4574 | 2514K| 8206 (1)| 00:01:39 | | 3 | COLLECTION ITERATOR PICKLER FETCH| SDO_JOIN | | || | |* 4 | TABLE ACCESS BY USER ROWID | GEOD_STATES | 1 | 561 |1 (0)| 00:00:01 | |* 5 | TABLE ACCESS BY USER ROWID | GEOD_STATES | 1 | 561 |1 (0)| 00:00:01 | Predicate Information (identified by operation id): --------------------------------------------------- 4 - access(CHARTOROWID(VALUE(KOKBF$))) 5 - access(CHARTOROWID(VALUE(KOKBF$))) filter("B".ROWID<"C".ROWID AND "SDO_GEOM"."RELATE"("B"."GEOM",'ANYINTERACT',"C"."GEOM",.05)='TRUE') SQL> set autotrace off In the preceding example, It is very important that AND b.rowid < c.rowid be before the call to SDO_GEOM.RELATE in the WHERE clause. This will omit the undesired scenarios for the invocation of the SDO_GEOM.RELATE function. Also, note that the example uses the ORDERED and USE_NL hints, and that the execution plan does not contain TABLE ACCESS FULL or HASH JOIN. Cross-Schema Invocation of SDO_JOIN You can invoke the SDO_JOIN table function on an indexed table that is not in your schema, if you have been granted SELECT access to both the spatial table and to the index table for the spatial index that was created on the spatial table. To find the name of the index table for a spatial index, query the SDO_INDEX_TABLE column in the USER_SDO_INDEX_METADATA view. For example, the following statement returns the name of the index table for the COLA_MARKETS_IDX spatial index: SELECT sdo_index_table FROM user_sdo_index_metadata WHERE sdo_index_name = 'COLA_SPATIAL_IDX'; Assume that user A owns spatial table T1 (with index table MDRT_F9AA$), and that user B owns spatial table T2 and wants to join geometries from both T1 and T2. Assume also that the geometry column in both tables is named GEOMETRY. User A or a suitably privileged user must connect as user A and execute the following statements: GRANT select on T1 to B; GRANT select on MDRT_F9AA$ to B; User B can now connect and execute an SDO_JOIN query, such as the following: SELECT COUNT(*) FROM (SELECT * FROM TABLE(SDO_JOIN('A.T1', 'GEOMETRY', 'B.T2', 'GEOMETRY', 'mask=anyinteract')) ); SDO_JOIN 19-22 Oracle Spatial Developer's Guide Examples The following example joins the COLA_MARKETS table with itself to find, for each geometry, all other geometries that have any spatial interaction with it. (The example uses the definitions and data from Section 2.1.) In this example, rowid1 and rowid2 correspond to the names of the attributes in the SDO_ROWIDPAIR type definition. Note that in the output, cola_d (the circle in Figure 2–1) interacts only with itself, and not with any of the other geometries. SELECT /*+ ordered */ a.name, b.name FROM TABLE(SDO_JOIN('COLA_MARKETS', 'SHAPE', 'COLA_MARKETS', 'SHAPE', 'mask=ANYINTERACT')) c, cola_markets a, cola_markets b WHERE c.rowid1 = a.rowid AND c.rowid2 = b.rowid ORDER BY a.name; NAME NAME -------------------------------- -------------------------------- cola_a cola_c cola_a cola_b cola_a cola_a cola_b cola_c cola_b cola_b cola_b cola_a cola_c cola_c cola_c cola_b cola_c cola_a cola_d cola_d 10 rows selected. Related Topics ■ SDO_RELATE SDO_NN Spatial Operators 19-23 SDO_NN Format SDO_NN(geometry1, geometry2, param [, number]); Description Uses the spatial index to identify the nearest neighbors for a geometry. Keywords and Parameters Table 19–4 lists the keywords for the param parameter. Value Description geometry1 Specifies a geometry column in a table. The column must be spatially indexed. Data type is SDO_GEOMETRY. geometry2 Specifies either a geometry from a table or a transient instance of a geometry. The nearest neighbor or neighbors to geometry2 will be returned from geometry1. (geometry2 is specified using a bind variable or SDO_ GEOMETRY constructor.) Data type is SDO_GEOMETRY. param Determines the behavior of the operator. The available keywords are listed in Table 19–4. If you do not specify this parameter, the operator returns all rows in increasing distance order from geometry2. Data type is VARCHAR2. number If the SDO_NN_DISTANCE ancillary operator is included in the call to SDO_NN, specifies the same number used in the call to SDO_NN_ DISTANCE. Data type is NUMBER. Table 19–4 Keywords for the SDO_NN Param Parameter Keyword Description distance Specifies the number of distance units after which to stop searching for nearest neighbors. If you do not also specify the unit keyword, the default is the unit of measurement associated with the data. Data type is NUMBER. For example: 'distance=10 unit=mile' sdo_batch_ size Specifies the number of rows to be evaluated at a time when the SDO_NN expression may need to be evaluated multiple times in order to return the desired number of results that satisfy the WHERE clause. Available only when an R-tree index is used. If you specify sdo_batch_size=0 (or if you omit the param parameter completely), Spatial calculates a batch size suited to the result set size. See the Usage Notes and Examples for more information. Data type is NUMBER. For example: 'sdo_batch_size=10' SDO_NN 19-24 Oracle Spatial Developer's Guide Returns This operator returns the sdo_num_res number of objects from geometry1 that are nearest to geometry2 in the query. In determining how near two geometry objects are, the shortest possible distance between any two points on the surface of each object is used. Usage Notes The operator is disabled if the table does not have a spatial index or if the number of dimensions for the query window does not match the number of dimensions specified when the index was created. The operator must always be used in a WHERE clause, and the condition that includes the operator should be an expression of the form SDO_NN(arg1, arg2, '') = 'TRUE'. The operator can be used in two ways: ■ If all geometries in the layer are candidates, use the sdo_num_res keyword to specify the number of geometries returned. ■ If any geometries in the table might be nearer than the geometries specified in the WHERE clause, use the sdo_batch_size keyword and use the WHERE clause (including the ROWNUM pseudocolumn) to limit the number of geometries returned. As an example of the sdo_batch_size keyword, assume that a RESTAURANTS table contains different types of restaurants, and you want to find the two nearest Italian restaurants to your hotel but only if they are within two miles. The query might look like the following: SELECT r.name FROM restaurants r WHERE SDO_NN(r.geometry, :my_hotel, 'sdo_batch_size=10 distance=2 unit=mile') = 'TRUE' AND r.cuisine = 'Italian' AND ROWNUM <=2; In this example, the ROWNUM <=2 clause is necessary to limit the number of results returned to no more than 2 where CUISINE is Italian. However, if the sdo_batch_ size keyword is not specified in this example, and if sdo_num_res=2 is specified sdo_num_res If sdo_batch_size is not specified, specifies the number of results (nearest neighbors) to be returned. If sdo_batch_size is specified, this keyword is ignored; instead, use the ROWNUM pseudocolumn to limit the number of results. If neither sdo_batch_size nor sdo_num_res is specified, this is equivalent to specifying sdo_batch_size=0. See the Usage Notes and Examples for more information. Data type is NUMBER. For example: 'sdo_num_res=5' unit If the distance keyword or the SDO_NN_DISTANCE ancillary operator is included in the call to SDO_NN, specifies the unit of measurement: a quoted string with unit= and an SDO_UNIT value from the MDSYS.SDO_DIST_UNITS table. See Section 2.10 for more information about unit of measurement specification. Data type is VARCHAR2. Default = unit of measurement associated with the data. For geodetic data, the default is meters. For example: 'unit=KM' Table 19–4 (Cont.) Keywords for the SDO_NN Param Parameter Keyword Description SDO_NN Spatial Operators 19-25 instead of ROWNUM <=2, only the two nearest restaurants within two miles are considered, regardless of their CUISINE value; and if the CUISINE value of these two rows is not Italian, the query may return no rows. The sdo_batch_size value can affect the performance of nearest neighbor queries. A good general guideline is to specify the number of candidate rows likely to satisfy the WHERE clause. Using the preceding example of a query for Italian restaurants, if approximately 20 percent of the restaurants nearest to the hotel are Italian and if you want 2 restaurants, an sdo_batch_size value of 10 will probably result in the best performance. On the other hand, if only approximately 5 percent of the restaurants nearest to the hotel are Italian and if you want 2 restaurants, an sdo_batch_size value of 40 would be better. You can specify sdo_batch_size=0, which causes Spatial to calculate a batch size that is suitable for the result set size. However, the calculated batch size may not be optimal, and the calculation incurs some processing overhead; if you can determine a good sdo_batch_size value for a query, the performance will probably be better than if you specify sdo_batch_size=0. If the sdo_batch_size keyword is specified, any sdo_num_res value is ignored. Do not specify both keywords. Specify the number parameter only if you are using the SDO_NN_DISTANCE ancillary operator in the call to SDO_NN. See the information about the SDO_NN_ DISTANCE operator in this chapter. If two or more objects from geometry1 are an equal distance from geometry2, any of the objects can be returned on any call to the function. For example, if item_a, item_b, and item_c are nearest to and equally distant from geometry2, and if sdo_num_res=2, two of those three objects are returned, but they can be any two of the three. If the SDO_NN operator uses a partitioned spatial index (see Section 5.1.3), the requested number of geometries is returned for each partition that contains candidate rows based on the query criteria. For example, if you request the 5 nearest restaurants to a point and the spatial index has 4 partitions, the operator returns up to 20 (5*4) geometries. In this case, you must use the ROWNUM pseudocolumn (here, WHERE ROWNUM <=5) to return the 5 nearest restaurants. If geometry1 and geometry2 are based on different coordinate systems, geometry2 is temporarily transformed to the coordinate system of geometry1 for the operation to be performed, as described in Section 6.10.1. SDO_NN is not supported for spatial joins. In some situations the SDO_NN operator will not use the spatial index unless an optimizer hint forces the index to be used. This can occur when a query involves a join; and if the optimizer hint is not used in such situations, an internal error occurs. To prevent such errors, you should always specify an optimizer hint to use the spatial index with the SDO_NN operator, regardless of how simple or complex the query is. For example, the following excerpt from a query specifies to use the COLA_SPATIAL_ IDX index that is defined on the COLA_MARKETS table: SELECT /*+ INDEX(c cola_spatial_idx) */ c.mkt_id, c.name, ... FROM cola_markets c, ...; However, if the column predicate in the WHERE clause specifies any nonspatial column in the table for geometry1 that has an associated index, be sure that this index is not used by specifying the NO_INDEX hint for that index. For example, if SDO_NN 19-26 Oracle Spatial Developer's Guide there was an index named COLA_NAME_IDX defined on the NAME column, you would need to specify the hints in the preceding example as follows: SELECT /*+ INDEX(c cola_spatial_idx) NO_INDEX(c cola_name_idx) */ c.mkt_id, c.name, ... FROM cola_markets c, ...; (Note, however, that there is no index named COLA_NAME_IDX in the example in Section 2.1.) If you join two or more tables with the SDO_NN operator and the sdo_num_res keyword, specify the LEADING hint for the outer table, USE_NL hint to have a nested loops join, and the INDEX hint for the inner table (the table with the spatial index). For example: SELECT /*+ LEADING(b) USE_NL(b a) INDEX(a cola_spatial_idx) */ a.gid FROM cola_qry b, cola_markets a WHERE SDO_NN(a.shape, b.shape, 'sdo_num_res=1')='TRUE'; However, if you join two or more tables with the SDO_NN operator, the sdo_batch_ size keyword, and the ROWNUM clause, the best way to implement the logic is to use a PL/SQL block. For example: BEGIN FOR item IN ( SELECT b.shape FROM cola_qry b) LOOP SELECT /*+ INDEX(a cola_spatial_idx) */ a.gid INTO local_gid FROM cola_markets a WHERE SDO_NN(a.shape, item.shape, 'sdo_batch_size=10')='TRUE' and a.name like ‘cola%’ and ROWNUM <2; END LOOP; END; For detailed information about using optimizer hints, see Oracle Database Performance Tuning Guide. For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Examples The following example finds the two objects from the SHAPE column in the COLA_ MARKETS table that are nearest to a specified point (10,7). (The example uses the definitions and data described in Section 2.1 and illustrated in Figure 2–1.) SELECT /*+ INDEX(c cola_spatial_idx) */ c.mkt_id, c.name FROM cola_markets c WHERE SDO_NN(c.shape, sdo_geometry(2001, NULL, sdo_point_type(10,7,NULL), NULL, NULL), 'sdo_num_res=2') = 'TRUE'; MKT_ID NAME ---------- -------------------------------- 2 cola_b 4 cola_d The following example uses the sdo_batch_size keyword to find the two objects (ROWNUM <=2), with a NAME value less than 'cola_d', from the SHAPE column in the COLA_MARKETS table that are nearest to a specified point (10,7). The value of 3 for sdo_batch_size represents a best guess at the number of nearest geometries that need to be evaluated before the WHERE clause condition is satisfied. (The example uses the definitions and data from Section 2.1.) SDO_NN Spatial Operators 19-27 SELECT /*+ INDEX(c cola_spatial_idx) */ c.mkt_id, c.name FROM cola_markets c WHERE SDO_NN(c.shape, sdo_geometry(2001, NULL, sdo_point_type(10,7,NULL), NULL, NULL), 'sdo_batch_size=3') = 'TRUE' AND c.name < 'cola_d' AND ROWNUM <= 2; MKT_ID NAME ---------- -------------------------------- 2 cola_b 3 cola_c See also the more complex SDO_NN examples in Section C.3. Related Topics ■ SDO_NN_DISTANCE SDO_NN_DISTANCE 19-28 Oracle Spatial Developer's Guide SDO_NN_DISTANCE Format SDO_NN_DISTANCE(number); Description Returns the distance of an object returned by the SDO_NN operator. Valid only within a call to the SDO_NN operator. Keywords and Parameters Returns This operator returns the distance of an object returned by the SDO_NN operator. In determining how near two geometry objects are, the shortest possible distance between any two points on the surface of each object is used. Usage Notes SDO_NN_DISTANCE is an ancillary operator to the SDO_NN operator. It returns the distance between the specified geometry and a nearest neighbor object. This distance is passed as ancillary data to the SDO_NN operator. (For an explanation of how operators can use ancillary data, see the section on ancillary data in the chapter on domain indexes in Oracle Database Data Cartridge Developer's Guide.) You can choose any arbitrary number for the number parameter. The only requirement is that it must match the last parameter in the call to the SDO_NN operator. Use a bind variable to store and operate on the distance value. Examples The following example finds the two objects from the SHAPE column in the COLA_ MARKETS table that are nearest to a specified point (10,7), and it finds the distance between each object and the point. (The example uses the definitions and data described in Section 2.1 and illustrated in Figure 2–1.) SELECT /*+ INDEX(c cola_spatial_idx) */ c.mkt_id, c.name, SDO_NN_DISTANCE(1) dist FROM cola_markets c WHERE SDO_NN(c.shape, sdo_geometry(2001, NULL, sdo_point_type(10,7,NULL), NULL, NULL), 'sdo_num_res=2', 1) = 'TRUE' ORDER BY dist; MKT_ID NAME DIST ---------- -------------------------------- ---------- 4 cola_d .828427125 2 cola_b 2.23606798 Value Description number Specifies a number that must be the same as the last parameter passed to the SDO_NN operator. Data type is NUMBER. SDO_NN_DISTANCE Spatial Operators 19-29 Note the following about this example: ■ 1 is used as the number parameter for SDO_NN_DISTANCE, and 1 is also specified as the last parameter to SDO_NN (after 'sdo_num_res=2'). ■ The column alias dist holds the distance between the object and the point. (For geodetic data, the distance unit is meters; for non-geodetic data, the distance unit is the unit associated with the data.) The following example uses the sdo_batch_size keyword in selecting the two closest Italian restaurants to your hotel from a YELLOW_PAGES table that contains different types of businesses: SELECT * FROM (SELECT /*+ FIRST_ROWS */ y.name FROM YELLOW_PAGES y WHERE SDO_NN(y.geometry, :my_hotel, 'sdo_batch_size=100', 1) = 'TRUE' AND y.business = 'Italian Restaurant' ORDER BY SDO_NN_DISTANCE(1)) WHERE ROWNUM <=10; In the preceding query, the FIRST_ROWS hint enables the optimizer to improve performance by pushing the ORDER BY operation into the spatial index. :my_hotel can be either a bind variable or a literal value. The FIRST_ROWS hint is also available to a local partitioned spatial index. In the preceding example, if the YELLOW_PAGES table is partitioned by name, the query will be executed as follows: 1. For each partition, the ORDER BY operation is processed using the spatial index until 10 rows are found. 2. After all partitions are completed, all rows found in the preceding step are sorted, and the top 10 rows are returned. Related Topics ■ SDO_NN SDO_ON 19-30 Oracle Spatial Developer's Guide SDO_ON Format SDO_ON(geometry1, geometry2); Description Checks if any geometries in a table have the ON topological relationship with a specified geometry. Equivalent to specifying the SDO_RELATE operator with 'mask=ON'. See the section on the SDO_RELATE operator in this chapter for information about the operations performed by this operator and for usage requirements. Keywords and Parameters Returns The expression SDO_ON(geometry1,geometry2) = 'TRUE' evaluates to TRUE for object pairs that have the ON topological relationship, and FALSE otherwise. Usage Notes See the Usage Notes for the SDO_RELATE operator in this chapter. For an explanation of the topological relationships and the nine-intersection model used by Spatial, see Section 1.8. For information about 3D support with Spatial operators (which operators do and do not consider all three dimensions in their computations), see Section 1.11. Examples The following example finds geometries tha