I have a widget.json file which is loaded into a document in couchbase:
{
"type": "widget",
"name": "clicker",
"description": "clicks!"
}
I also have a couchbase design document, couchbase.ddoc, for a bucket. It is registered with the name "views":
{
"_id": "_design/accesscheck",
"language": "javascript",
"views": {
"all_widgets": {
"map": "function(doc, meta) { if(doc.type == 'widget') { emit(meta.id, doc.name); } }"
}
}
}
and some golang code, using the couchbase golang API, to fetch it:
opts := map[string]interface{}{
"stale": false
}
data, _ := bucket.View("views", "all_widgets", opts)
and at this point i still have A Few Questions:
some of the Get() examples pass in a struct type i.e.
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)
", err)
}
fmt.Printf("Got back a user with a name of (%s) and id (%s)
", user.Name, user.Id)
Is it possible to do something like this with a View()?
I didn't find these questions covered in the golang client API examples or documentation. I probably missed something. If someone has links please let me know.
Thanks for any help!
If you are using github.com/couchbaselabs/go-couchbase
, you can use bucket.ViewCustom
to solve your problem. It accepts a item which view result parsed to.
The bucket.View
is just calling bucket.ViewCustom
with predefined struct and returns it.
An executed view result is a json object like below;
{
"total_rows": 123,
"rows": [
{
"id": "id of document",
"key": {key you emitted},
"value": {value you emitted},
"doc": {the document}
},
...
]
}
As we are know this structure, we can set struct type manually to bucket.ViewCustom
.
In your case, you can write custom view struct for "all_widgets" like this;
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"`
}
And use bucket.ViewCustom
to retrieve the value.
var result AllWidgetsView
opts := map[string]interface{}{}
viewErr := bucket.ViewCustom("views", "all_widgets", opts, &result)
if viewErr != nil {
// handle error
}
If this pattern of code appears frequently, you can refactor it.
For the question 2, it's not related to golang but Couchbase itself.
View has some feature that bucket has not. View results are sorted by key so you can specify startkey
option to where the result start. You can use this attribute and make view for searching. See Querying views for more information.
But you need more detailed search like full-text search, you should use ElasticSearch plugin or N1QL
to do it. (note the N1QL
is preview and not officially released yet)