[GIS] Selecting features using expression with ‘maximum’ aggregates function in QGIS python console

pyqgis

I am trying to accomplish what should be a simple task: selecting features using an expression in the python console. I am using QGIS 2.18.14 and the Alaska Airports dataset from the QGIS sample data.
I want to select the feature with the highest value in the “ELEV” field.
My code snippet is:

layer = iface.activeLayer()
expr = QgsExpression('"ELEV" = maximum"ELEV"')
selection = layer.getFeatures(QgsFeatureRequest(expr))
ids = [s.id() for s in selection]
layer.setSelectedFeatures(ids)

However, the result is that no features are selected (with no error messages).

If I use this expression : "ELEV" = maximum( "ELEV" ) in the Select by expression dialog from the GUI, all works as expected, selecting the feature with the maximum elevation value.

Using other expressions in the python console also work successfully, for example:

layer = iface.activeLayer()
expr = QgsExpression('"ELEV" <100')
selection = layer.getFeatures(QgsFeatureRequest(expr))
ids = [s.id() for s in selection]
layer.setSelectedFeatures(ids)

The above code snippet works well, selecting all features with elevation values less than 100.

As I am very much a beginner with Python, I am assuming the problem is with the syntax of the expression within my python code.
To this end I have tried typing the expression in different ways including:

expr = QgsExpression('"ELEV" = maximum"ELEV"')

expr = QgsExpression('"ELEV" = maximum\"ELEV\"')

expr = QgsExpression('"ELEV" = maximum\( "ELEV" \)')

expr = QgsExpression('"ELEV" = maximum\("ELEV"\)')

Which all give the same result- no error message but no features selected.

How do I use the ‘maximum’ aggregates function as an expression with PyQGIS code?

Best Answer

Not sure if it's a bug or something else but a possible workaround could be to determine the maximum value using the QgsVectorLayer::maximumValue() method and putting this into the QgsExpression:

layer = iface.activeLayer()
field_name = 'ELEV'
field = layer.fieldNameIndex(field_name)
max_value = str(layer.maximumValue(field))
expr = QgsExpression(field_name + ' = ' + max_value)
selection = layer.getFeatures(QgsFeatureRequest(expr))
ids = [s.id() for s in selection]
layer.setSelectedFeatures(ids)