Reputation: 4706
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{"[email protected]", "Joe", 30},
&Person{"[email protected]", "Lucy", 35},
&Person{"[email protected]", "Tariq", 21},
&Person{"[email protected]", "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 [email protected]
?
Upvotes: 2
Views: 345
Reputation: 44962
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 write tx
deltxn := db.Txn(true)
err = deltxn.Delete("person", Person{Email: "[email protected]"})
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
Upvotes: 1