Python generators provide an efficient way to process large datasets. A QGIS developer named Nathan Woodrow has created a simple Python QGIS query engine that uses generators to easily fetch features from QGIS layers. We'll use this engine in this recipe to query a layer.
You need to install the query engine using easy_install
or by downloading it and adding it to your QGIS Python installation. To use easy_install
, run the following command from a console, which downloads a clone of the original code that includes a Python setup file:
easy_install
https://github.com/GeospatialPython/qquery/archive/master.zip
You can also download the ZIP file from https://github.com/NathanW2/qquery/archive/master.zip and copy the contents to your working directory or the site-packages
directory of your QGIS Python installation.
You will also need to download the zipped shapefile and decompress it to a directory named ms
in your qgis_data
directory from the following location:
https://geospatialpython.googlecode.com/files/MS_UrbanAnC10.zip
We'll load a layer containing population data. Then, we'll use the query engine to perform a simple query for an urban area with less than 50,000 people. We'll filter the results to only give us three columns, place name, population level, and land area. To do this, we need to perform the following steps:
from query import query
pth = "/Users/joellawhead/qgis_data/ms/MS_UrbanAnC10.shp" layer = QgsVectorLayer(pth, "Urban Areas", "ogr")
where
clause search and then filter using a select
statement. This line will return a generator with the result:q = (query(layer).where("POP > 50000").select('NAME10', "POP", "AREALAND", "POPDEN"))
q().next()