Can't execute a distinct projection query

2019-02-28 11:11发布

I have a simple little "Observation" class:

from google.appengine.ext import ndb

class Observation(ndb.Model):
    remote_id = ndb.StringProperty()
    dimension_id = ndb.IntegerProperty()
    metric = ndb.StringProperty()
    timestamp_observed = ndb.StringProperty()
    timestamp_received = ndb.DateTimeProperty(auto_now_add=True)

    @classmethod
    def query_book(cls):
        return cls.query()

I can run projection queries against the Datastore to return only certain columns. E.g:

observations = Observation.query().fetch(projection=[Observation.dimension_id])

This works nicely, but I only want unique results. The documentation makes this sound easy:

# Functionally equivalent
Article.query(projection=[Article.author], group_by=[Article.author])
Article.query(projection=[Article.author], distinct=True)

But when I do this:

observations = Observation.query().fetch(projection=[Observation.dimension_id], group_by=[Observation.dimension_id])
observations = Observation.query().fetch(projection=[Observation.dimension_id], distinct=True)

I get errors for both variants.

TypeError: Unknown configuration option ('group_by')
TypeError: Unknown configuration option ('distinct')

This happens on localhost and in the prod environment too. What am I missing?

1条回答
放荡不羁爱自由
2楼-- · 2019-02-28 11:46

Silly me - all of these params need to sit within the query() function, not within fetch(). The projection elements actually works in fetch(), but you need to move both the projection and distinct arguments into query() to get it to work.

From Grouping:

Projection queries can use the distinct keyword to ensure that only completely unique results will be returned in a result set. This will only return the first result for entities which have the same values for the properties that are being projected.

Article.query(projection=[Article.author], group_by=[Article.author])
Article.query(projection=[Article.author], distinct=True)

Both queries are equivalent and will produce each author's name only once.

Hope this helps anyone else with a similar problem :)

查看更多
登录 后发表回答