Manipulating a CSV with Pandas

At my day job I am working on some natural language processing and need to generate a list of place names so I can further train the excellent spacy library.  I previously imported the full Planet OSM so went there to pull a list of places.  However, the place names in OSM are typically in the language of the person who did the collection, so they can be anything from English to Arabic.  I stored the OSM data using imposm3 and included a PostgreSQL hstore column to store all of the user tags so we would not lose any data.  I did a search for all tags that had values like name and en in them and exported those keys and values to  several CSV files based on the points, lines, and polygons tables.  I thought I would write a quick post to show how easy it can be to manipulate data outside of traditional spreadsheet software.

The next thing I needed to do was some data reduction, so I went to my go-to library of Pandas.  If you have been living under a rock and have not heard of it, Pandas is an exceptional data processing library that allows you to easily manipulate data from Python.  In this case, I knew some of my data rows were empty and that I would have duplicates due to how things get named in OSM.  Pandas makes cleaning data incredibly easy in this case.

First I needed to load the files into Pandas to being cleaning things up.  My personal preference for a Python interpreter is ipython/jupyter in a console window. To do this I ran ipython and then imported Pandas by doing the following:

In [1]: import pandas as pd

Next I needed to load up the CSV into Pandas to start manipulating the data.

In [2]: df = pd.read_csv('osm_place_lines.csv', low_memory=False)

At this point, I could examine how many columns and rows I have by running:

In [3]: df.shape
Out[3]: (611092, 20)

Here we can see that I have 611,092 rows and 20 columns.  My original query pulled a lot of columns because I wanted to try to capture as many pre-translated English names as I could.  To see what all of the column names are, I just had to run:

In [10]: df.columns
Index(['name', 'alt_name_1_en', 'alt_name_en', 'alt_name_en_2',
       'alt_name_en_3', 'alt_name_en_translation', 'en_name',
       'gns_n_eng_full_name', 'name_en', 'name_ena', 'name_en1', 'name_en2',
       'name_en3', 'name_en4', 'name_en5', 'name_en6', 'nam_en', 'nat_name_en',
       'official_name_en', 'place_name_en'],

The first task I then wanted to do was drop any rows that had no values in them.  In Pandas, empty cells default to the NaN value.  So to drop all the empty rows, I just had to run:

In [4]: df = df.dropna(how='all')

To see how many rows fell out, I again checked the shape of the data.

In [5]: df.shape
Out[5]: (259564, 20)

Here we can see that the CSV had 351,528 empty rows where the line had no name or English name translations.

Next, I assumed that I had some duplicates in the data.  Some things in OSM get generic names, so these can be filtered out since I only want the first row from each duplicate.  With no options, drop_duplicates() in Pandas only keeps the first value.

In [6]: df = df.drop_duplicates()

Checking the shape again, I can see that I had 68,131 rows of duplicated data.

In [7]: df.shape
Out[7]: (191433, 20)

At this point I was interested in how many cells in each row still contained no data.  The CSV was already sparse since I converted each hstore key into a separate column in my output.  To do this, I ran:

In [8]: df.isna().sum()
name                          188
alt_name_1_en              191432
alt_name_en                190310
alt_name_en_2              191432
alt_name_en_3              191432
alt_name_en_translation    191432
en_name                    191430
gns_n_eng_full_name        191432
name_en                    191430
name_ena                   172805
name_en1                   191409
name_en2                   191423
name_en3                   191429
name_en4                   191430
name_en5                   191432
name_en6                   191432
nam_en                     191432
nat_name_en                191431
official_name_en           191427
place_name_en              191429
dtype: int64

Here we can see the sparseness of the data.  Considering I am now down to 191,433 columns, some of the columns only have a single entry in them.  We can also see that I am probably not going to have a lot of English translations to work with.

At this point I wanted to save the modified dataset so I would not loose it.  This was a simple

In [8]: df.to_csv('osm_place_lines_nonull.csv', index=False)

The index=False option tells Pandas to not output its internal index field to the CSV.

Now I was curious what things looked like, so I decided to check out the name column.  First I increased some default values in Pandas because I did not want it to abbreviate rows or columns.

pd.set_option('display.max_rows', 200)
pd.set_option('display.max_columns', 25)

To view the whole row where the value in a specific column is null, I did the following and I will abbreviate the output to keep the blog shorter 🙂

       name_en                                 name_ena name_en1 name_en2  \
166        NaN                        Orlovskogo Island      NaN      NaN   
129815     NaN                            Puukii Island      NaN      NaN   
159327     NaN                           Ometepe Island      NaN      NaN   
162420     NaN                                  Tortuga      NaN      NaN   
164834     NaN                         Jack Adan Island      NaN      NaN   
191664     NaN                            Hay Felistine      NaN      NaN   
193854     NaN             Alborán Island Military Base      NaN      NaN   
197893     NaN                         Carabelos Island      NaN      NaN   
219472     NaN                           Little Fastnet      NaN      NaN   
219473     NaN                             Fastnet Rock      NaN      NaN   
220004     NaN                           Doonmanus Rock      NaN      NaN   
220945     NaN                             Tootoge Rock      NaN      NaN   
229446     NaN                               Achallader      NaN      NaN   
238355     NaN                            Ulwile Island      NaN      NaN   
238368     NaN                             Mvuna Island      NaN      NaN   
238369     NaN                            Lupita Island      NaN      NaN   
238370     NaN                              Mvuna Rocks      NaN      NaN   
259080     NaN                                  Kafouri      NaN      NaN   
259235     NaN                              Al Thawra 8      NaN      NaN   
259256     NaN                              Beit al-Mal      NaN      NaN   
261584     NaN                                   Al Fao      NaN      NaN   
262200     NaN                                  May 1st      NaN      NaN   

Now that I have an idea how things look, I can do things like fill out the rest of the name columns with the English names found the various other columns.


Added a GNIS “Fixer” to my misc_gis_scripts repository

As I’ve posted before, the download from the USGS Geonames site has some problems.  The feature_id column should be unique, but it is not because the file contains some of the same feature names in Mexico and Canada with the same id which breaks the unique constraint.

I just added a very quick and dirty python program to my misc_gis_scripts repo on Github.  It’s run by

python3 downloadedgnisfile newgnisfile

For the latest download, it removed over 7,000 non-US or US Territory entries and into the DB perfectly.

Geonames Part 2

Since I needed it as part of my job, I finally got around to finishing up the Geonames scripts in my github repository misc_gis_scripts.  In the geonames subdirectory is a bash script called  Create a PostGIS database, edit the bash file, and then run it and it will download and populate your Geonames database for you.

Note that I’m not using the alternatenamesv2 file that they’re distributing now.  I checked with a hex editor and they’re not actually including all fields on each line, and Postgres will not import a file unless each column is there.  I’ll probably add in a Python file to fix it at some point but not now 🙂

Quick Post: My New SBC Computer – the Asus Tinkerboard

A while back I picked up a Raspberry Pi 3 and turned it into a NAS and LAMP stack server (Apache, PostgreSQL, Mysql, PostGIS, and so on).  Later I came across forums mentioning a new entry from Asus into this space called the Tinkerboard.  Now I’m not going to go into an in-depth review since you can find those all over the Internet.  However, I do want to mention a few things I’ve found and done that are very helpful.  I like the board since it’s supports things like OpenCL and pound for pound is more powerful than the Pi 3.  The two gig of RAM vs one with the Pi 3 makes it useful for more advanced processing.

One thing to keep in mind is that the board is still “new” and has a growing community.  As such there are going to be some pains, such as not having as big a community as the Pi ecosystem.  But things do appear to be getting better, and so far it’s proven to be more capable and, in some cases, more stable than my Pi 3.

So without much fanfare, here are my list of tips for using the Tinkerboard.  You can find a lot more information online.

  1. Community – The Tinkerboard has a growing community of developers.  My favorite forums are at the site run by Currys PC World.  They’re active and you can find a lot of valuable information there.
  2. Package Management – Never, EVER, run apt-get dist-upgrade.  Since it’s Debian, the usual apt-get update and apt-get upgrade are available.  However, running dist-upgrade can cause you to loose hardware acceleration.
  3. OpenCL – One nice think about the Tinkerboard is that the Mali GPU has support for hardware-accelerated OpenCL.  TinkerOS an incorrectly named directory in /etc/OpenCL which causes apps to not work by default.  The quick fix is to change to /etc/OpenCL and run ln -s venders vendors.  After doing this, tools like clinfo should properly pick up support.
  4. Driver updates – Asus is active on Github.  At their rk-rootfs-build site there you can find updated drivers as they’re released.  I recommend checking this site from time to time and downloading updated packages are they are released.
  5. Case – The Tinkerboard is the same size and mostly the same form-factor as the Raspberry Pi 3.  I highly recommend you pick up a case with a built-in cooling fan since the board can get warm, even with the included heat sinks attached.
  6. You can follow this link and install Tensorflow for the Pi on the Tinkerboard.  It’s currently not up-to-date, but much less annoying than building Tensorflow from scratch.
  7. SD Card – You would do well to follow my previous post about how to zero out a SD card before you format and install TinkerOS to it.  This will save you a lot of time and pain.  I will note that so far, my Tinkerboard holds up under heavy IO better than my Pi 3 does.   I can do thinks like make -j 5 and it doesn’t lock up or corrupt the card.

I’ll have more to say about this board later.

Another Fixed GNIS Dataset

When I went to import the latest GNIS dataset into my local PostGIS database, I found that it contains the same issues I’ve been reporting for the past few years.   You can find my fixed version of the dataset here.

As a disclaimer, while I used to work there, I no longer have any association with the US Geological Survey or the Board of Geographic Names.

For those interested, here is the list of problems I found and fixed:

ID 45605: Duplicate entry for Parker Canyon, AZ. The coordinates are in Sonora, Mexico.
ID 45606: Duplicate entry for San Antonio Canyon, AZ. The coordinates are in Sonora, Mexico.
ID 45608: Duplicate entry for Silver Creek, AZ. The coordinates are in Sonora, Mexico.
ID 45610: Duplicate entry for Sycamore Canyon, AZ. The coordinates are in Sonora, Mexico.
ID 567773: Duplicate entry for Hovey Hill, ME. The coordinates are in New Brunswick, Canada.
ID 581558: Duplicate entry for Saint John River, ME. The coordinates are in New Brunswick, Canada.
ID 768593: Duplicate entry for Bear Gulch, MT.  The coordinates are in Alberta, Canada.
ID 774267: Duplicate entry for Miners Coulee, MT.  The coordinates are in Alberta, Canada.
ID 774784: Duplicate entry for North Fork Milk River, MT.  The coordinates are in Alberta, Canada.
ID 775339: Duplicate entry for Police Creek, MT.  The coordinates are in Alberta, Canada.
ID 776125: Duplicate entry for Saint Mary River, MT.  The coordinates are in Alberta, Canada.
ID 778142: Duplicate entry for Waterton River, MT.  The coordinates are in Alberta, Canada.
ID 778545: Duplicate entry for Willow Creek, MT.  The coordinates are in Alberta, Canada.
ID 798995: Duplicate entry for Lee Creek, MT.  The coordinates are in Alberta, Canada.
ID 790166: Duplicate entry for Screw Creek, MT.  The coordinates are in British Columbia, Canada.
ID 793276: Duplicate entry for Wigwam River, MT.  The coordinates are in British Columbia, Canada.
ID 1504446: Duplicate entry for Depot Creek, WA.  The coordinates are in British Columbia, Canada.
ID 1515954: Duplicate entry for Arnold Slough, WA.  The coordinates are in British Columbia, Canada.
ID 1515973: Duplicate entry for Ashnola River, WA.  The coordinates are in British Columbia, Canada.
ID 1516047: Duplicate entry for Baker Creek, WA.  The coordinates are in British Columbia, Canada.
ID 1517465: Duplicate entry for Castle Creek, WA.  The coordinates are in British Columbia, Canada.
ID 1517496: Duplicate entry for Cathedral Fork, WA.  The coordinates are in British Columbia, Canada.
ID 1517707: Duplicate entry for Chilliwack River, WA.  The coordinates are in British Columbia, Canada.
ID 1517762: Duplicate entry for Chuchuwanteen Creek, WA.  The coordinates are in British Columbia, Canada.
ID 1519414: Duplicate entry for Ewart Creek, WA. The coordinates are in British Columbia, Canada.
ID 1520446: Duplicate entry for Haig Creek, WA. The coordinates are in British Columbia, Canada.
ID 1520654: Duplicate entry for Heather Creek, WA. The coordinates are in British Columbia, Canada.
ID 1521214: Duplicate entry for International Creek, WA. The coordinates are in British Columbia, Canada.
ID 1523541: Duplicate entry for Myers Creek, WA. The coordinates are in British Columbia, Canada.
ID 1523731: Duplicate entry for North Creek, WA. The coordinates are in British Columbia, Canada.
ID 1524131: Duplicate entry for Pack Creek, WA. The coordinates are in British Columbia, Canada.
ID 1524235: Duplicate entry for Pass Creek, WA. The coordinates are in British Columbia, Canada.
ID 1524303: Duplicate entry for Peeve Creek, WA. The coordinates are in British Columbia, Canada.
ID 1525297: Duplicate entry for Russian Creek, WA. The coordinates are in British Columbia, Canada.
ID 1525320: Duplicate entry for Saar Creek, WA. The coordinates are in British Columbia, Canada.
ID 1527272: Duplicate entry for Togo Creek, WA. The coordinates are in British Columbia, Canada.
ID 1529904: Duplicate entry for McCoy Creek, WA. The coordinates are in British Columbia, Canada.
ID 1529905: Duplicate entry for Liumchen Creek, WA. The coordinates are in British Columbia, Canada.
ID 942345: Duplicate entry for Allen Brook, NY. The coordinates are in Quebec, Canada.
ID 949668: Duplicate entry for English River, NY. The coordinates are in Quebec, Canada.
ID 959094: Duplicate entry for Oak Creek, NY. The coordinates are in Quebec, Canada.
ID 967898: Duplicate entry for Trout River, NY. The coordinates are in Quebec, Canada.
ID 975764: Duplicate entry for Richelieu River, VT. The coordinates are in Quebec, Canada.
ID 1458184: Duplicate entry for Leavit Brook, VT. The coordinates are in Quebec, Canada.
ID 1458967: Duplicate entry for Pike River, VT. The coordinates are in Quebec, Canada.
ID 1028583: Duplicate entry for Cypress Creek, ND. The coordinates are in Manitoba, Canada.
ID 1035871: Duplicate entry for Mowbray Creek, ND. The coordinates are in Manitoba, Canada.
ID 1035887: Duplicate entry for Gimby Creek, ND. The coordinates are in Manitoba, Canada.
ID 1035890: Duplicate entry for Red River of the North, ND. The coordinates are in Manitoba, Canada.
ID 1035895: Duplicate entry for Wakopa Creek, ND. The coordinates are in Manitoba, Canada.
ID 1930555: Duplicate entry for Red River of the North, ND. The coordinates are in Manitoba, Canada.
ID 1035882: Duplicate entry for East Branch Short Creek, ND. The coordinates are in Saskatchewan, Canada.
ID 1782010: Duplicate entry for Manitoulin Basin, MI. The coordinates are in Ontario, Canada

Creating a NAS using the Raspberry Pi 3 Part 3 (finally)

So I have been meaning to finish up this series for a while now, but other things got in the way (which hopefully I can post on here soon).  In the mean time, there are numerous tutorials on-line now about how to set a Pi up as a home file server, so I think I will defer to those instead of wasting more bits on the Internet.  However, I would like to point out some things I have done that has resulted in my Pi setup being nice and stable.

This biggest thing to do when using the SD card as the root file system for the Pi is to minimize the number of writes to it.  This will help keep it lasting longer and avoid any file system corruption.  One thing you can do is modify your /etc/fstab and use the noatime family of attributes.  The default of most Pi distributions is ext3/4, so this should work for you.  First find your entry in the /etc/fstab for your /.  In mine below, you can see it’s /dev/mmcblk0p2:

proc /proc proc defaults 0 0
/dev/mmcblk0p2 / ext4 defaults 0 1
/dev/mmcblk0p1 /boot/ vfat defaults 0 2
/dev/md0 /mnt/filestore xfs defaults,nofail 0 2

Change line 2 so that it reads like this:

/dev/mmcblk0p2 / ext4 defaults,noatime,nodiratime 0

This will stop the file system from modifying itself each time a directory or file is accessed.

As you can see from my fstab, I also have my RAID partition on the enclosure set to xfs and I use the nofail attribute.  This is very important since your enclosure may not be fully spun up and ready by the time your Pi tries to mount it.  If it’s not there, the Pi will hang (forever in my case since it will cause the kernel to panic).

I also run mariadb and postgresql with postgis on the Pi3, however I have them set to not autostart by running:

systemctl disable mysqld
systemctl disable postgresql

I could leave them running since I’ve lowered their memory requirements, but choose to only have things running on the Pi 3 whenever I need it to make sure I don’t run out of memory.

I put their respective data directories on the NAS and then made a soft link under /var by running;

ln -s /mnt/filestore/data/mysql /var/lib/mysql
ln -s /mnt/filestore/data/postgresql /var/lib/postgresql

You could edit their config files to change the location, but for me I have found it is easier to simply use soft links.  Plus, since the servers are not set to start a boot, I do not have to worry about any errors every time the Pi restarts.

I also run recoll on the Pi as I have collected several hundred gigabytes of papers and ebooks over the years.  Recoll is a nice utility that provides a semantic search ability.  By default, recoll and run your file system and system itself into the ground if you let it.  I made a few tweaks so that would play nice whenever I run it periodically on the Pi.  The first thing I did was move the ~/.recoll directory to the NAS and create a soft link by running

ln -s /mnt/filestore/data recoll .recoll

Again, the goal is to reduce the number of file system access to the SD card itself.  Secondly, I created the .recoll/recoll.conf file with the following contents:

topdirs = /mnt/filestore/data/Documents /mnt/filestore/data/ebooks /mnt/filestore/data/Programming
filtermaxseconds 60
thrQSizes = -1 -1 -1

The filtermaxseconds parameter tells recoll to stop indexing a file if the filter runs for a whole minute.  The thrQSizes option has recoll use a single thread.  While this makes it slower, it makes things run much better on the Pi while still allowing other services to run.

If you want to run other services, keep in mind that if they do a lot of I/O, you should move them to your external drive and use a soft link to redirect like I did above.  Doing so will help to greatly extend the life of your SD card and keep you from having to reimage it.

Creating a NAS Using a Raspberry Pi 3 Part 2

In the last article, I went over my decisions about the hardware I wanted to use to build a cheap home NAS. Here I will go over the software and configuration to get everything working.

Once all the parts came in, it was time to get going and configure everything. First, though, I would like to talk about SD cards, and why I feel they are the one major flaw with the Raspberry Pi series.

Conceptually, SD cards are a great thing. They come in different sizes and can store multiple gigabytes of data on them. They are used in everything from cell phones to digital cameras to computers. You are probably using one daily in a device without even knowing it.

You might think there are hundreds of companies making them, and you would be wrong. See, as with many things, a few companies actually make the physical cards and then a lot of other companies will buy and re-brand them. The companies that slap their logo on these cards do not care whether they buy quality card stock as long as it is cheap. So what we end up with is a situation where you can by two of the same “type” of SD card and physically they could be quite different from each other.

You also may not realize that SD cards are just as capable of developing bad sectors as your physical hard drive is. Some cards have a smart enough controller built-in that will automatically remap bad sectors to other good spaces on the card like SMART does with hard drives. Many others do not and have a “dumb” controller that does the bare minimum to make the device work.

The reality with SD cards is that expecting them to “just work” is about as safe as playing Russian roulette with all six cylinders loaded. Just as with hard drives, your SD WILL fail. Unlike hard drives, your SD may or may not be able to take care of problems on its own. And with the wild west of the cards, well, your best bet is to never trust that data on them is safe.

At my previous job I spent a lot of time dealing with SD cards and learning how to deal with their various issues. Often we would have random problems come up that could not be explained, only to find out that the SD card had developed issues that needed to be corrected to return things to normal. What I found out after looking at the low level portions of the card and a lot of reading has made me rethink trusting these devices for long term storage and use. The Pi will be running an operating system off of the SD, so you can expect a lot of reads and writes being done to it. This will speed up the development of bad sectors on the device and reduce its operating lifetime.

There are a few things you can do to help things. Before you even start to install software for your Pi, I highly recommend that you do the check the physical surface of the SD before you use it, even if it is new out of the package. I’m writing this from a Linux perspective, but the same information applies to Windows or even Mac OS as well. As usual, your mileage may vary. Doing this could cause you to lose data and make dogs and cats live together in a dystopian future. This will take some extra time, but I firmly believe it is worth it.

Plug the SD into your computer and identify what device it is assigned. I will leave it up to you to web search this for bonus points. First thing I recommend is using the dd command to write random data to the entire device. If the SD card has an intelligent controller, this will help it to determine if there are any bad sectors and remap them before you put Linux on it for the Pi. Even without an intelligent controller, initially writing to it can help find spots that may be bad or trigger marginal sectors to go bad. Run a command similar to:

dd if=/dev/random of=/your/sd/device bs=8M

This command will write a random value to each byte on your SD card. Once this is done, the next thing I recommend is format the SD and check for bad sectors while formatting. This can be done with something along the lines of:

mkfs.ext4 -cc /your/sd/device

This command will put a file system on the SD and do a read/write test while formatting it. Along with the dd command, this should bang on the physical surface of the card enough to find any initial bad sectors that could already be there.

That is it for this installment. Now that my soapbox is over, next time we will talk installing software and configuring the Pi to be a NAS.

Creating a NAS Using a Raspberry Pi 3 Part 1

Find yourself needing a lot of storage on your network and do not want to have something that requires a lot of attention? You can use a Raspberry Pi 3 and a hard drive enclosure to make a home or small office NAS to store files and keep them available.

Recently I found myself wanting to upgrade my home network attached storage (NAS). It was basically an old laptop connected to a USB enclosure. It was stable, but had a few flaws. The first was that I had to periodically clean out the laptop since it seemed to be a magnet for dust. The second was that the hard drive was a single drive that I kept backed up, but it did not provide availability in case that drive should fail. Plus, the laptop drew more power than it needed to since it spent a lot of time just sitting around.

What I wanted was something that used a small amount of power and was expandable. I wanted to be able to easily add more drives in as our family storage needs grew. My ideal solution would not need much fuss or maintenance. Most importantly, since I am cheap, the hardware solution needed to be low cost.

I had been waiting to pick up a Raspberry Pi 3 until I had a project that actually needed one. If you search Google, you will find a lot of people using it for a file server. Owners also complain because not only does it just come with USB 2.0 ports, but the built-in Ethernet also shares bandwidth with the USB devices. However, I was not looking for something high-bandwidth as all the video I transfer over the network is already compressed. My home network is limited to 100 megabit Ethernet, so at best I only get around eight to nine megabytes a second transfer speed anyway. I ordered the Vilros Raspberry Pi 3 Basic Starter Kit off Amazon and picked up a 64 gigabyte class-10 SD card for the root file system.

Once I settled on the Pi 3, I needed an external USB enclosure. I ended up picking the Mediasonic ProBox HF2-SU3S2 four-bay enclosure. It has a standard-sized cooling fan in the back and controls on the front for things like setting the fan speed and so on. I had two four gigabyte drives ready for it and would still have room to expand.

While waiting for everything to arrive, I then had to decide the how of setting the NAS up. There a lot of options out there, ranging from FreeNAS to rolling your own Linux distribution. You will see a huge amount of discussion of what types of file systems to use. Here it seems to be split into two camps: the “ZFS for everything” camp, and everything else (XFS, EXT4, and so on). ZFS is a great file system and I have used it for other things, but for a home NAS (especially one running off a Pi), it can be a bit of overkill. This is especially true since many of ZFS’s best features require a lot of RAM.

What I decided on is good old Linux software RAID 1 and the XFS file system. I have had a lot of success with software RAID over the years, and for my purposes it has been more flexible than a hardware RAID system. Linux software RAID can do things like convert in-place from a RAID-1 setup to RAID-5 with no data loss. This way, if I needed to expand past the four gigabyte RAID-1 system, I could add another drive and convert it to RAID-5. Linux software RAID-5 will let you grow it by adding hard drives, so in the end I could have a twelve gigabyte RAID-5 system if I needed one. I already back up the data with integrity checks, so instead of ZFS, XFS would satisfy all of my needs.

Distribution-wise, I decided it would be either Raspbian or Ubuntu MATE. Both are Debian-based, and both are solid operating systems for the Pi. Raspbian is the official distribution from the Raspberry Pi Foundation, and MATE is a distribution for the Pi built by Martin Wimpress and Rohith Madhavan. As I had never used a Pi before, I had no idea how either would work on the Pi 3. I used to use MATE for my desktop so I was at least familiar with it and knew it did not need a lot of resources to run.

In Part 2 I will go over setting up the Pi 3 to serve out data. As a spoiler, I will also go into why I chose Ubuntu for my Pi 3 in the end over Raspbian.


Filtering Data from a Geospatial Database using QGIS

If you have spatial databases such as the ones I set up in my previous blog posts about GNIS and PostGIS, you will likely want to add a few things to them to make them more useful. GNIS and Geonames contain point types of all different classes, from airports to populated places. What if you were only interested in one type of point, such as airports? By default, if you load GNIS data into QGIS, it will display all of the points in your view and look cluttered as the screen shot below demonstrates.

All GNIS Points Over an Area

All GNIS Points Over an Area








The good news is that you can easily specify what you only want QGIS to show you.  There are a couple of ways that you can filter data out in a layer with QGIS: the Set Filter button and creating a database view. The Set Filter button lets you create a SQL filter by clicking on the field you want to filter with, the relational operator, and what you want to compare with. A database view lets you pre-define your filter and presents it as another table. Whichever one you use is up to you, but there is at least one thing you must do to speed up both methods.

The Add Filter Method

Assuming you followed my previous posts about setting up GNIS, we will use that for this example. First you need to create an index on the feature_class column of GNIS. This will make the query that we will use as an example run much faster. To do this, run the following commands:

psql -d USGS
USGS=# create index gnis_feature_class_idx on gnis(feature_class);

Once this is done, you will have a new index called gnis_feature_class_idx. This allows PostgreSQL find the matching feature classes from the data more quickly by consulting the index instead of manually searching each row in the database.

Now that this is done, we will next move on to our first example, the Set Filter button method. As a refresher, here are the feature classes in GNIS:

USGS=# select distinct(feature_class), count(*) from gnis group by feature_class order by feature_class;
feature_class   | count
Airport         | 23202
Arch            | 720
Area            | 2557
Arroyo          | 466
Bar             | 5870
Basin           | 4304
Bay             | 14094
Beach           | 2409
Bench           | 724
Bend            | 2797
Bridge          | 7356
Building        | 160291
Canal           | 21559
Cape            | 16417
Cemetery        | 145544
Census          | 11629
Channel         | 4014
Church          | 231967
Civil           | 64237
Cliff           | 4479
Crater          | 246
Crossing        | 13167
Dam             | 56931
Falls           | 2499
Flat            | 10559
Forest          | 1314
Gap             | 8246
Glacier         | 1021
Gut             | 3541
Harbor          | 1271
Hospital        | 15864
Island          | 20540
Isthmus         | 28
Lake            | 69403
Lava            | 168
Levee           | 546
Locale          | 162518
Military        | 2860
Mine            | 36133
Oilfield        | 4863
Park            | 69501
Pillar          | 2092
Plain           | 289
Populated Place | 201065
Post Office     | 66942
Range           | 2480
Rapids          | 1062
Reserve         | 1276
Reservoir       | 74683
Ridge           | 15127
School          | 216473
Sea             | 28
Slope           | 373
Spring          | 38655
Stream          | 231462
Summit          | 70614
Swamp           | 7608
Tower           | 16800
Trail           | 11047
Tunnel          | 750
Unknown         | 186
Valley          | 70239
Well            | 38797
Woods           | 684
(64 rows)

Both of the examples here will work with the feature class of Airports. These examples also assume you already have some data set up as I previously demonstrated on this blog.

For the Set Filter method, first click on the Add PostGIS Layer button in QGIS. Select the USGS database and select the gnis table. Once you have done this, click on the Set Filter button at the bottom right side of the Add Layer dialog.


Creating a Filter in QGIS

Creating a Filter in QGIS








As you can see above, you are presented with a list of Fields on the left side, operator buttons in the middle, and Values on the right side. Click on the Feature Class field to select it and then click the All button under the values window to the right. Since we created an index on the Feature Class field, this should quickly show you all the unique values that exist in the database for that field. Now double click Feature Class to add it into the Provider specific filter expression in the text box at the bottom of the dialog. Then click the = button in the Operators group. Now double click Airport from the Values box to add it. Your filter expression should now look like this:

"feature_class" = 'Airport'

If you click the Test button, QGIS will perform a query and display the number of rows that match your query. You can use this to double check that you did not make any errors during entry. In our case, the query should return around 23,000+ rows depending on the version of GNIS you are using. Click the OK button to go back to the Layers dialog and then the Add button to add it to your project.  With the filter in place, your screen should look less cluttered as it is only showing airports from GNIS

Only Airports Displayed in GNIS

Only Airports Displayed in GNIS








You can use this method to filter out data on any type of field in a geospatial database.  I recommend, though, that you first create an index on that column to speed up the operation.  Otherwise, you may have to wait a while every time you try to load your filtered data.

Creating a Database View

The second method to filter data is to create a database view. Basically all database types can create a view. For the non-database savvy, a view can be thought of as a virtual table that is defined by a database query. This means that whenever you access the view, the data that is returned is generated by a query. For example, if you wanted a table of only airports in GNIS, you could make a view that pretends to be another table but does not take up as much space as a real table would.

For this example, we will again use Airports. Once you understand this, you can then create views for other classes by replacing the feature class name. However, when working with tools such as QGIS, there is a caveat that you need to first know about. If you are savvy with databases, your might create the view with the following command:

psql -d USGS
USGS=# create view view_airports as select * from gnis where feature_class = 'Airport';

When you then go to load this into QGIS, you will indeed see the view as a layer, but there will be a problem.

How a View Appears in QGIS

How a View Appears in QGIS








As you can see, QGIS will not let you just click on the view to add it. If you hover over the error triangle, you will see it displays a message of Select columns in the ‘Feature Id’ column that uniquely identify features of this layer. If you scroll to the right, you will see that QGIS will let you select a column in the view that is a unique identifier (feature_id in the case of GNIS).

Why does QGIS not automatically know which column to use? If you are not well versed in how QGIS and databases work, tables in a database typically need a unique identifier for each entry so that it can be properly found. With recent versions of PostgreSQL and PostGIS, the view does not have a unique key presented with the view. If QGIS tried to automatically deduce what field to use as the unique key, it would take a lot of processing power and would mean that QGIS would temporarily “hang” whenever you tried to access a database. Instead, QGIS gives you an option to tell it what field to use as the unique identifier for each row.

If you go ahead and select the feature_id field in the Add Layer dialog, you will then be able to select the layer and click Add to load it into QGIS.

Select Feature ID Option in QGIS

Select Feature ID Option in QGIS








So the question you might have is “Which method is better?” The correct answer is “Whichever method makes more sense to you.” Some people may be OK with setting a filter when they load in data. Others may prefer to have views show up in the Layers dialog to remind them what all is available. A PostgreSQL materialized view would likely be the fastest method as it creates a cache of the data, but that is a bit beyond the scope of this post 🙂

Have fun and happy GISing with all Open Source software!