Getting Distinct Result From Google App Engine GQL Query

One of the big limitations of Google App Engine is query syntax. Like SQL we don’t have all freedom in GQL. As an example, we cannot get DISTINCT result like following SQL query…

“Select DISTINCT name from users”

Let’s say we want to select distinct city from our datastore in Google App Engine application
How can we do it ?
One of the solutions could be using set() function
Example:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])


This is possible in Python and GAE….but remember first you have to create an array which required a loop to run and then use the set() function. Certainly, it can’t be a good solution. 

Here is a better way, let’s create a custom function that will return unique result or distinct result. 

  def unique_result(array):
    unique_results = []
    for obj in array:
        if obj.city not in unique_results:
            unique_results.append(obj.city)
    return unique_results


This function will return distinct result from an array result. 

Example : (how to call it…)

result = db.GqlQuery(“SELECT * FROM table_name order by date DESC limit x”)
distinct_result = unique_result(result)

Well, so far i think this is the better way to get distinct data in GAE GQL query. Let me know if you have any better way for it. I will update it here :)

This entry was posted in Google App Engine, GQL, Python and tagged . Bookmark the permalink.
  • http://www.mbt-outlet-store.com mbt outlet

    Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum!
    http://www.sin-game.com

  • sheshakiran

    when we use the word DISTINCT its showing error can any body mail be the solution and my email-id is kiran.shesha1@gmail.com

  • http://kovshenin.com kovshenin

    Thanks for sharing, looks great. There are times though when you’d like to retrieve a certain number of distinct values, since the entity can have thousands or tens of thousands of entries and you only need 20. A simple solution would be check for len(unique_results) >= 20 and break the loop if it is.

  • Betty Cflores

    como crear un bd con relaciones pero aunque entiendo que con google app engine no es asi.. alquien puede darme un ejemplo :D

  • http://patelatharva.myopenid.com/ Atharva Patel

    Complexity n(n+1)/2 = O(n2)

  • David M.

    Thanks, it helped me a lot!