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
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') radios=pry.mapLayersByName('radios_censales') 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.