douhuanchi6586 2014-07-05 08:27
浏览 17
已采纳

mgo不保证不同的指标

I am using following go file as layer between my http API and 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)
}

As you see I am ensuring indices on each operation by calling m.index(model). The model type has tags of form store:"index" or store:"unique".

As setting a general index is different from setting a unique index I collect them separately and then call m.collection.EnsureIndex on the resolved keys.

However the second call to m.collection.EnsureIndex does never reach the server only the normal indices were sent.

A look into the godocs shows that ensure Index caches its calls so I think I should combine them in one call.

So how do I combine different index settings in one call to EnsureIndex?

Solution: You need to lower case field names from reflect to use them with mgo...

  • 写回答

1条回答 默认 最新

  • duandong1963 2014-07-05 17:00
    关注

    The problem description seems to imply you have unique and non-unique index on the same set of fields. That's an additional unnecessary overhead.. just create one unique index in those cases.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog