如何在GO中从memDB中删除条目

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

How to remove an entry from memDB in GO

问题

你可以使用以下代码从go-memdb中删除joe@aol.com

// 创建一个写事务
txn := db.Txn(true)

// 删除指定的记录
err := txn.Delete("person", &Person{Email: "joe@aol.com"})
if err != nil {
    panic(err)
}

// 提交事务
txn.Commit()

这将在person表中删除具有Email字段为joe@aol.com的记录。

英文:

I am doing something like this with github.com/hashicorp/go-memdb:

// Create a sample struct
type Person struct {
	Email string
	Name  string
	Age   int
}

// Create the DB schema
schema := &memdb.DBSchema{
	Tables: map[string]*memdb.TableSchema{
		"person": &memdb.TableSchema{
			Name: "person",
			Indexes: map[string]*memdb.IndexSchema{
				"id": &memdb.IndexSchema{
					Name:    "id",
					Unique:  true,
					Indexer: &memdb.StringFieldIndex{Field: "Email"},
				},
				"age": &memdb.IndexSchema{
					Name:    "age",
					Unique:  false,
					Indexer: &memdb.IntFieldIndex{Field: "Age"},
				},
			},
		},
	},
}

// Create a new data base
db, err := memdb.NewMemDB(schema)
if err != nil {
	panic(err)
}

// Create a write transaction
txn := db.Txn(true)

// Insert some people
people := []*Person{
	&Person{"joe@aol.com", "Joe", 30},
	&Person{"lucy@aol.com", "Lucy", 35},
	&Person{"tariq@aol.com", "Tariq", 21},
	&Person{"dorothy@aol.com", "Dorothy", 53},
}
for _, p := range people {
	if err := txn.Insert("person", p); err != nil {
		panic(err)
	}
}

// Commit the transaction
txn.Commit()

My question is how do I remove joe@aol.com ?

答案1

得分: 1

使用Txn.Delete方法,将具有唯一索引字段设置为所需值的对象传递给它。

根据您的模式,唯一索引与结构体Email字段相关联,因此将一个具有该字段的Person结构体传递给Delete方法(它不必是指针):

// 创建读取事务
deltxn := db.Txn(true)
err = deltxn.Delete("person", Person{Email: "joe@aol.com"})

如果要删除多个条目,请使用Txn.DeleteAll方法,并传递表名、索引名和过滤值。它将返回删除的条目数:

deltxn = db.Txn(true)
// 删除所有age=30的条目
d, err = txn.DeleteAll("person", "age", 30)
// d 的值为 1

Playground: https://go.dev/play/p/b-Tl5Nntdjm

英文:

Use Txn.Delete by passing an object with the unique index field set to the desired value.

Based on your schema, the unique index is associated to the struct Email field, so pass to Delete a Person struct with that field (it doesn't have to be a pointer):

// new read tx
deltxn := db.Txn(true)
err = deltxn.Delete("person", Person{Email: "joe@aol.com"})

If you want to delete multiple entries, use Txn.DeleteAll and pass the table name, the index name and a filter value. It returns the number of deleted entries:

deltxn = db.Txn(true)
// deleting all entries with age=30
d, err = txn.DeleteAll("person", "age", 30)
// d is 1

Playground: https://go.dev/play/p/b-Tl5Nntdjm

huangapple
  • 本文由 发表于 2022年5月21日 04:40:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/72324568.html
匿名

发表评论

匿名网友

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

确定