开源软件名称:rethinkdb/rethinkdb-go开源软件地址:https://github.com/rethinkdb/rethinkdb-go开源编程语言:Go 87.4%开源软件介绍:RethinkDB-go - RethinkDB Driver for GoCurrent version: v6.2.1 (RethinkDB v2.4) Please note that this version of the driver only supports versions of RethinkDB using the v0.4 protocol (any versions of the driver older than RethinkDB 2.0 will not work). If you need any help you can find me on the RethinkDB slack in the #gorethink channel. Installation
Replace Examplepackage rethinkdb_test
import (
"fmt"
"log"
r "gopkg.in/rethinkdb/rethinkdb-go.v6"
)
func Example() {
session, err := r.Connect(r.ConnectOpts{
Address: url, // endpoint without http
})
if err != nil {
log.Fatalln(err)
}
res, err := r.Expr("Hello World").Run(session)
if err != nil {
log.Fatalln(err)
}
var response string
err = res.One(&response)
if err != nil {
log.Fatalln(err)
}
fmt.Println(response)
// Output:
// Hello World
} ConnectionBasic ConnectionSetting up a basic connection with RethinkDB is simple: func ExampleConnect() {
var err error
session, err = r.Connect(r.ConnectOpts{
Address: url,
})
if err != nil {
log.Fatalln(err.Error())
}
} See the documentation for a list of supported arguments to Connect(). Connection PoolThe driver uses a connection pool at all times, by default it creates and frees connections automatically. It's safe for concurrent use by multiple goroutines. To configure the connection pool func ExampleConnect_connectionPool() {
var err error
session, err = r.Connect(r.ConnectOpts{
Address: url,
InitialCap: 10,
MaxOpen: 10,
})
if err != nil {
log.Fatalln(err.Error())
}
} Connect to a clusterTo connect to a RethinkDB cluster which has multiple nodes you can use the following syntax. When connecting to a cluster with multiple nodes queries will be distributed between these nodes. func ExampleConnect_cluster() {
var err error
session, err = r.Connect(r.ConnectOpts{
Addresses: []string{url},
// Addresses: []string{url1, url2, url3, ...},
})
if err != nil {
log.Fatalln(err.Error())
}
} When User AuthenticationTo login with a username and password you should first create a user, this can be done by writing to the err := r.DB("rethinkdb").Table("users").Insert(map[string]string{
"id": "john",
"password": "p455w0rd",
}).Exec(session)
...
err = r.DB("blog").Table("posts").Grant("john", map[string]bool{
"read": true,
"write": true,
}).Exec(session)
... Finally the username and password should be passed to session, err := r.Connect(r.ConnectOpts{
Address: "localhost:28015",
Database: "blog",
Username: "john",
Password: "p455w0rd",
}) Please note that Query FunctionsThis library is based on the official drivers so the code on the API page should require very few changes to work. To view full documentation for the query functions check the API reference or GoDoc Slice Expr Example r.Expr([]interface{}{1, 2, 3, 4, 5}).Run(session) Map Expr Example r.Expr(map[string]interface{}{"a": 1, "b": 2, "c": 3}).Run(session) Get Example r.DB("database").Table("table").Get("GUID").Run(session) Map Example (Func) r.Expr([]interface{}{1, 2, 3, 4, 5}).Map(func (row Term) interface{} {
return row.Add(1)
}).Run(session) Map Example (Implicit) r.Expr([]interface{}{1, 2, 3, 4, 5}).Map(r.Row.Add(1)).Run(session) Between (Optional Args) Example r.DB("database").Table("table").Between(1, 10, r.BetweenOpts{
Index: "num",
RightBound: "closed",
}).Run(session) For any queries which use callbacks the function signature is important as your function needs to be a valid RethinkDB-go callback, you can see an example of this in the map example above. The simplified explanation is that all arguments must be of type r.Table("test").Insert(doc, r.InsertOpts{
Conflict: func(id, oldDoc, newDoc r.Term) interface{} {
return newDoc.Merge(map[string]interface{}{
"count": oldDoc.Add(newDoc.Field("count")),
})
},
}) Optional ArgumentsAs shown above in the Between example optional arguments are passed to the function as a struct. Each function that has optional arguments as a related struct. This structs are named in the format FunctionNameOpts, for example BetweenOpts is the related struct for Between. Cancelling queriesFor query cancellation use For unlimited timeouts for ResultsDifferent result types are returned depending on what function is used to execute the query.
Example: res, err := r.DB("database").Table("tablename").Get(key).Run(session)
if err != nil {
// error
}
defer res.Close() // Always ensure you close the cursor to ensure connections are not leaked Cursors have a number of methods available for accessing the query results
Examples: var row interface{}
for res.Next(&row) {
// Do something with row
}
if res.Err() != nil {
// error
} var rows []interface{}
err := res.All(&rows)
if err != nil {
// error
} var row interface{}
err := res.One(&row)
if err == r.ErrEmptyResult {
// row not found
}
if err != nil {
// error
} Encoding/DecodingWhen passing structs to Expr(And functions that use Expr such as Insert, Update) the structs are encoded into a map before being sent to the server. Each exported field is added to the map unless
Each fields default name in the map is the field name but can be specified in the struct field's tag value. The "rethinkdb" key in the struct field's tag value is the key name, followed by an optional comma and options. Examples: // Field is ignored by this package.
Field int `rethinkdb:"-"`
// Field appears as key "myName".
Field int `rethinkdb:"myName"`
// Field appears as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `rethinkdb:"myName,omitempty"`
// Field appears as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `rethinkdb:",omitempty"`
// When the tag name includes an index expression
// a compound field is created
Field1 int `rethinkdb:"myName[0]"`
Field2 int `rethinkdb:"myName[1]"` NOTE: It is strongly recommended that struct tags are used to explicitly define the mapping between your Go type and how the data is stored by RethinkDB. This is especially important when using an When encoding maps with non-string keys the key values are automatically converted to strings where possible, however it is recommended that you use strings where possible (for example If you wish to use the NOTE: Old-style Pseudo-typesRethinkDB contains some special types which can be used to store special value types, currently supports are binary values, times and geometry data types. RethinkDB-go supports these data types natively however there are some gotchas:
Compound KeysRethinkDB unfortunately does not support compound primary keys using multiple fields however it does support compound keys using an array of values. For example if you wanted to create a compound key for a book where the key contained the author ID and book name then the ID might look like this type Book struct {
AuthorID string `rethinkdb:"id[0]"`
Name string `rethinkdb:"id[1]"`
}
// Creates the following document in RethinkDB
{"id": [AUTHORID, NAME]} ReferencesSometimes you may want to use a Go struct that references a document in another table, instead of creating a new struct which is just used when writing to RethinkDB you can annotate your struct with the reference tag option. This will tell RethinkDB-go that when encoding your data it should "pluck" the ID field from the nested document and use that instead. This is all quite complicated so hopefully this example should help. First lets assume you have two types type Author struct {
ID string `rethinkdb:"id,omitempty"`
Name string `rethinkdb:"name"`
}
type Book struct {
ID string `rethinkdb:"id,omitempty"`
Title string `rethinkdb:"title"`
Author Author `rethinkdb:"author_id,reference" rethinkdb_ref:"id"`
} The resulting data in RethinkDB should look something like this: {
"author_id": "author_1",
"id": "book_1",
"title": "The Hobbit"
} If you wanted to read back the book with the author included then you could run the following RethinkDB-go query: r.Table("books").Get("1").Merge(func(p r.Term) interface{} {
return map[string]interface{}{
"author_id": r.Table("authors").Get(p.Field("author_id")),
}
}).Run(session) You are also able to reference an array of documents, for example if each book stored multiple authors you could do the following: type Book struct {
ID string `rethinkdb:"id,omitempty"`
Title string `rethinkdb:"title"`
Authors []Author `rethinkdb:"author_ids,reference" rethinkdb_ref:"id"`
} {
"author_ids": ["author_1", "author_2"],
"id": "book_1",
"title": "The Hobbit"
} The query for reading the data back is slightly more complicated but is very similar: r.Table("books").Get("book_1").Merge(func(p r.Term) interface{} {
return map[string]interface{}{
"author_ids": r.Table("authors").GetAll(r.Args(p.Field("author_ids"))).CoerceTo("array"),
}
})
Custom |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论