我使用以下go文件作为我的http和mgo之间的层:
package store
import (
"reflect"
"strings"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
type Manager struct {
collection *mgo.Collection
}
type Model interface {
Id() bson.ObjectId
}
func (m *Manager) index(model Model) {
v := reflect.ValueOf(model).Elem()
var index, unique []string
for i := 0; i < v.NumField(); i++ {
t := v.Type().Field(i)
if s := t.Tag.Get("store"); len(s) != 0 {
if strings.Contains(s, "index") {
index = append(index, t.Name)
}
if strings.Contains(s, "unique") {
unique = append(unique, t.Name)
}
}
}
m.collection.EnsureIndex(mgo.Index{Key: index})
m.collection.EnsureIndex(mgo.Index{Key: unique, Unique: true})
}
func (m *Manager) Create(model Model) error {
m.index(model)
return m.collection.Insert(model)
}
func (m *Manager) Update(model Model) error {
m.index(model)
return m.collection.UpdateId(model.Id(), model)
}
func (m *Manager) Destroy(model Model) error {
m.index(model)
return m.collection.RemoveId(model.Id())
}
func (m *Manager) Find(query Query, models interface{}) error {
return m.collection.Find(query).All(models)
}
func (m *Manager) FindOne(query Query, model Model) error {
m.index(model)
return m.collection.Find(query).One(model)
}正如您所看到的,我通过调用m.index(model)来确保每个操作的索引。模型类型具有表单store:"index"或store:"unique"的标记。
由于设置通用索引与设置唯一索引不同,所以我分别收集它们,然后在解析的键上调用m.collection.EnsureIndex。
但是,对m.collection.EnsureIndex的第二个调用永远不会到达服务器,只发送正常的索引。
通过查看戈多斯,可以确保索引缓存其调用,因此我认为我应该将它们合并到一个调用中。
,那么如何在一个调用EnsureIndex?中组合不同的索引设置?
解决方案:您需要降低大小写字段名的反射,以使用它们与乐高.
发布于 2014-07-05 17:00:20
问题描述似乎意味着在同一组字段上有唯一的和非唯一的索引。这是额外的不必要的开销。只需在这些情况下创建一个唯一的索引即可。
https://stackoverflow.com/questions/24584501
复制相似问题