11.4.10 Creating Spatial Indexes创建空间索引

For InnoDB and MyISAM tables, MySQL can create spatial indexes using syntax similar to that for creating regular indexes, but using the SPATIAL keyword. 对于InnoDBMyISAM表,MySQL可以使用与创建常规索引类似的语法创建空间索引,但使用SPATIAL关键字。Columns in spatial indexes must be declared NOT NULL. The following examples demonstrate how to create spatial indexes:空间索引中的列必须声明为NOT NULL。以下示例演示了如何创建空间索引:

SPATIAL INDEX creates an R-tree index. 创建R树索引。For storage engines that support nonspatial indexing of spatial columns, the engine creates a B-tree index. A B-tree index on spatial values is useful for exact-value lookups, but not for range scans.对于支持空间列的非空间索引的存储引擎,该引擎会创建一个B树索引。空间值的B树索引对于精确的值查找很有用,但对于范围扫描则不有用。

The optimizer can use spatial indexes defined on columns that are SRID-restricted. 优化器可以使用在受SRID限制的列上定义的空间索引。For more information, see Section 11.4.1, “Spatial Data Types”, and Section 8.3.3, “SPATIAL Index Optimization”.有关更多信息,请参阅第11.4.1节,“空间数据类型”第8.3.3节,“空间索引优化”

For more information on indexing spatial columns, see Section 13.1.15, “CREATE INDEX Statement”.有关索引空间列的更多信息,请参阅第13.1.15节,“CREATE INDEX语句”

To drop spatial indexes, use ALTER TABLE or DROP INDEX:要删除空间索引,请使用ALTER TABLEDROP INDEX

Example: Suppose that a table geom contains more than 32,000 geometries, which are stored in the column g of type GEOMETRY. The table also has an AUTO_INCREMENT column fid for storing object ID values.示例:假设一个表geom包含32000多个几何图形,这些几何图形存储在GEOMETRY类型的g列中。该表还有一个AUTO_INCREMENTfid,用于存储对象ID值。

mysql> DESCRIBE geom;
+-------+----------+------+-----+---------+----------------+
| Field | Type     | Null | Key | Default | Extra          |
+-------+----------+------+-----+---------+----------------+
| fid   | int(11)  |      | PRI | NULL    | auto_increment |
| g     | geometry |      |     |         |                |
+-------+----------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> SELECT COUNT(*) FROM geom;
+----------+
| count(*) |
+----------+
|    32376 |
+----------+
1 row in set (0.00 sec)

To add a spatial index on the column g, use this statement:要在g列上添加空间索引,请使用以下语句:

mysql> ALTER TABLE geom ADD SPATIAL INDEX(g);
Query OK, 32376 rows affected (4.05 sec)
Records: 32376  Duplicates: 0  Warnings: 0