Skip to content

Commit 7c8177e

Browse files
committed
Use expression filter request for SelectByAttribute
Makes SelectByAttribute orders of magnitude faster for providers which support compiled expressions (eg Postgres), also allows algorithm to take advantage of database indexes created on attribute. For a 4 million point PostGIS layer (with an index on attribute) BEFORE: cancelled after 20 mins AFTER: ~2 seconds
1 parent fd9f0b5 commit 7c8177e

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed

python/plugins/processing/algs/qgis/SelectByAttribute.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
__revision__ = '$Format:%H$'
2727

2828
from PyQt4.QtCore import QVariant
29-
from qgis.core import QgsExpression
29+
from qgis.core import QgsExpression, QgsFeatureRequest
3030
from processing.core.GeoAlgorithm import GeoAlgorithm
3131
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
3232
from processing.core.parameters import ParameterVector
@@ -115,18 +115,12 @@ def processAlgorithm(self, progress):
115115
raise GeoAlgorithmExecutionException(
116116
self.tr('Unsupported field type "%s"' % fields[idx].typeName()))
117117

118-
expression = QgsExpression(expr)
119-
expression.prepare(fields)
120-
121-
features = vector.features(layer)
122-
123-
selected = []
124-
count = len(features)
125-
total = 100.0 / float(count)
126-
for count, f in enumerate(features):
127-
if expression.evaluate(f, fields):
128-
selected.append(f.id())
129-
progress.setPercentage(int(count * total))
118+
qExp = QgsExpression(expr)
119+
if not qExp.hasParserError():
120+
qReq = QgsFeatureRequest(qExp)
121+
else:
122+
raise GeoAlgorithmExecutionException(qExp.parserErrorString())
123+
selected = [f.id() for f in layer.getFeatures(qReq)]
130124

131125
layer.setSelectedFeatures(selected)
132126
self.setOutputValue(self.OUTPUT, fileName)

0 commit comments

Comments
 (0)