indexer.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. package core
  2. import (
  3. "github.com/huichen/wukong/types"
  4. "github.com/huichen/wukong/utils"
  5. "log"
  6. "math"
  7. "sort"
  8. "sync"
  9. )
  10. // 索引器
  11. type Indexer struct {
  12. // 从搜索键到文档列表的反向索引
  13. // 加了读写锁以保证读写安全
  14. tableLock struct {
  15. sync.RWMutex
  16. table map[string]*KeywordIndices
  17. docsState map[uint64]int // 0: 存在于索引中,1: 等待删除,2: 等待加入
  18. }
  19. addCacheLock struct {
  20. sync.RWMutex
  21. addCachePointer int
  22. addCache types.DocumentsIndex
  23. }
  24. removeCacheLock struct {
  25. sync.RWMutex
  26. removeCachePointer int
  27. removeCache types.DocumentsId
  28. }
  29. initOptions types.IndexerInitOptions
  30. initialized bool
  31. // 这实际上是总文档数的一个近似
  32. numDocuments uint64
  33. // 所有被索引文本的总关键词数
  34. totalTokenLength float32
  35. // 每个文档的关键词长度
  36. docTokenLengths map[uint64]float32
  37. }
  38. // 反向索引表的一行,收集了一个搜索键出现的所有文档,按照DocId从小到大排序。
  39. type KeywordIndices struct {
  40. // 用于标记在 docIds[] 进行批量加入索引时二分查找的下界
  41. lowerBound int
  42. // 下面的切片是否为空,取决于初始化时IndexType的值
  43. docIds []uint64 // 全部类型都有
  44. frequencies []float32 // IndexType == FrequenciesIndex
  45. locations [][]int // IndexType == LocationsIndex
  46. }
  47. // 初始化索引器
  48. func (indexer *Indexer) Init(options types.IndexerInitOptions) {
  49. if indexer.initialized == true {
  50. log.Fatal("索引器不能初始化两次")
  51. }
  52. options.Init()
  53. indexer.initOptions = options
  54. indexer.initialized = true
  55. indexer.tableLock.table = make(map[string]*KeywordIndices)
  56. indexer.tableLock.docsState = make(map[uint64]int)
  57. indexer.addCacheLock.addCache = make([]*types.DocumentIndex, indexer.initOptions.DocCacheSize)
  58. indexer.removeCacheLock.removeCache = make([]uint64, indexer.initOptions.DocCacheSize*2)
  59. indexer.docTokenLengths = make(map[uint64]float32)
  60. }
  61. // 从KeywordIndices中得到第i个文档的DocId
  62. func (indexer *Indexer) getDocId(ti *KeywordIndices, i int) uint64 {
  63. return ti.docIds[i]
  64. }
  65. // 得到KeywordIndices中文档总数
  66. func (indexer *Indexer) getIndexLength(ti *KeywordIndices) int {
  67. return len(ti.docIds)
  68. }
  69. // 向 ADDCACHE 中加入一个文档
  70. func (indexer *Indexer) AddDocumentToCache(document *types.DocumentIndex, forceUpdate bool) {
  71. if indexer.initialized == false {
  72. log.Fatal("索引器尚未初始化")
  73. }
  74. indexer.addCacheLock.Lock()
  75. if document != nil {
  76. indexer.addCacheLock.addCache[indexer.addCacheLock.addCachePointer] = document
  77. indexer.addCacheLock.addCachePointer++
  78. }
  79. if indexer.addCacheLock.addCachePointer >= indexer.initOptions.DocCacheSize || forceUpdate {
  80. indexer.tableLock.Lock()
  81. position := 0
  82. for i := 0; i < indexer.addCacheLock.addCachePointer; i++ {
  83. docIndex := indexer.addCacheLock.addCache[i]
  84. if docState, ok := indexer.tableLock.docsState[docIndex.DocId]; ok && docState == 0 {
  85. if position != i {
  86. indexer.addCacheLock.addCache[position], indexer.addCacheLock.addCache[i] =
  87. indexer.addCacheLock.addCache[i], indexer.addCacheLock.addCache[position]
  88. }
  89. indexer.removeCacheLock.Lock()
  90. indexer.removeCacheLock.removeCache[indexer.removeCacheLock.removeCachePointer] =
  91. docIndex.DocId
  92. indexer.removeCacheLock.removeCachePointer++
  93. indexer.removeCacheLock.Unlock()
  94. indexer.tableLock.docsState[docIndex.DocId] = 1
  95. indexer.numDocuments--
  96. position++
  97. } else if !(ok && docState == 1) {
  98. // ok && docState == 1 表示等待删除或者删除当前 doc
  99. indexer.tableLock.docsState[docIndex.DocId] = 2
  100. }
  101. }
  102. indexer.tableLock.Unlock()
  103. if indexer.RemoveDocumentToCache(0, forceUpdate) {
  104. position = 0
  105. }
  106. addCachedDocuments := indexer.addCacheLock.addCache[position:indexer.addCacheLock.addCachePointer]
  107. indexer.addCacheLock.addCachePointer = position
  108. indexer.addCacheLock.Unlock()
  109. sort.Sort(addCachedDocuments)
  110. indexer.AddDocuments(&addCachedDocuments)
  111. } else {
  112. indexer.addCacheLock.Unlock()
  113. }
  114. }
  115. // 向反向索引表中加入 ADDCACHE 中所有文档
  116. func (indexer *Indexer) AddDocuments(documents *types.DocumentsIndex) {
  117. if indexer.initialized == false {
  118. log.Fatal("索引器尚未初始化")
  119. }
  120. indexer.tableLock.Lock()
  121. defer indexer.tableLock.Unlock()
  122. for _, indices := range indexer.tableLock.table {
  123. indices.lowerBound = 0
  124. }
  125. // DocId 递增顺序遍历插入文档保证索引移动次数最少
  126. for i, document := range *documents {
  127. if i < len(*documents)-1 && (*documents)[i].DocId == (*documents)[i+1].DocId {
  128. // 如果有重复文档加入,因为稳定排序,只加入最后一个
  129. continue
  130. }
  131. if docState, ok := indexer.tableLock.docsState[document.DocId]; ok && docState == 1 {
  132. // 如果此时 docState 仍为 1,说明该文档需被删除
  133. continue
  134. }
  135. // 更新文档关键词总长度
  136. if document.TokenLength != 0 {
  137. indexer.docTokenLengths[document.DocId] = float32(document.TokenLength)
  138. indexer.totalTokenLength += document.TokenLength
  139. }
  140. docIdIsNew := true
  141. for _, keyword := range document.Keywords {
  142. indices, foundKeyword := indexer.tableLock.table[keyword.Text]
  143. if !foundKeyword {
  144. // 如果没找到该搜索键则加入
  145. ti := KeywordIndices{}
  146. switch indexer.initOptions.IndexType {
  147. case types.LocationsIndex:
  148. ti.locations = [][]int{keyword.Starts}
  149. case types.FrequenciesIndex:
  150. ti.frequencies = []float32{keyword.Frequency}
  151. }
  152. ti.docIds = []uint64{document.DocId}
  153. indexer.tableLock.table[keyword.Text] = &ti
  154. continue
  155. }
  156. // 查找应该插入的位置,且索引一定不存在
  157. position, _ := indexer.searchIndex(
  158. indices, indices.lowerBound, indexer.getIndexLength(indices)-1, document.DocId)
  159. indices.lowerBound = position
  160. switch indexer.initOptions.IndexType {
  161. case types.LocationsIndex:
  162. indices.locations = append(indices.locations, []int{})
  163. copy(indices.locations[position+1:], indices.locations[position:])
  164. indices.locations[position] = keyword.Starts
  165. case types.FrequenciesIndex:
  166. indices.frequencies = append(indices.frequencies, float32(0))
  167. copy(indices.frequencies[position+1:], indices.frequencies[position:])
  168. indices.frequencies[position] = keyword.Frequency
  169. }
  170. indices.docIds = append(indices.docIds, 0)
  171. copy(indices.docIds[position+1:], indices.docIds[position:])
  172. indices.docIds[position] = document.DocId
  173. }
  174. // 更新文章状态和总数
  175. if docIdIsNew {
  176. indexer.tableLock.docsState[document.DocId] = 0
  177. indexer.numDocuments++
  178. }
  179. }
  180. }
  181. // 向 REMOVECACHE 中加入一个待删除文档
  182. func (indexer *Indexer) RemoveDocumentToCache(docId uint64, forceUpdate bool) bool {
  183. if indexer.initialized == false {
  184. log.Fatal("索引器尚未初始化")
  185. }
  186. indexer.removeCacheLock.Lock()
  187. if docId != 0 {
  188. indexer.tableLock.Lock()
  189. if docState, ok := indexer.tableLock.docsState[docId]; ok && docState == 0 {
  190. indexer.removeCacheLock.removeCache[indexer.removeCacheLock.removeCachePointer] = docId
  191. indexer.removeCacheLock.removeCachePointer++
  192. indexer.tableLock.docsState[docId] = 1
  193. indexer.numDocuments--
  194. } else if !ok {
  195. // 删除一个等待加入的文档
  196. indexer.tableLock.docsState[docId] = 1
  197. }
  198. indexer.tableLock.Unlock()
  199. }
  200. if indexer.removeCacheLock.removeCachePointer > 0 &&
  201. (indexer.removeCacheLock.removeCachePointer >= indexer.initOptions.DocCacheSize ||
  202. forceUpdate) {
  203. removeCachedDocuments := indexer.removeCacheLock.removeCache[:indexer.removeCacheLock.removeCachePointer]
  204. indexer.removeCacheLock.removeCachePointer = 0
  205. indexer.removeCacheLock.Unlock()
  206. sort.Sort(removeCachedDocuments)
  207. indexer.RemoveDocuments(&removeCachedDocuments)
  208. return true
  209. }
  210. indexer.removeCacheLock.Unlock()
  211. return false
  212. }
  213. // 向反向索引表中删除 REMOVECACHE 中所有文档
  214. func (indexer *Indexer) RemoveDocuments(documents *types.DocumentsId) {
  215. if indexer.initialized == false {
  216. log.Fatal("索引器尚未初始化")
  217. }
  218. indexer.tableLock.Lock()
  219. defer indexer.tableLock.Unlock()
  220. // 更新文档关键词总长度,删除文档状态
  221. for _, docId := range *documents {
  222. indexer.totalTokenLength -= indexer.docTokenLengths[docId]
  223. delete(indexer.docTokenLengths, docId)
  224. delete(indexer.tableLock.docsState, docId)
  225. }
  226. for keyword, indices := range indexer.tableLock.table {
  227. indicesTop, indicesPointer := 0, 0
  228. documentsPointer := sort.Search(
  229. len(*documents), func(i int) bool { return (*documents)[i] >= indices.docIds[0] })
  230. // 双指针扫描,进行批量删除操作
  231. for ; documentsPointer < len(*documents) &&
  232. indicesPointer < indexer.getIndexLength(indices); indicesPointer++ {
  233. if indices.docIds[indicesPointer] < (*documents)[documentsPointer] {
  234. if indicesTop != indicesPointer {
  235. switch indexer.initOptions.IndexType {
  236. case types.LocationsIndex:
  237. indices.locations[indicesTop] = indices.locations[indicesPointer]
  238. case types.FrequenciesIndex:
  239. indices.frequencies[indicesTop] = indices.frequencies[indicesPointer]
  240. }
  241. indices.docIds[indicesTop] = indices.docIds[indicesPointer]
  242. }
  243. indicesTop++
  244. } else {
  245. documentsPointer++
  246. }
  247. }
  248. if indicesTop != indicesPointer {
  249. switch indexer.initOptions.IndexType {
  250. case types.LocationsIndex:
  251. indices.locations = append(
  252. indices.locations[:indicesTop], indices.locations[indicesPointer:]...)
  253. case types.FrequenciesIndex:
  254. indices.frequencies = append(
  255. indices.frequencies[:indicesTop], indices.frequencies[indicesPointer:]...)
  256. }
  257. indices.docIds = append(
  258. indices.docIds[:indicesTop], indices.docIds[indicesPointer:]...)
  259. }
  260. if len(indices.docIds) == 0 {
  261. delete(indexer.tableLock.table, keyword)
  262. }
  263. }
  264. }
  265. // 查找包含全部搜索键(AND操作)的文档
  266. // 当docIds不为nil时仅从docIds指定的文档中查找
  267. func (indexer *Indexer) Lookup(
  268. tokens []string, labels []string, docIds map[uint64]bool, countDocsOnly bool) (docs []types.IndexedDocument, numDocs int) {
  269. if indexer.initialized == false {
  270. log.Fatal("索引器尚未初始化")
  271. }
  272. if indexer.numDocuments == 0 {
  273. return
  274. }
  275. numDocs = 0
  276. // 合并关键词和标签为搜索键
  277. keywords := make([]string, len(tokens)+len(labels))
  278. copy(keywords, tokens)
  279. copy(keywords[len(tokens):], labels)
  280. indexer.tableLock.RLock()
  281. defer indexer.tableLock.RUnlock()
  282. table := make([]*KeywordIndices, len(keywords))
  283. for i, keyword := range keywords {
  284. indices, found := indexer.tableLock.table[keyword]
  285. if !found {
  286. // 当反向索引表中无此搜索键时直接返回
  287. return
  288. } else {
  289. // 否则加入反向表中
  290. table[i] = indices
  291. }
  292. }
  293. // 当没有找到时直接返回
  294. if len(table) == 0 {
  295. return
  296. }
  297. // 归并查找各个搜索键出现文档的交集
  298. // 从后向前查保证先输出DocId较大文档
  299. indexPointers := make([]int, len(table))
  300. for iTable := 0; iTable < len(table); iTable++ {
  301. indexPointers[iTable] = indexer.getIndexLength(table[iTable]) - 1
  302. }
  303. // 平均文本关键词长度,用于计算BM25
  304. avgDocLength := indexer.totalTokenLength / float32(indexer.numDocuments)
  305. for ; indexPointers[0] >= 0; indexPointers[0]-- {
  306. // 以第一个搜索键出现的文档作为基准,并遍历其他搜索键搜索同一文档
  307. baseDocId := indexer.getDocId(table[0], indexPointers[0])
  308. if docIds != nil {
  309. if _, found := docIds[baseDocId]; !found {
  310. continue
  311. }
  312. }
  313. iTable := 1
  314. found := true
  315. for ; iTable < len(table); iTable++ {
  316. // 二分法比简单的顺序归并效率高,也有更高效率的算法,
  317. // 但顺序归并也许是更好的选择,考虑到将来需要用链表重新实现
  318. // 以避免反向表添加新文档时的写锁。
  319. // TODO: 进一步研究不同求交集算法的速度和可扩展性。
  320. position, foundBaseDocId := indexer.searchIndex(table[iTable],
  321. 0, indexPointers[iTable], baseDocId)
  322. if foundBaseDocId {
  323. indexPointers[iTable] = position
  324. } else {
  325. if position == 0 {
  326. // 该搜索键中所有的文档ID都比baseDocId大,因此已经没有
  327. // 继续查找的必要。
  328. return
  329. } else {
  330. // 继续下一indexPointers[0]的查找
  331. indexPointers[iTable] = position - 1
  332. found = false
  333. break
  334. }
  335. }
  336. }
  337. if found {
  338. if docState, ok := indexer.tableLock.docsState[baseDocId]; !ok || docState != 0 {
  339. continue
  340. }
  341. indexedDoc := types.IndexedDocument{}
  342. // 当为LocationsIndex时计算关键词紧邻距离
  343. if indexer.initOptions.IndexType == types.LocationsIndex {
  344. // 计算有多少关键词是带有距离信息的
  345. numTokensWithLocations := 0
  346. for i, t := range table[:len(tokens)] {
  347. if len(t.locations[indexPointers[i]]) > 0 {
  348. numTokensWithLocations++
  349. }
  350. }
  351. if numTokensWithLocations != len(tokens) {
  352. if !countDocsOnly {
  353. docs = append(docs, types.IndexedDocument{
  354. DocId: baseDocId,
  355. })
  356. }
  357. numDocs++
  358. break
  359. }
  360. // 计算搜索键在文档中的紧邻距离
  361. tokenProximity, tokenLocations := computeTokenProximity(table[:len(tokens)], &indexPointers, tokens)
  362. indexedDoc.TokenProximity = int32(tokenProximity)
  363. indexedDoc.TokenSnippetLocations = tokenLocations
  364. // 添加TokenLocations
  365. indexedDoc.TokenLocations = make([][]int, len(tokens))
  366. for i, t := range table[:len(tokens)] {
  367. indexedDoc.TokenLocations[i] = t.locations[indexPointers[i]]
  368. }
  369. }
  370. // 当为LocationsIndex或者FrequenciesIndex时计算BM25
  371. if indexer.initOptions.IndexType == types.LocationsIndex ||
  372. indexer.initOptions.IndexType == types.FrequenciesIndex {
  373. bm25 := float32(0)
  374. d := indexer.docTokenLengths[baseDocId]
  375. for i, t := range table[:len(tokens)] {
  376. var frequency float32
  377. if indexer.initOptions.IndexType == types.LocationsIndex {
  378. frequency = float32(len(t.locations[indexPointers[i]]))
  379. } else {
  380. frequency = t.frequencies[indexPointers[i]]
  381. }
  382. // 计算BM25
  383. if len(t.docIds) > 0 && frequency > 0 && indexer.initOptions.BM25Parameters != nil && avgDocLength != 0 {
  384. // 带平滑的idf
  385. idf := float32(math.Log2(float64(indexer.numDocuments)/float64(len(t.docIds)) + 1))
  386. k1 := indexer.initOptions.BM25Parameters.K1
  387. b := indexer.initOptions.BM25Parameters.B
  388. bm25 += idf * frequency * (k1 + 1) / (frequency + k1*(1-b+b*d/avgDocLength))
  389. }
  390. }
  391. indexedDoc.BM25 = float32(bm25)
  392. }
  393. indexedDoc.DocId = baseDocId
  394. if !countDocsOnly {
  395. docs = append(docs, indexedDoc)
  396. }
  397. numDocs++
  398. }
  399. }
  400. return
  401. }
  402. // 二分法查找indices中某文档的索引项
  403. // 第一个返回参数为找到的位置或需要插入的位置
  404. // 第二个返回参数标明是否找到
  405. func (indexer *Indexer) searchIndex(
  406. indices *KeywordIndices, start int, end int, docId uint64) (int, bool) {
  407. // 特殊情况
  408. if indexer.getIndexLength(indices) == start {
  409. return start, false
  410. }
  411. if docId < indexer.getDocId(indices, start) {
  412. return start, false
  413. } else if docId == indexer.getDocId(indices, start) {
  414. return start, true
  415. }
  416. if docId > indexer.getDocId(indices, end) {
  417. return end + 1, false
  418. } else if docId == indexer.getDocId(indices, end) {
  419. return end, true
  420. }
  421. // 二分
  422. var middle int
  423. for end-start > 1 {
  424. middle = (start + end) / 2
  425. if docId == indexer.getDocId(indices, middle) {
  426. return middle, true
  427. } else if docId > indexer.getDocId(indices, middle) {
  428. start = middle
  429. } else {
  430. end = middle
  431. }
  432. }
  433. return end, false
  434. }
  435. // 计算搜索键在文本中的紧邻距离
  436. //
  437. // 假定第 i 个搜索键首字节出现在文本中的位置为 P_i,长度 L_i
  438. // 紧邻距离计算公式为
  439. //
  440. // ArgMin(Sum(Abs(P_(i+1) - P_i - L_i)))
  441. //
  442. // 具体由动态规划实现,依次计算前 i 个 token 在每个出现位置的最优值。
  443. // 选定的 P_i 通过 tokenLocations 参数传回。
  444. func computeTokenProximity(table []*KeywordIndices, indexPointers *[]int, tokens []string) (
  445. minTokenProximity int, tokenLocations []int) {
  446. minTokenProximity = -1
  447. tokenLocations = make([]int, len(tokens))
  448. var (
  449. currentLocations, nextLocations []int
  450. currentMinValues, nextMinValues []int
  451. path [][]int
  452. )
  453. // 初始化路径数组
  454. path = make([][]int, len(tokens))
  455. for i := 1; i < len(path); i++ {
  456. path[i] = make([]int, len(table[i].locations[(*indexPointers)[i]]))
  457. }
  458. // 动态规划
  459. currentLocations = table[0].locations[(*indexPointers)[0]]
  460. currentMinValues = make([]int, len(currentLocations))
  461. for i := 1; i < len(tokens); i++ {
  462. nextLocations = table[i].locations[(*indexPointers)[i]]
  463. nextMinValues = make([]int, len(nextLocations))
  464. for j, _ := range nextMinValues {
  465. nextMinValues[j] = -1
  466. }
  467. var iNext int
  468. for iCurrent, currentLocation := range currentLocations {
  469. if currentMinValues[iCurrent] == -1 {
  470. continue
  471. }
  472. for iNext+1 < len(nextLocations) && nextLocations[iNext+1] < currentLocation {
  473. iNext++
  474. }
  475. update := func(from int, to int) {
  476. if to >= len(nextLocations) {
  477. return
  478. }
  479. value := currentMinValues[from] + utils.AbsInt(nextLocations[to]-currentLocations[from]-len(tokens[i-1]))
  480. if nextMinValues[to] == -1 || value < nextMinValues[to] {
  481. nextMinValues[to] = value
  482. path[i][to] = from
  483. }
  484. }
  485. // 最优解的状态转移只发生在左右最接近的位置
  486. update(iCurrent, iNext)
  487. update(iCurrent, iNext+1)
  488. }
  489. currentLocations = nextLocations
  490. currentMinValues = nextMinValues
  491. }
  492. // 找出最优解
  493. var cursor int
  494. for i, value := range currentMinValues {
  495. if value == -1 {
  496. continue
  497. }
  498. if minTokenProximity == -1 || value < minTokenProximity {
  499. minTokenProximity = value
  500. cursor = i
  501. }
  502. }
  503. // 从路径倒推出最优解的位置
  504. for i := len(tokens) - 1; i >= 0; i-- {
  505. if i != len(tokens)-1 {
  506. cursor = path[i+1][cursor]
  507. }
  508. tokenLocations[i] = table[i].locations[(*indexPointers)[i]][cursor]
  509. }
  510. return
  511. }