How to Get features by their attributes (similar to Iqueryfilter in arcobjects) in Qgis using python? Instead of getting all features and filter it manually, is there any option to use whereclause to filter it out?

For Example: I have a field name called 'Counties'. It has more than fifty thousand of features.i.e not possible to fetch all features and filter it because of time consuming. So i can query it by using iqueryfilter.whereclause = 'Counties = Norwich' in arcobjects. Similar thing i need in PyQgis. kindly let me know whether its doable. If so, please give me an example


Update Please read this answer for a safer method of achieving the same https://gis.stackexchange.com/a/74940/9839

In case you experience performance issues you may still resort to original method described below.

The only way of forwarding a WHERE clause to the data provider (backend) at the moment is to use the setSubsetString method of QgsDataProvider

If you have a QgsVectorLayer assigned to a variable vl :

vl.setSubsetString( 'Counties = "Norwich"' )

This causes heavy side-effects, because the filter will then apply to the whole layer and not only to your query, so you have to carefully consider if this is really an option for your use case!

Any other option will require a seperate connection to the database or adding a new layer with a subsetString as outlined above.

  • Its working fine. just like definition query in Arcgis. Thanks a lot – venkat Apr 22 '13 at 12:29
  • I have 4 lakhs features in a shape file..its taking long time to execute this query 'Counties = "Norwich"'. is there any solutions to speedup the execution? – venkat Jun 10 '13 at 12:59
  • You can probably create an index on the column (untested) – Matthias Kuhn Jun 10 '13 at 13:02
  • Yes I created an index by using ArcCatalog. but no effect – venkat Jun 11 '13 at 5:22
  • This is a gdal issue. You can read up on it here gdal.org/ogr/drv_shapefile.html . QGis 1.9 (master) provides vl.dataProvider().createAttributeIndex( fieldIndex ) as frontend to index creation. – Matthias Kuhn Jun 11 '13 at 6:04

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.