英文:
How to use r.Do and r.Branch in gorethink?
问题
我正在寻找关于gorethink中r.Do()和r.Branch()函数的清晰示例。
英文:
I'm looking for clear example of r.Do() and r.Branch() functions in gorethink.
答案1
得分: 3
Go RethinkDB驱动程序的作者在Github上非常活跃,如果在那里提问,你可能会得到更快的答案。
这是一个Do
的示例。
res, _ := r.DB("test").Table("table").Get("ID").Do(func(issue r.Term) r.Term {
return issue.Merge(map[string]string{
"new_field": "new_value",
})
}).Run(session)
var b []interface{}
a.All(&b)
fmt.Println(b)
我认为最重要的是确保我们声明了正确的Term
类型。我将RethinkDB驱动程序导入为r
,所以我使用了r.Term
。然后在Do
函数内部,你可以使用Term中的任何命令:https://godoc.org/github.com/dancannon/gorethink#Term
同时使用Do
和Branch
的示例:
r.DB("test").Table("issues").Insert(map[string]interface{}{
"id": 1111,
}).Do(func(result r.Term) r.Term {
return r.Branch(result.Field("inserted").Gt(0),
r.DB("test").Table("log").Insert(map[string]interface{}{
"time": r.Now(),
"result": "ok",
}),
r.DB("test").Table("log").Insert(map[string]interface{}{
"time": r.Now(),
"result": "failed",
}))
}).Run(session)
基本上,在Do
内部,我们可以访问RethinkDB先前函数调用的返回值,并且我们可以继续在该返回值上调用ReQL命令,就像在Map
函数中一样。
在Branch
内部,我们传递了3个参数,它们都是Go RethinkDB驱动程序中的Term
类型。你还可以参考官方示例:https://godoc.org/github.com/dancannon/gorethink#Branch
由于Go语言的特性以及无法适应官方驱动程序(Ruby、Python、JS)相同的动态风格,要熟悉Go驱动程序有点困难。在无法链式调用命令的语言中,这更加令人困惑。
英文:
The author of Go RethinkDB driver is very active on Github and you may get quicker answer if asking over there.
Here is an example of Do
.
res, _ := r.DB("test").Table("table").Get("ID").Do(func(issue r.Term) r.Term {
return issue.Merge(map[string]string{
"new_field": "new_value",
})
}).Run(session)
var b []interface{}
a.All(&b)
fmt.Println(b)
I think the most important thing is to ensure we declare correct type Term
. I import RethinkDB driver as r
so I used r.Term
. Then inside Do
function, you can use any command from Term: https://godoc.org/github.com/dancannon/gorethink#Term
An example of Do
and Branch
at same time:
r.DB("test").Table("issues").Insert(map[string]interface{}{
"id": 1111,
}).Do(func(result r.Term) r.Term {
return r.Branch(result.Field("inserted").Gt(0),
r.DB("test").Table("log").Insert(map[string]interface{}{
"time": r.Now(),
"result": "ok",
}),
r.DB("test").Table("log").Insert(map[string]interface{}{
"time": r.Now(),
"result": "failed",
}))
}).Run(session)
Basically, inside Do
, we have access to return value of previous funciton call of RethinkDB, and we can continue to call ReQL command on that return value as in a Map
function.
Inside Branch
, we pass 3 arguments, all are Term
type in Go RethinkDB driver. You can also refer to the official example: https://godoc.org/github.com/dancannon/gorethink#Branch
It's bit hard to get familiar with Go driver because of the nature of language and cannot fit in same dynamic style of official driver(Ruby, Python, JS). It's even more confusing in Language that we cannot chain command.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论