-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongo.go
64 lines (54 loc) · 1.44 KB
/
mongo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const (
mongoHost = "localhost"
mongoDB = "nbc"
mongoCollection = "data"
)
var session *mgo.Session
// mongoConnect sets up a global *mgo.Session object, and ensures that the main collection is indexed
func mongoConnect() *mgo.Session {
var err error
session, err = mgo.Dial(mongoHost)
if err != nil {
panic(err)
}
session.SetSafe(&mgo.Safe{})
indexCollection()
return session
}
// mongoDisconnect disconnects from the underlying data source
func mongoDisconnect() {
session.Close()
}
// getCollection returns the mongo collection that is used to store the ngram data
func getCollection() *mgo.Collection {
return session.DB(mongoDB).C(*collection)
}
//getClassCollection returns the mongo collection used to store information about
// the different classes that have been learned so far
func getClassCollection() *mgo.Collection {
return session.DB(mongoDB).C(*collection + "_classes")
}
// indexCollection ensures that the mongo collection for the data is properly indexed
func indexCollection() {
col := getCollection()
index := mgo.Index{
Key: []string{"hash"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
_ = col.EnsureIndex(index)
}
// forgetData clears the data out of the mongo collection
func forgetData() {
c := getCollection()
c.RemoveAll(bson.M{})
c = getClassCollection()
c.RemoveAll(bson.M{})
}