forked from huichen/wukong
-
Notifications
You must be signed in to change notification settings - Fork 10
/
engine.go
530 lines (457 loc) · 15.9 KB
/
engine.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package engine
import (
"fmt"
"github.com/henrylee2cn/wukong/core"
"github.com/henrylee2cn/wukong/storage"
"github.com/henrylee2cn/wukong/types"
"github.com/henrylee2cn/wukong/utils"
"github.com/huichen/sego"
"log"
"os"
"runtime"
"sort"
"strconv"
"sync"
"sync/atomic"
"time"
)
const (
NumNanosecondsInAMillisecond = 1000000
PersistentStorageFilePrefix = "wukong"
)
type Engine struct {
// 计数器,用来统计有多少文档被索引等信息
numDocumentsIndexed uint64
numIndexingRequests uint64
numTokenIndexAdded uint64
numDocumentsStored uint64
// 记录初始化参数
initOptions types.EngineInitOptions
initialized bool
indexers map[uint64]*core.Indexer
rankers map[uint64]*core.Ranker
dbs map[uint64]storage.Storage
segmenter sego.Segmenter
stopTokens StopTokens
// 建立索引器使用的通信通道
segmenterChannel chan segmenterRequest
indexerAddDocumentChannels map[uint64]chan indexerAddDocumentRequest
indexerRemoveDocChannels map[uint64]chan indexerRemoveDocRequest
rankerAddDocChannels map[uint64]chan rankerAddDocRequest
// 建立排序器使用的通信通道
indexerLookupChannels map[uint64]chan indexerLookupRequest
rankerRankChannels map[uint64]chan rankerRankRequest
rankerRemoveDocChannels map[uint64]chan rankerRemoveDocRequest
// 建立持久存储使用的通信通道
persistentStorageIndexDocumentChannels map[uint64]chan persistentStorageIndexDocumentRequest
persistentStorageInitChannel chan bool
// 动态添加工作协程的锁
sync.Mutex
}
func (engine *Engine) Init(options types.EngineInitOptions) {
// 将线程数设置为CPU数
runtime.GOMAXPROCS(runtime.NumCPU())
// 初始化初始参数
if engine.initialized {
log.Fatal("请勿重复初始化引擎")
}
options.Init()
engine.initOptions = options
engine.initialized = true
if !options.NotUsingSegmenter {
// 载入分词器词典
engine.segmenter.LoadDictionary(options.SegmenterDictionaries)
// 初始化停用词
engine.stopTokens.Init(options.StopTokenFile)
}
// 初始化分词器通道
engine.segmenterChannel = make(chan segmenterRequest, options.NumSegmenterThreads)
// 启动分词器
for iThread := 0; iThread < options.NumSegmenterThreads; iThread++ {
go engine.segmenterWorker()
}
// 分片数量
numShards := len(options.Shards)
// 初始化索引器和排序器
engine.indexers = make(map[uint64]*core.Indexer, numShards)
engine.rankers = make(map[uint64]*core.Ranker, numShards)
// 初始化索引器通道
engine.indexerAddDocumentChannels = make(map[uint64]chan indexerAddDocumentRequest, numShards)
engine.indexerLookupChannels = make(map[uint64]chan indexerLookupRequest, numShards)
// 初始化排序器通道
engine.rankerAddDocChannels = make(map[uint64]chan rankerAddDocRequest, numShards)
engine.rankerRankChannels = make(map[uint64]chan rankerRankRequest, numShards)
engine.rankerRemoveDocChannels = make(map[uint64]chan rankerRemoveDocRequest, numShards)
// 初始化持久化存储通道
if options.UsePersistentStorage {
engine.persistentStorageIndexDocumentChannels = make(map[uint64]chan persistentStorageIndexDocumentRequest, numShards)
for _, shard := range options.Shards {
engine.persistentStorageIndexDocumentChannels[shard] = make(chan persistentStorageIndexDocumentRequest)
}
engine.persistentStorageInitChannel = make(chan bool, numShards)
err := os.MkdirAll(options.PersistentStorageFolder, 0700)
if err != nil {
log.Fatal("无法创建目录", options.PersistentStorageFolder)
}
// 打开或者创建数据库
engine.dbs = make(map[uint64]storage.Storage, numShards)
}
if numShards == 0 {
return
}
for _, shard := range options.Shards {
// 索引器和排序器
engine.indexers[shard] = new(core.Indexer)
engine.indexers[shard].Init(*options.IndexerInitOptions)
engine.rankers[shard] = new(core.Ranker)
engine.rankers[shard].Init()
// 排序器通道
engine.indexerAddDocumentChannels[shard] = make(chan indexerAddDocumentRequest, options.IndexerBufferLength)
engine.indexerLookupChannels[shard] = make(chan indexerLookupRequest, options.IndexerBufferLength)
// 持久化存储通道
engine.rankerAddDocChannels[shard] = make(chan rankerAddDocRequest, options.RankerBufferLength)
engine.rankerRankChannels[shard] = make(chan rankerRankRequest, options.RankerBufferLength)
engine.rankerRemoveDocChannels[shard] = make(chan rankerRemoveDocRequest, options.RankerBufferLength)
// 启动索引器和排序器
go engine.indexerAddDocumentWorker(shard)
go engine.indexerRemoveDocWorker(shard)
go engine.rankerAddDocWorker(shard)
go engine.rankerRemoveDocWorker(shard)
for i := 0; i < options.NumIndexerThreadsPerShard; i++ {
go engine.indexerLookupWorker(shard)
}
for i := 0; i < options.NumRankerThreadsPerShard; i++ {
go engine.rankerRankWorker(shard)
}
}
// 启动索引信息持久化存储工作协程
if options.UsePersistentStorage {
for _, shard := range options.Shards {
dbPath := options.PersistentStorageFolder + "/" + PersistentStorageFilePrefix + "." + strconv.FormatUint(shard, 10)
db, err := storage.OpenStorage(dbPath, engine.initOptions.PersistentStorageEngine)
if db == nil || err != nil {
log.Fatal("无法打开数据库", dbPath, ": ", err)
}
engine.dbs[shard] = db
}
// 从数据库中恢复
for _, shard := range options.Shards {
go engine.persistentStorageInitWorker(shard)
}
// 等待恢复完成
for range options.Shards {
<-engine.persistentStorageInitChannel
}
for {
runtime.Gosched()
if engine.numIndexingRequests == engine.numDocumentsIndexed {
break
}
}
// 启动数据库实时写入协程
for _, shard := range options.Shards {
go engine.persistentStorageIndexDocumentWorker(shard)
}
}
}
// 在执行IndexDocument方法的过程中对documentIndexChan写入的数据进行计数
var documentIndexChanCount = map[chan *types.DocumentIndex]*Count{}
type Count struct {
Num int
sync.Mutex
}
// 将文档加入索引
//
// 输入参数:
// docId 标识文档编号,必须唯一
// data 见DocumentIndexData注释
//
// 注意:
// 1. 这个函数是线程安全的,请尽可能并发调用以提高索引速度。
// 2. 这个函数调用是非同步的,也就是说在函数返回时有可能文档还没有加入索引中,因此
// 如果立刻调用Search可能无法查询到这个文档。强制刷新索引请调用FlushIndex函数。
// 3. 可选参数documentIndexChan不为空时,将在分词步骤写入关键词及其词频信息,此时程序并进入等待状态,
// 只有当其通道内所有数据被外部读出来,程序才能继续运行、建立索引。
// 这样设计的目的在于让外部程序可以在索引建立之前,处理一些与documentIndexChan相关的事务。
// 注意:documentIndexChan必须为异步通道,其容量设置为欲传入IndexDocument方法的总次数!
func (engine *Engine) IndexDocument(docId string, data types.DocumentIndexData, shard uint64, documentIndexChan ...chan *types.DocumentIndex) {
// 检验指定的shard是否存在
if err := engine.checkShard(shard); err != nil {
// 动态添加工作协程及数据库
engine.appendRoutine(shard)
}
if !engine.initialized {
log.Fatal("必须先初始化引擎")
}
atomic.AddUint64(&engine.numIndexingRequests, 1)
var dichan chan *types.DocumentIndex
if len(documentIndexChan) > 0 {
dichan = documentIndexChan[0]
if _, ok := documentIndexChanCount[dichan]; !ok {
documentIndexChanCount[dichan] = new(Count)
}
}
engine.segmenterChannel <- segmenterRequest{docId: docId, shard: shard, data: data, documentIndexChan: dichan}
}
// 将文档从索引中删除
//
// 输入参数:
// docId 标识文档编号,必须唯一
// shards 指定分片,为空时在所有分片下操作
// 注意:这个函数仅从排序器中删除文档,索引器不会发生变化。
func (engine *Engine) RemoveDocument(docId string, shards ...uint64) {
if !engine.initialized {
log.Fatal("必须先初始化引擎")
}
if len(shards) == 0 {
for _, shard := range engine.initOptions.Shards {
engine.indexerRemoveDocChannels[shard] <- indexerRemoveDocRequest{docId: docId}
engine.rankerRemoveDocChannels[shard] <- rankerRemoveDocRequest{docId: docId}
if engine.initOptions.UsePersistentStorage {
// 从数据库中删除
go engine.persistentStorageRemoveDocumentWorker(shard, docId)
}
}
} else {
for _, shard := range shards {
engine.indexerRemoveDocChannels[shard] <- indexerRemoveDocRequest{docId: docId}
engine.rankerRemoveDocChannels[shard] <- rankerRemoveDocRequest{docId: docId}
if engine.initOptions.UsePersistentStorage {
// 从数据库中删除
go engine.persistentStorageRemoveDocumentWorker(shard, docId)
}
}
}
}
// 阻塞等待直到所有索引添加完毕
func (engine *Engine) FlushIndex() {
for {
runtime.Gosched()
if engine.numIndexingRequests == engine.numDocumentsIndexed &&
(!engine.initOptions.UsePersistentStorage || engine.numIndexingRequests == engine.numDocumentsStored) {
return
}
}
}
// 查找满足搜索条件的文档,此函数线程安全
func (engine *Engine) Search(request types.SearchRequest) (output types.SearchResponse) {
if !engine.initialized {
log.Fatal("必须先初始化引擎")
}
// 处理请求指定的shard
if len(request.Shards) == 0 {
request.Shards = engine.initOptions.Shards
} else if err := engine.checkShard(request.Shards...); err != nil {
log.Printf("%v", err)
// 指定搜范围有误时返回
return types.SearchResponse{}
}
var rankOptions types.RankOptions
if request.RankOptions == nil {
rankOptions = *engine.initOptions.DefaultRankOptions
} else {
rankOptions = *request.RankOptions
}
if rankOptions.ScoringCriteria == nil {
rankOptions.ScoringCriteria = engine.initOptions.DefaultRankOptions.ScoringCriteria
}
// 收集关键词
tokens := []string{}
if request.Text != "" {
querySegments := engine.segmenter.Segment([]byte(request.Text))
for _, s := range querySegments {
token := s.Token().Text()
if !engine.stopTokens.IsStopToken(token) {
tokens = append(tokens, s.Token().Text())
}
}
} else {
for _, t := range request.Tokens {
tokens = append(tokens, t)
}
}
// 建立排序器返回的通信通道
rankerReturnChannel := make(chan rankerReturnRequest, len(request.Shards))
// 生成查找请求
lookupRequest := indexerLookupRequest{
countDocsOnly: request.CountDocsOnly,
tokens: tokens,
labels: request.Labels,
docIds: request.DocIds,
options: rankOptions,
rankerReturnChannel: rankerReturnChannel,
orderless: request.Orderless,
}
// 向索引器发送查找请求
for _, shard := range request.Shards {
engine.indexerLookupChannels[shard] <- lookupRequest
}
// 从通信通道读取排序器的输出
numDocs := 0
rankOutput := types.ScoredDocuments{}
timeout := request.Timeout
isTimeout := false
if timeout <= 0 {
// 不设置超时
for range request.Shards {
rankerOutput := <-rankerReturnChannel
if !request.CountDocsOnly {
for _, doc := range rankerOutput.docs {
rankOutput = append(rankOutput, doc)
}
}
numDocs += rankerOutput.numDocs
}
} else {
// 设置超时
boom := time.After(time.Nanosecond * time.Duration(NumNanosecondsInAMillisecond*request.Timeout))
for range request.Shards {
select {
case rankerOutput := <-rankerReturnChannel:
if !request.CountDocsOnly {
for _, doc := range rankerOutput.docs {
rankOutput = append(rankOutput, doc)
}
}
numDocs += rankerOutput.numDocs
case <-boom:
isTimeout = true
break
}
}
}
// 再排序
if !request.CountDocsOnly && !request.Orderless {
if rankOptions.ReverseOrder {
sort.Sort(sort.Reverse(rankOutput))
} else {
sort.Sort(rankOutput)
}
}
// 准备输出
output.Tokens = tokens
// 仅当CountDocsOnly为false时才充填output.Docs
if !request.CountDocsOnly {
if request.Orderless {
// 无序状态无需对Offset截断
output.Docs = rankOutput
} else {
var start, end int
if rankOptions.MaxOutputs == 0 {
start = utils.MinInt(rankOptions.OutputOffset, len(rankOutput))
end = len(rankOutput)
} else {
start = utils.MinInt(rankOptions.OutputOffset, len(rankOutput))
end = utils.MinInt(start+rankOptions.MaxOutputs, len(rankOutput))
}
output.Docs = rankOutput[start:end]
}
}
output.NumDocs = numDocs
output.Timeout = isTimeout
return
}
// 关闭引擎
func (engine *Engine) Close() {
engine.FlushIndex()
if engine.initOptions.UsePersistentStorage {
for _, db := range engine.dbs {
db.Close()
}
}
}
// 只分词与过滤弃用词
func (engine *Engine) Segment(content string) (keywords []string) {
segments := engine.segmenter.Segment([]byte(content))
for _, segment := range segments {
token := segment.Token().Text()
if !engine.stopTokens.IsStopToken(token) {
keywords = append(keywords, token)
}
}
return
}
// 动态追加工作协程及数据库
func (engine *Engine) appendRoutine(shard uint64) {
engine.Mutex.Lock()
defer engine.Mutex.Unlock()
// 检验指定的shard是否存在
if err := engine.checkShard(shard); err == nil {
return
}
engine.initOptions.Shards = append(engine.initOptions.Shards, shard)
// 初始化索引器和排序器
engine.indexers[shard] = new(core.Indexer)
engine.indexers[shard].Init(*engine.initOptions.IndexerInitOptions)
engine.rankers[shard] = new(core.Ranker)
engine.rankers[shard].Init()
// 初始化索引器通道
engine.indexerAddDocumentChannels[shard] = make(chan indexerAddDocumentRequest, engine.initOptions.IndexerBufferLength)
engine.indexerLookupChannels[shard] = make(chan indexerLookupRequest, engine.initOptions.IndexerBufferLength)
// 初始化排序器通道
engine.rankerAddDocChannels[shard] = make(chan rankerAddDocRequest, engine.initOptions.RankerBufferLength)
engine.rankerRankChannels[shard] = make(chan rankerRankRequest, engine.initOptions.RankerBufferLength)
engine.rankerRemoveDocChannels[shard] = make(chan rankerRemoveDocRequest, engine.initOptions.RankerBufferLength)
// 初始化持久化存储通道
if engine.initOptions.UsePersistentStorage {
engine.persistentStorageIndexDocumentChannels[shard] = make(chan persistentStorageIndexDocumentRequest)
engine.persistentStorageInitChannel = make(chan bool, 1)
}
// 启动索引器和排序器
go engine.indexerAddDocumentWorker(shard)
go engine.rankerAddDocWorker(shard)
go engine.rankerRemoveDocWorker(shard)
for i := 0; i < engine.initOptions.NumIndexerThreadsPerShard; i++ {
go engine.indexerLookupWorker(shard)
}
for i := 0; i < engine.initOptions.NumRankerThreadsPerShard; i++ {
go engine.rankerRankWorker(shard)
}
// 启动索引信息持久化存储工作协程
if engine.initOptions.UsePersistentStorage {
// 打开或者创建数据库
dbPath := engine.initOptions.PersistentStorageFolder + "/" + PersistentStorageFilePrefix + "." + strconv.FormatUint(shard, 10)
db, err := storage.OpenStorage(dbPath, engine.initOptions.PersistentStorageEngine)
if db == nil || err != nil {
log.Fatal("无法打开数据库", dbPath, ": ", err)
}
engine.dbs[shard] = db
// 从数据库中恢复
go engine.persistentStorageInitWorker(shard)
// 等待恢复完成
<-engine.persistentStorageInitChannel
for {
runtime.Gosched()
if engine.numIndexingRequests == engine.numDocumentsIndexed {
break
}
}
// 从数据库初始化索引文档
go engine.persistentStorageIndexDocumentWorker(shard)
}
}
// 检查请求指定的shard是否已存在
func (engine *Engine) checkShard(shard ...uint64) error {
if len(shard) == 0 {
for _, i := range engine.initOptions.Shards {
shard = append(shard, i)
}
return nil
}
var ok = false
for _, m := range shard {
ok = false
for _, n := range engine.initOptions.Shards {
if m == n {
ok = true
break
}
}
if !ok {
goto err
}
}
return nil
err:
return fmt.Errorf("指定shard %v 不存在,有效shard范围为 %v", shard, engine.initOptions.Shards)
}