diff --git a/database/books.go b/database/books.go index 72728f8..e8fe16d 100644 --- a/database/books.go +++ b/database/books.go @@ -1,6 +1,8 @@ package database import ( + log "github.com/cihub/seelog" + "strings" "unicode" @@ -37,6 +39,34 @@ type Book struct { Keywords []string } +func indexBooks(coll *mgo.Collection) { + indexes := []mgo.Index{ + { + Key: []string{"id"}, + Unique: true, + Background: true, + }, + { + Key: []string{"active", "-_id"}, + Background: true, + }, + } + for _, k := range []string{"keywords", "lang", "title", "author", "subject"} { + idx := mgo.Index{ + Key: []string{"active", k, "-_id"}, + Background: true, + } + indexes = append(indexes, idx) + } + + for _, idx := range indexes { + err := coll.EnsureIndex(idx) + if err != nil { + log.Error("Error indexing books: ", err) + } + } +} + func addBook(coll *mgo.Collection, book map[string]interface{}) error { book["keywords"] = keywords(book) return coll.Insert(book) diff --git a/database/database.go b/database/database.go index b98f8ef..ab80e43 100644 --- a/database/database.go +++ b/database/database.go @@ -30,9 +30,20 @@ func Init(host string, name string) *DB { os.Exit(1) } db.name = name + db.initIndexes() return db } +func (db *DB) initIndexes() { + dbCopy := db.session.Copy() + booksColl := dbCopy.DB(db.name).C(books_coll) + go indexBooks(booksColl) + statsColl := dbCopy.DB(db.name).C(stats_coll) + go indexStats(statsColl) + newsColl := dbCopy.DB(db.name).C(news_coll) + go indexNews(newsColl) +} + func (db *DB) Close() { db.session.Close() } diff --git a/database/news.go b/database/news.go index 52fd9e9..24b6158 100644 --- a/database/news.go +++ b/database/news.go @@ -1,6 +1,8 @@ package database import ( + log "github.com/cihub/seelog" + "time" "gopkg.in/mgo.v2" @@ -16,6 +18,18 @@ type News struct { Text string } +func indexNews(coll *mgo.Collection) { + idx := mgo.Index{ + Key: []string{"-date"}, + Unique: true, + Background: true, + } + err := coll.EnsureIndex(idx) + if err != nil { + log.Error("Error indexing news: ", err) + } +} + func addNews(coll *mgo.Collection, text string) error { var news News news.Text = text diff --git a/database/stats.go b/database/stats.go index 8add666..a716c0b 100644 --- a/database/stats.go +++ b/database/stats.go @@ -1,6 +1,8 @@ package database import ( + log "github.com/cihub/seelog" + "time" "gopkg.in/mgo.v2" @@ -42,6 +44,26 @@ type Visits struct { Count int "count" } +func indexStats(coll *mgo.Collection) { + indexes := []mgo.Index{ + { + Key: []string{"section"}, + Background: true, + }, + { + Key: []string{"-date", "section"}, + Background: true, + }, + } + + for _, idx := range indexes { + err := coll.EnsureIndex(idx) + if err != nil { + log.Error("Error indexing stats: ", err) + } + } +} + func GetTags(tagsColl *mgo.Collection) ([]string, error) { var result []struct { Tag string "_id"