我有一个widget.json文件,该文件已加载到couchbase的文档中:
{
"type": "widget",
"name": "clicker",
"description": "clicks!"
}
我也有一个用于存储桶的沙发床设计文档,couchbase.ddoc。它以名称“ views”注册:
{
"_id": "_design/accesscheck",
"language": "javascript",
"views": {
"all_widgets": {
"map": "function(doc, meta) { if(doc.type == 'widget') { emit(meta.id, doc.name); } }"
}
}
}
以及一些使用ouchbase golang API的golang代码来获取它:
opts := map[string]interface{}{
"stale": false
}
data, _ := bucket.View("views", "all_widgets", opts)
在这一点上,我还有几个问题:
一些Get()示例传递的是struct类型,即
type User struct {
Name string `json:"name"`
Id string `json:"id"`
}
err = bucket.Get("1", &user)
if err != nil {
log.Fatalf("Failed to get data from the cluster (%s)\n", err)
}
fmt.Printf("Got back a user with a name of (%s) and id (%s)\n", user.Name, user.Id)
是否可以使用View()做类似的事情?
我没有在golang客户端API示例或文档中找到这些问题。我可能错过了一些东西。如果有人有链接,请告诉我。
谢谢你的帮助!
如果您使用github.com/couchbaselabs/go-couchbase
,则可以使用bucket.ViewCustom
来解决您的问题。它接受一个视图结果解析为的项目。
在bucket.View
刚刚打电话bucket.ViewCustom
预定义的结构和返回。
执行后的视图结果是一个json对象,如下所示;
{
"total_rows": 123,
"rows": [
{
"id": "id of document",
"key": {key you emitted},
"value": {value you emitted},
"doc": {the document}
},
...
]
}
众所周知,我们可以将struct type手动设置为bucket.ViewCustom
。
就您而言,您可以像这样为“ all_widgets”编写自定义视图结构;
type AllWidgetsView struct {
Total int `json:"total_rows"`
Rows []struct {
ID string `json:"id"` // document id
Key string `json:"string"` // key you emitted, the 'meta.id'
Value string `json:"value"` // value you emitted, the 'doc.name'
} `json:"rows"`
}
并用于bucket.ViewCustom
检索值。
var result AllWidgetsView
opts := map[string]interface{}{}
viewErr := bucket.ViewCustom("views", "all_widgets", opts, &result)
if viewErr != nil {
// handle error
}
如果这种代码模式频繁出现,则可以对其进行重构。
对于问题2,它与golang无关,但与Couchbase本身有关。
视图具有存储桶没有的某些功能。查看结果按键排序,因此您可以指定startkey
开始结果的选项。您可以使用此属性并使视图成为搜索对象。有关更多信息,请参见查询视图。
但是您需要更详细的搜索(例如全文搜索),您应该使用ElasticSearch插件或N1QL
执行此操作。(请注意N1QL
是预览,尚未正式发布)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句