英文:
Order by nested object in RethinkDB using Go driver
问题
使用Go驱动程序如何从RethinkDB中按嵌套对象的顺序获取数据?
假设我在表中有以下JSON数据:
[
{
"id": "1",
"date": "2001-01-15",
"time": {
"begin": "09:00",
"end": "10:30"
}
},
{
"id": "2",
"date": "2001-01-16",
"time": {
"begin": "08:30",
"end": "10:30"
}
}
]
Go模型如下:
type MyTime struct {
Begin time.Time json:"begin"
End time.Time json:"end"
}
type Something struct {
Id string json:"id"
Date time.Time json:"date"
Time MyTime json:"time"
}
以下是按id排序的示例:
var result []Something
db.Table("someTable").OrderBy("id").Run(session).All(&result)
我尝试按时间开始排序,像这样(认为这种方法与ArangoDB中的方法相同,但显然不是):
var result []Something
db.Table("someTable").OrderBy("time.begin").Run(session).All(&result)
我在官方网站上看到了一个使用原生JavaScript驱动程序的示例:
示例:使用嵌套字段语法对子文档的字段进行排序。(您还可以使用此语法使用indexCreate在嵌套字段上创建索引。)
r.table('user').orderBy(r.row('group')('id')).run(conn, callback)
但不太清楚如何将其转换为Go语言。
有什么办法可以使其工作吗?
英文:
How is it possible using Go driver fetch data from RethinkDB in order by of nested object?
So let's imagine I have such json in my table:
[
{
"id": "1",
"date": "2001-01-15",
"time": {
"begin": "09:00",
"end": "10:30"
}
},
{
"id": "2",
"date": "2001-01-16",
"time": {
"begin": "08:30",
"end": "10:30"
}
}
]
Go model is:
type MyTime struct {
Begin time.Time `json:"begin"`
End time.Time `json:"end"`
}
type Something struct {
Id string `json:"id"`
Date time.Time `json:"date"`
Time MyTime `json:"time"`
}
Example how it is possible to order by id:
var result []Something
db.Table("someTable").OrderBy("id").Run(session).All(&result)
I tried to order by beginning of time like this (thinking that the approach is the same as in ArangoDB, but apparently it is not):
var result []Something
db.Table("someTable").OrderBy("time.begin").Run(session).All(&result)
I saw an example on the official site how it works by using native javascript driver
> Example: Use nested field syntax to sort on fields from subdocuments. (You can also
> create indexes on nested fields using this syntax with indexCreate.)
>
> r.table('user').orderBy(r.row('group')('id')).run(conn, callback)
But it is not really clear how to transform it to Go.
Any idea how to make it work?
答案1
得分: 1
你可以使用一个函数,类似这样的:
db.Table("someTable").OrderBy(func(row Term) Term {
return row.Field("time").Field("begin")
}).Run(session).All(&result)
英文:
You can use a function, something like this:
db.Table("someTable").OrderBy(func(row Term) Term {
return row.Field("time").Field("begin")
}).Run(session).All(&result)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论