ArcGIS JavaScript API Hacks: Query Return Distinct

EDITAs of version 3.11, ESRI has updated the ArcGIS JavaScript API so that this hack is no longer necessary. The returnDistinctValues parameter works just fine. Maybe I should publish a few more of these so that other issues I have with the API can get fixed :).


One of the handy things about ArcGIS Server is its ability to make SQL selections approachable. In ArcGIS Server 10.1 SP 1, ESRI introduced the returnDistinctValues parameter. It lets your queries return distinct values when you’re requesting specific fields. Unfortunately, the ArcGIS JavaScript API doesn’t support the returnDistinctValues parameter yet. Let’s talk about how to add it into your application, anyway.

Why is this useful? Let’s say you have a map of cat sightings, and you want a unique list of cat breeds. One way you could do it is to query for the entire list, then sort and cut out all the repeating values. That would look something like this:

The problem here two-fold. First, if the list is long, the array sorting and splicing will take a significant amount of time, especially on mobile browsers. Secondly, ArcGIS Server has a limit on the number of results it returns (default 1000-2000). If you have 10,000+ cat sightings, you’re not going to get everything on the list. You may miss the sighting of a Sphynx, a Ukrainian Lekvoy, or even a Grumpy.

Since the ArcGIS JavaScript API doesn’t support returnDistinctValues, how do we get the unique values without having to slosh through all the repeats? There’s a couple ways. If you’re just using a QueryTask to get the unique values, the shortcut way is to append the returnDistinctValue parameter to the url of the QueryTask, like so:

Strangely enough, this works as long as you’re just querying using where clauses and text. Executing a query on at QueryTask breaks if you try to do the following.

  • Get a count (queryForCount())
  • Query for ObjectIDs
  • Send a Query with a list of ObjectIDs

There may be more, but that’s as far as I checked. Another method, as mentioned here, uses the esriRequest.setRequestPreCallback() method to dig into requests (including queries), and add the returnDistinctValue = true parameter to the request. Here is a more robust way to add the value to any query request. Warning: this does contain regex, which may warp your brain if you let it.

I hope this helps somebody out there.

2 thoughts on “ArcGIS JavaScript API Hacks: Query Return Distinct

  1. Hey Ken,

    As of version 3.11 ESRI did add returnDistinctValues to the Query class. However, prior to the inclusion I was taking the “add parameter to the url” approach. It’s much nicer having it in the API.

Comments are closed.