在BoltDB中存储数据的最佳方法是什么?

huangapple go评论169阅读模式
英文:

Best way to store data in BoltDB

问题

我是新手,对BoltDB和Golang不太了解,想请你帮忙。

我知道在BoltDB中,只能将字节数组([]byte)保存为键和值。如果我有一个如下所示的用户结构体,其中键将是用户名,那么在将数据存储到BoltDB中(它期望字节数组)时,最好选择哪种方式?

是序列化还是JSON?还是有更好的方法?

type User struct {
    name string
    age  int
    location string
    password string
    address string 
}

非常感谢,祝你晚上愉快。

英文:

I am new to BoltDB and Golang, and trying to get your help.

So, I understand that I can only save byte array ([]byte) for key and value of BoltDB. If I have a struct of user as below, and key will be the username, what would be the best choice to store the data into BoltDB where it expects array of bytes?

Serializing it or JSON? Or better way?

type User struct {
    name string
    age  int
    location string
    password string
    address string 
}

Thank you so much, have a good evening

答案1

得分: 21

是的,我建议将User结构体编组为JSON,然后使用唯一的键[]byte切片。不要忘记,编组为JSON只包括导出的结构体字段,所以你需要按照下面的示例更改你的结构体。

另一个示例,请参考BoltDB GitHub页面

type User struct {
    Name     string
    Age      int
    Location string
    Password string
    Address  string
}

func (user *User) save(db *bolt.DB) error {
    // 使用用户名作为键,将用户模型存储在用户桶中。
    err := db.Update(func(tx *bolt.Tx) error {
        b, err := tx.CreateBucketIfNotExists(usersBucket)
        if err != nil {
            return err
        }

        encoded, err := json.Marshal(user)
        if err != nil {
            return err
        }
        return b.Put([]byte(user.Name), encoded)
    })
    return err
}
英文:

Yes, I would recommend marshaling the User struct to JSON and then use a unique key []byte slice. Don't forget that marshaling to JSON only includes the exported struct fields, so you'll need to change your struct as shown below.

For another example, see the BoltDB GitHub page.

type User struct {
    Name string
    Age  int
    Location string
    Password string
    Address string 
}

func (user *User) save(db *bolt.DB) error {
	// Store the user model in the user bucket using the username as the key.
	err := db.Update(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists(usersBucket)
		if err != nil {
			return err
		}    

		encoded, err := json.Marshal(user)
		if err != nil {
			return err
		}
		return b.Put([]byte(user.Name), encoded)
	})
	return err
}

答案2

得分: 1

一个很好的选择是Storm包,它可以实现你想要做的事情:

package main

import (
   "fmt"
   "github.com/asdine/storm/v3"
)

type user struct {
   ID int `storm:"increment"`
   address string
   age int
}

func main() {
   db, e := storm.Open("storm.db")
   if e != nil {
      panic(e)
   }
   defer db.Close()
   u := user{address: "123 Main St", age: 18}
   db.Save(&u)
   fmt.Printf("%+v\n", u) // {ID:1 address:123 Main St age:18}
}

如你所见,你不必担心编组的问题,它会为你处理。默认情况下,它使用JSON,但你也可以配置它使用GOB或其他格式:

https://github.com/asdine/storm

英文:

A good option is the Storm package, which allows for exactly what you are wanting to do:

package main

import (
   "fmt"
   "github.com/asdine/storm/v3"
)

type user struct {
   ID int `storm:"increment"`
   address string
   age int
}

func main() {
   db, e := storm.Open("storm.db")
   if e != nil {
      panic(e)
   }
   defer db.Close()
   u := user{address: "123 Main St", age: 18}
   db.Save(&u)
   fmt.Printf("%+v\n", u) // {ID:1 address:123 Main St age:18}
}

As you can see, you don't have to worry about marshalling, it takes care of it for you. By default it uses JSON, but you can configure it to use GOB or others as well:

https://github.com/asdine/storm

huangapple
  • 本文由 发表于 2016年3月31日 10:09:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/36322933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定