Sql-Server

未使用空間索引

  • February 19, 2017

我有一個帶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

正確的。遺憾的是,在這種情況下,空間索引沒有得到利用。

空間索引提供一組網格,允許系統辨識與這些網格重疊的幾何(或地理)。

您最好的選擇是設置可接受的接近度門檻值,並嘗試使用 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 子句,它應該可以工作。

引用自:https://dba.stackexchange.com/questions/59840