golang mgo TTL index 的中文翻译是 “golang mgo TTL 索引”。

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

golang mgo TTL index

问题

如何使用golang和mongodb创建TTL(生存时间)索引?

以下是我目前尝试的方法:

sessionTTL := mgo.Index{
    Key:         []string{"created"},
    Unique:      false,
    DropDups:    false,
    Background:  true,
    ExpireAfter: session_expire, // session_expire是一个time.Duration类型的变量
}

if err := db.C("session").EnsureIndex(sessionTTL); err != nil {
    panic(err)
}

但是,如果我使用以下代码进行查找:

db.session.getIndexes()

session_expire被设置为5*time.Second。文档中的"created"字段使用time.Now()设置为当前日期,所以我期望文档在5秒后被删除。

英文:

how do I create a TTL (time to live) index with golang and mongodb?
This is how I'm trying to do it currently:

sessionTTL := mgo.Index{
	Key:         []string{"created"},
	Unique:      false,
	DropDups:    false,
	Background:  true,
	ExpireAfter: session_expire} // session_expire is a time.Duration

if err := db.C("session").EnsureIndex(sessionTTL); err != nil {
	panic(err)
}

But if I look it up using:

db.session.getIndexes()

session_expire is set to 5*time.Second. The field "created" in the document is set to current date using time.Now(), so I expected the documents the be deleted after 5 seconds.

答案1

得分: 1

所以问题是我必须删除该集合。索引已经存在,因此不会重新创建带有过期约束的索引。

英文:

So the issue was that I had to drop the collection. The index existed already so it was not recreated with the expiration constraint.

答案2

得分: 1

我试图使用这个答案,但遇到了一个问题。考虑以下小的更改:

sessionTTL := mgo.Index{
    Key:         []string{"created"},
    Unique:      false,
    DropDups:    false,
    Background:  true,
    ExpireAfter: 60 * 60} // 一小时

if err := db.C("session").EnsureIndex(sessionTTL); err != nil {
    panic(err)
}

这个问题在于,如果ExpireAfter不是一个合适的time.Duration,代码会悄无声息地失败。

我不得不改成:

ExpireAfter: time.Duration(60 * 60) * time.Second,
英文:

I was trying to use the answer to this question, and ran into a problem. Consider the following small change:

sessionTTL := mgo.Index{
    Key:         []string{"created"},
    Unique:      false,
    DropDups:    false,
    Background:  true,
    ExpireAfter: 60 * 60} // one hour

if err := db.C("session").EnsureIndex(sessionTTL); err != nil {
    panic(err)
}

The problem with this is that the code silently fails if ExpireAfter is not a proper time.Duration.

I had to change to:
ExpireAfter: time.Duration(60 * 60) * time.Second,

huangapple
  • 本文由 发表于 2015年12月23日 06:52:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/34425770.html
匿名

发表评论

匿名网友

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

确定