Using generators for layer queries

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.

Getting ready

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

How to do it...

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:

  1. First, we import the query engine module:
    from query import query
    
  2. Then, we set up the path to our shapefile and load it as a vector layer:
    pth = "/Users/joellawhead/qgis_data/ms/MS_UrbanAnC10.shp"
    layer = QgsVectorLayer(pth, "Urban Areas", "ogr")
    
  3. Now, we can run the query, which uses Python's dot notation to perform a 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"))
    
  4. Finally, we'll use the query's generator to iterate to the first result:
    q().next()
    

How it works...

As you can see, this module is quite handy. To perform this same query using the default PyQGIS API, it would take nearly four times as much code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset