4

I have a point PostGIS layer (my_layer) which has more than 66000 features. I am getting the features I want but it takes too long. My code is:

    resultList = []
    req = QgsFeatureRequest().setFilterExpression(' "some_field_name" = \'some_value\' ')
    for feat in my_layer.getFeatures(req):
        name = feat.attribute("some_other_field")
        resultList.append(name)

How can I optimize it so that I can get the results quicker?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
okorkut
  • 268
  • 1
  • 9

2 Answers2

8

QGIS API provides you with a couple of ways for optimizing features requests.

In your case, if you don't need geometry and the rest of attributes in the result, you can:

  • Use flag NoGeometry (see docs).
  • Set subset of attributes you really need using setSubsetOfAttributes() (see docs).

That should speed your request up.

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
6

Another suggestion which may also help - make sure you have a suitable index created on your field on the Postgres database, and then switch on the option under Settings -> Data Sources -> "Execute expressions on server-side if possible". That should make a huge difference, as all the filtering will be done on the server rather then sending ALL the features in the layer to QGIS to filter.

ndawson
  • 27,620
  • 3
  • 61
  • 85