/
mongo.go
131 lines (110 loc) · 2.47 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package repo
import (
"log"
"math/rand"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type MongoDBRepo struct {
db *mgo.Database
session *mgo.Session
}
func (repo *MongoDBRepo) Init() bool {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
repo.db = session.DB("test")
return true
}
func (repo *MongoDBRepo) Seed(itemsInDataSet int) bool {
c := repo.db.C("items")
c.EnsureIndexKey("id")
c.EnsureIndexKey("name")
c.EnsureIndexKey("year")
c.EnsureIndex(mgo.Index{
Key: []string{"$text:description"}})
log.Printf("Seeding data to mongo")
bulk := c.Bulk()
for i := 0; i < itemsInDataSet; i++ {
bulk.Insert(newItem(i))
}
if _, err := bulk.Run(); err != nil {
panic(err)
}
return true
}
func (repo *MongoDBRepo) QueryFullText(textQuery func() string, N int, limit int) (ret []*Item) {
c := repo.db.C("items")
ret = make([]*Item, 0, limit)
for i := 0; i < N; i++ {
it := c.Find(bson.M{"$text": bson.M{"$search": textQuery()}}).Limit(limit).Iter()
item := &Item{}
for it.Next(item) {
ret = append(ret, item)
}
it.Close()
}
return ret
}
func (repo *MongoDBRepo) QueryByID(N int, onlyQuery bool) (it *Item) {
c := repo.db.C("items")
for i := 0; i < N; i++ {
it = &Item{}
if err := c.Find(bson.M{"id": rand.Int() % itemsInDataSet}).One(it); err != nil {
panic(err)
}
}
return it
}
func (repo *MongoDBRepo) Query2Cond(N int, onlyQuery bool, limit int) (ret []*Item) {
c := repo.db.C("items")
if !onlyQuery {
ret = make([]*Item, 0, limit)
}
for i := 0; i < N; i++ {
it := c.Find(bson.M{"name": randString(), "year": bson.M{"$gt": 2010}}).Limit(limit).Iter()
item := &Item{}
if !onlyQuery {
for it.Next(item) {
ret = append(ret, item)
}
} else {
it.Next(item)
}
}
return ret
}
func (repo *MongoDBRepo) Query1Cond(N int, onlyQuery bool, limit int) (ret []*Item) {
c := repo.db.C("items")
if !onlyQuery {
ret = make([]*Item, 0, limit)
}
for i := 0; i < N; i++ {
it := c.Find(bson.M{"year": bson.M{"$gt": 2010}}).Limit(limit).Iter()
item := &Item{}
if !onlyQuery {
for it.Next(item) {
ret = append(ret, item)
}
} else {
it.Next(item)
}
}
return ret
}
func (repo *MongoDBRepo) Update(N int) {
c := repo.db.C("items")
for i := 0; i < N; i++ {
id := rand.Int() % itemsInDataSet
item := newItem(id)
_, err := c.Upsert(bson.M{"id": id}, item)
if err != nil {
panic(err)
}
}
}
func init() {
registerRepo("mongo", &MongoDBRepo{})
}