Filtering a GAE Query
When attempting to filter a GAE query, a common issue arises when the filter appears ineffective. To address this problem, it's essential to understand how the Query.Filter() method operates.
The Query.Filter() method returns a derivative query that includes the specified filter. However, it's crucial to assign the return value to a new variable to preserve the filter:
q = datastore.NewQuery("employee").Filter("Name =", "Andrew W")
Alternatively, the new filtering can be achieved in a single line:
q := datastore.NewQuery("employee").Filter("Name =", "Andrew W")
Without this step, the executed query will have no filters, resulting in the retrieval of all saved "employee" entities. Consequently, "Joe Citizen" may be the first entity printed.
Additionally, eventual consistency must be considered. After performing a Put() operation, the subsequent query may not immediately see the expected results due to the use of the development SDK. To alleviate this issue, a time.Sleep() can be introduced before executing the query:
time.Sleep(time.Second) q := datastore.NewQuery("employee").Filter("Name =", "Andrew W")
In production, strong consistency can be simulated by creating a context with the following option:
c, err := aetest.NewContext(&aetest.Options{StronglyConsistentDatastore: true})
However, it's important to note that ancestor keys should be utilized for strongly consistent results in production.
The above is the detailed content of Why Aren't My Google App Engine Datastore Queries Filtering Correctly?. For more information, please follow other related articles on the PHP Chinese website!