I am trying to create a spatial index for some shapefiles using the Qgis API. I have followed the steps described in Nathan Woodrow's blog (https://nathanw.net/2013/01/04/using-a-qgis-spatial-index-to-speed-up-your-code/) and it works great:

layer = QgsVectorLayer(path, name, 'ogr')
idx = QgsSpatialIndex()
all_features = layer.getFeatures()
map(idx.insertFeature, all_features)

My problem is that I don't have any resulting file (.qix ? .sbn ? .sbx ?)

How can I save this spatial index so that future users of the shapefiles can benefit from it ?


If you want to create a spatial index for all features in your layer, you could try using the following:


This will create the .qix spatial index file.


As mentioned by Matthias Kuhn in his comments below, the QgsSpatialIndex class is only used temporarily as seen in the blog you linked to; whereas the createSpatialIndex() function creates a spatial index on the datasource and results in a qix file for shapefiles.

  • 2
    I think it would be good to highlight the difference between a persistent (file-based) and temporary, runtime index (QgsSpatialIndex). – Matthias Kuhn Nov 22 '16 at 12:07
  • 1
    Thanks guys ! I could only find information about QgsSpatialIndex. createSpatialIndex is exactly what I was looking for. – Lauref Nov 22 '16 at 13:11
  • @Lauref - Awesome, glad it helped :) – Joseph Nov 22 '16 at 13:22
  • After 4 tries to write something comprehensive in this comment, I have to surrender and admit that it would require more for something adequate. What I wanted to say is just that the information that QgsSpatialIndex is not persistent gives a lot of information already without any extra explanation. – Matthias Kuhn Nov 22 '16 at 13:32
  • @MatthiasKuhn - Thanks, I've edited the post to include a brief explanation as you mentioned ;) – Joseph Nov 22 '16 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.