英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论