Mic*_*elD 5 performance index sql-server spatial query-performance
我有一个带geometry
列的表。对于一个记录,只Point
存储一个。已创建空间索引,但搜索最近位置的查询不使用此索引,从而导致性能不佳。
示例脚本:
--Create the table
create table Location(
LocationID int not null identity(1,1) primary key,
LocationPoint geometry
)
--add records
declare @counter int =0
WHILE @counter<150000
BEGIN
set nocount on
--select
set @counter =@counter +1
declare @RandomLocation geometry=geometry::Point(RAND() *1000, RAND() *1000, 0)
insert into Location(LocationPoint) values (@RandomLocation)
END
--create index
CREATE SPATIAL INDEX SPATIAL_StructureBE ON dbo.Location(LocationPoint)
USING GEOMETRY_GRID WITH (
BOUNDING_BOX = (xmin = 0.0, ymin = 0.0, xmax = 1000, ymax = 1000),
GRIDS = ( LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),
CELLS_PER_OBJECT = 16,
STATISTICS_NORECOMPUTE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON)
--Search, this query should use the index but it doesn't
declare @CurrentLocation geometry=geometry::Point(24,50, 0)
select top 1 *
from Location
order by LocationPoint.STDistance(@CurrentLocation) asc
Run Code Online (Sandbox Code Playgroud)
正确的。遗憾的是,空间索引在这种情况下没有得到利用。
空间索引提供一组网格,允许系统识别与这些网格重叠的几何图形(或地理)。
最好的办法是设置一个可接受的接近度阈值,然后尝试使用 STBuffer 之类的东西。STIntersects 运行良好,如果没有发现任何内容,您可以增加此阈值(例如,如果没有发现任何内容,则使用第二个 OUTER APPLY。
编辑:他们现在做!检查我的帖子...... http://blogs.lobsterpot.com.au/2014/08/14/sql-spatial-getting-nearest-calculations-working-properly/
总之,要使用您的索引,您需要确保您的 ORDER BY 值不能为 NULL - 只需添加一个 WHERE...IS NOT NULL 子句,它应该可以工作。