I built a manual index on a shapefile, through the process "Create spatial index", which can be found in the process toolbox > general vector tools.
This process creates a persistent spatial index, a .qix
file.
I want to optimize the query: "How many polygons of a layer are contained within one or more larger polygons that I select" using PyQGIS.
Both layers are based on files in polygon shapefile format. The layer of the polygons that will be evaluated has more than 300.000 entities.
I can build and use a custom index with this code:
pry=QgsProject.instance()
parcelas=pry.mapLayersByName('parcelas')[0]
radios=pry.mapLayersByName('radios_censales')[0]
tiempo_inicial = time.time()
index = QgsSpatialIndex() # Spatial index
index = QgsSpatialIndex(parcelas.getFeatures())
duracionSI=time.time()-tiempo_inicial # 6.816403388977051 sec
csi=0
lisIds=[]
tiempo_inicial = time.time()
for i in radios.getSelectedFeatures():
bbx= i.geometry().boundingBox()
listIds=index.intersects(bbx)
for j in listIds:
if i.geometry().contains(parcelas.getFeature(j).geometry()):
csi=csi+1
duracionSI=time.time()-tiempo_inicial
But what I really want to do is leverage the existing .qix
file directly, so I don't have to spend six seconds compiling the index every time. How can I do this from PyQGIS?
Note: I am aware that the spatial index file must be updated if geometries are modified, removed or added.
index.intersects
. I guess that you should rather open the shapefile that has .qix index with the ogr provider and query asa.geometry().intersects(b.geometry())
and hope that the qix index is utilized transparently. See also gis.stackexchange.com/questions/168266/…