英文:
How to filter a GAE query?
问题
我正在尝试保存两条记录,并获取第二条记录。问题在于过滤器似乎不起作用。尽管我按照名称("Andrew W")进行过滤,但我始终得到的是"Joe Citizen"。计数器也显示为2条记录,而实际上应该只有一条。这让我很疯狂。请参考下面的完整代码。
package main
import (
"fmt"
"time"
"net/http"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
)
type Employee struct {
Name string
Role string
HireDate time.Time
Account string
}
func init(){
http.HandleFunc("/", handle)
}
func handle(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
e1 := Employee{
Name: "Joe Citizen",
Role: "Manager",
HireDate: time.Now(),
}
_, err := datastore.Put(c, datastore.NewKey(c, "employee", "", 0, nil), &e1)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
panic(err)
return
}
e1.Name = "Andrew W"
_, err = datastore.Put(c, datastore.NewKey(c, "employee", "", 0, nil), &e1)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
panic(err)
return
}
var e2 Employee
q := datastore.NewQuery("employee")
q.Filter("Name =", "Andrew W")
cnt, err := q.Count(c)
if err !=nil{
http.Error(w, err.Error(), http.StatusInternalServerError)
panic(err)
return
}
for t := q.Run(c); ; {
if _, err := t.Next(&e2); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
panic(err)
return
}
break
}
fmt.Fprintf(w, "counter %v e2 %q", cnt, e2)
}
结果打印为 "counter 2 e2 {"Joe Citizen" "Manager" "2015-03-24 09:08:58.363929 +0000 UTC" ""}"。
英文:
I'm trying to save two records and then get the 2nd one. The issue is that the filter doesn't seem to work. Although I filter by Name ("Andrew W") I always get "Joe Citizen". The counter also indicates 2 records when it should be just one. This drives me crazy. See the full code below.
The result prints counter 2 e2 {"Joe Citizen" "Manager" "2015-03-24 09:08:58.363929 +0000 UTC" ""}
package main
import (
"fmt"
"time"
"net/http"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
)
type Employee struct {
Name string
Role string
HireDate time.Time
Account string
}
func init(){
http.HandleFunc("/", handle)
}
func handle(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
e1 := Employee{
Name: "Joe Citizen",
Role: "Manager",
HireDate: time.Now(),
}
_, err := datastore.Put(c, datastore.NewKey(c, "employee", "", 0, nil), &e1)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
panic(err)
return
}
e1.Name = "Andrew W"
_, err = datastore.Put(c, datastore.NewKey(c, "employee", "", 0, nil), &e1)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
panic(err)
return
}
var e2 Employee
q := datastore.NewQuery("employee")
q.Filter("Name =", "Andrew W")
cnt, err := q.Count(c)
if err !=nil{
http.Error(w, err.Error(), http.StatusInternalServerError)
panic(err)
return
}
for t := q.Run(c); ; {
if _, err := t.Next(&e2); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
panic(err)
return
}
break
}
fmt.Fprintf(w, "counter %v e2 %q", cnt, e2)
}
答案1
得分: 5
第一个问题是这样的:
q := datastore.NewQuery("employee")
q.Filter("Name =", "Andrew W")
Query.Filter()
返回一个包含指定过滤器的派生查询。你需要存储返回值并在后续使用它:
q := datastore.NewQuery("employee")
q = q.Filter("Name =", "Andrew W")
或者只用一行代码:
q := datastore.NewQuery("employee").Filter("Name =", "Andrew W")
注意:如果没有这样做,你执行的查询将没有过滤器,因此会返回之前保存的所有 "employee"
类型的实体,其中 "Joe Citizen"
可能是你看到的第一个打印出来的实体。
在第一次运行时,你很可能会看到 0 个结果。请注意,由于你没有使用祖先查询,最终一致性将适用。开发 SDK 模拟了具有最终一致性的高复制数据存储,并且因此在 Put()
操作后的查询中不会看到结果。
如果在继续查询之前加上一个小的 time.Sleep()
,你将看到预期的结果:
time.Sleep(time.Second)
var e2 Employee
q := datastore.NewQuery("employee").Filter("Name=", "Andrew W")
// 其余的代码...
还要注意,在 SDK 中运行代码时,你可以通过这样创建上下文来模拟强一致性:
c, err := aetest.NewContext(&aetest.Options{StronglyConsistentDatastore: true})
但当然,这仅用于测试目的,你不能在生产环境中这样做。
如果你想要强一致性的结果,在创建键时指定一个祖先键,并使用祖先查询。只有当你想要强一致性的结果时,才需要祖先键。如果你对结果出现几秒钟的延迟没有问题,那就不需要。还要注意,祖先键不必是现有实体的键,这只是语义上的。你可以创建任何虚构的键。使用相同的(虚构的)键对多个实体进行操作将使它们进入同一个实体组,对该组的祖先查询将具有强一致性。
通常,祖先键是一个现有键,通常是从当前用户或帐户派生的,因为它可以轻松创建/计算,并且它保存/存储一些附加信息,但如上所述,这不是必需的。
英文:
The (first) problem is this:
q := datastore.NewQuery("employee")
q.Filter("Name =", "Andrew W")
Query.Filter()
returns a derivative query with the filter you specified included. You have to store the return value and use it ongoing:
q := datastore.NewQuery("employee")
q = q.Filter("Name =", "Andrew W")
Or just one line:
q := datastore.NewQuery("employee").Filter("Name =", "Andrew W")
Note: Without this the query you execute would have no filters and therefore would return all previously saved entities of the kind "employee"
, where "Joe Citizen"
might be the first one which you see printed.
For the first run you will most likely see 0 results. Note that since you don't use Ancestor queries, eventual consistency applies. The development SDK simulates the High replication datastore with its eventual consistency, and therefore the query following the Put()
operations will not see the results.
If you put a small time.Sleep()
before proceeding with the query, you will see the results you expect:
time.Sleep(time.Second)
var e2 Employee
q := datastore.NewQuery("employee").Filter("Name=", "Andrew W")
// Rest of your code...
Also note that running your code in the SDK you can simulate strong consistency by creating your context like this:
c, err := aetest.NewContext(&aetest.Options{StronglyConsistentDatastore: true})
But of course this is for testing purposes only, you can't do this in production.
If you want strongly consistent results, specify an ancestor key when creating the key, and use ancestor queries. An ancestor key is only required if you want strongly consistent results. If you're fine with a few seconds delay for the results to show up, you don't have to. Also note that the ancestor key does not have to be the key of an existing entity, it's just semantics. You can create any fictional key. Using the same (fictional) key to multiple entities will put them into the same entity group and ancestor queries on this group will be strongly consistent.
Often the ancestor key is an existing key, usually derived from the current user or account, because that can be created/computed easily and it holds/stores some additional information, but as noted above, it doesn't have to be.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论