indexer.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. package core
  2. import (
  3. "log"
  4. "math"
  5. "sort"
  6. "sync"
  7. "github.com/huichen/wukong/types"
  8. "github.com/huichen/wukong/utils"
  9. )
  10. // 索引器
  11. type Indexer struct {
  12. // 从搜索键到文档列表的反向索引
  13. // 加了读写锁以保证读写安全
  14. tableLock struct {
  15. sync.RWMutex
  16. table map[string]*KeywordIndices
  17. docsState map[uint64]int // nil: 表示无状态记录,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. // 下面的切片是否为空,取决于初始化时IndexType的值
  41. docIds []uint64 // 全部类型都有
  42. frequencies []float32 // IndexType == FrequenciesIndex
  43. locations [][]int // IndexType == LocationsIndex
  44. }
  45. // 初始化索引器
  46. func (indexer *Indexer) Init(options types.IndexerInitOptions) {
  47. if indexer.initialized == true {
  48. log.Fatal("索引器不能初始化两次")
  49. }
  50. options.Init()
  51. indexer.initOptions = options
  52. indexer.initialized = true
  53. indexer.tableLock.table = make(map[string]*KeywordIndices)
  54. indexer.tableLock.docsState = make(map[uint64]int)
  55. indexer.addCacheLock.addCache = make([]*types.DocumentIndex, indexer.initOptions.DocCacheSize)
  56. indexer.removeCacheLock.removeCache = make([]uint64, indexer.initOptions.DocCacheSize*2)
  57. indexer.docTokenLengths = make(map[uint64]float32)
  58. }
  59. // 从KeywordIndices中得到第i个文档的DocId
  60. func (indexer *Indexer) getDocId(ti *KeywordIndices, i int) uint64 {
  61. return ti.docIds[i]
  62. }
  63. // 得到KeywordIndices中文档总数
  64. func (indexer *Indexer) getIndexLength(ti *KeywordIndices) int {
  65. return len(ti.docIds)
  66. }
  67. // 向 ADDCACHE 中加入一个文档
  68. func (indexer *Indexer) AddDocumentToCache(document *types.DocumentIndex, forceUpdate bool) {
  69. if indexer.initialized == false {
  70. log.Fatal("索引器尚未初始化")
  71. }
  72. indexer.addCacheLock.Lock()
  73. if document != nil {
  74. indexer.addCacheLock.addCache[indexer.addCacheLock.addCachePointer] = document
  75. indexer.addCacheLock.addCachePointer++
  76. }
  77. if indexer.addCacheLock.addCachePointer >= indexer.initOptions.DocCacheSize || forceUpdate {
  78. indexer.tableLock.Lock()
  79. position := 0
  80. for i := 0; i < indexer.addCacheLock.addCachePointer; i++ {
  81. docIndex := indexer.addCacheLock.addCache[i]
  82. if docState, ok := indexer.tableLock.docsState[docIndex.DocId]; ok && docState == 0 {
  83. // ok && docState == 0 表示存在于索引中,需先删除再添加
  84. if position != i {
  85. indexer.addCacheLock.addCache[position], indexer.addCacheLock.addCache[i] =
  86. indexer.addCacheLock.addCache[i], indexer.addCacheLock.addCache[position]
  87. }
  88. indexer.removeCacheLock.Lock()
  89. indexer.removeCacheLock.removeCache[indexer.removeCacheLock.removeCachePointer] =
  90. docIndex.DocId
  91. indexer.removeCacheLock.removeCachePointer++
  92. indexer.removeCacheLock.Unlock()
  93. indexer.tableLock.docsState[docIndex.DocId] = 1
  94. indexer.numDocuments--
  95. position++
  96. } else if !(ok && docState == 1) {
  97. // ok && docState == 1 表示等待删除
  98. indexer.tableLock.docsState[docIndex.DocId] = 2
  99. }
  100. }
  101. indexer.tableLock.Unlock()
  102. if indexer.RemoveDocumentToCache(0, forceUpdate) {
  103. // 只有当存在于索引表中的文档已被删除,其才可以重新加入到索引表中
  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. indexPointers := make(map[string]int, len(indexer.tableLock.table))
  123. // DocId 递增顺序遍历插入文档保证索引移动次数最少
  124. for i, document := range *documents {
  125. if i < len(*documents)-1 && (*documents)[i].DocId == (*documents)[i+1].DocId {
  126. // 如果有重复文档加入,因为稳定排序,只加入最后一个
  127. continue
  128. }
  129. if docState, ok := indexer.tableLock.docsState[document.DocId]; ok && docState == 1 {
  130. // 如果此时 docState 仍为 1,说明该文档需被删除
  131. continue
  132. }
  133. // 更新文档关键词总长度
  134. if document.TokenLength != 0 {
  135. indexer.docTokenLengths[document.DocId] = float32(document.TokenLength)
  136. indexer.totalTokenLength += document.TokenLength
  137. }
  138. docIdIsNew := true
  139. for _, keyword := range document.Keywords {
  140. indices, foundKeyword := indexer.tableLock.table[keyword.Text]
  141. if !foundKeyword {
  142. // 如果没找到该搜索键则加入
  143. ti := KeywordIndices{}
  144. switch indexer.initOptions.IndexType {
  145. case types.LocationsIndex:
  146. ti.locations = [][]int{keyword.Starts}
  147. case types.FrequenciesIndex:
  148. ti.frequencies = []float32{keyword.Frequency}
  149. }
  150. ti.docIds = []uint64{document.DocId}
  151. indexer.tableLock.table[keyword.Text] = &ti
  152. continue
  153. }
  154. // 查找应该插入的位置,且索引一定不存在
  155. position, _ := indexer.searchIndex(
  156. indices, indexPointers[keyword.Text], indexer.getIndexLength(indices)-1, document.DocId)
  157. indexPointers[keyword.Text] = position
  158. switch indexer.initOptions.IndexType {
  159. case types.LocationsIndex:
  160. indices.locations = append(indices.locations, []int{})
  161. copy(indices.locations[position+1:], indices.locations[position:])
  162. indices.locations[position] = keyword.Starts
  163. case types.FrequenciesIndex:
  164. indices.frequencies = append(indices.frequencies, float32(0))
  165. copy(indices.frequencies[position+1:], indices.frequencies[position:])
  166. indices.frequencies[position] = keyword.Frequency
  167. }
  168. indices.docIds = append(indices.docIds, 0)
  169. copy(indices.docIds[position+1:], indices.docIds[position:])
  170. indices.docIds[position] = document.DocId
  171. }
  172. // 更新文章状态和总数
  173. if docIdIsNew {
  174. indexer.tableLock.docsState[document.DocId] = 0
  175. indexer.numDocuments++
  176. }
  177. }
  178. }
  179. // 向 REMOVECACHE 中加入一个待删除文档
  180. // 返回值表示文档是否在索引表中被删除
  181. func (indexer *Indexer) RemoveDocumentToCache(docId uint64, forceUpdate bool) bool {
  182. if indexer.initialized == false {
  183. log.Fatal("索引器尚未初始化")
  184. }
  185. indexer.removeCacheLock.Lock()
  186. if docId != 0 {
  187. indexer.tableLock.Lock()
  188. if docState, ok := indexer.tableLock.docsState[docId]; ok && docState == 0 {
  189. indexer.removeCacheLock.removeCache[indexer.removeCacheLock.removeCachePointer] = docId
  190. indexer.removeCacheLock.removeCachePointer++
  191. indexer.tableLock.docsState[docId] = 1
  192. indexer.numDocuments--
  193. } else if !ok {
  194. // 删除一个不存在或者等待加入的文档
  195. indexer.tableLock.docsState[docId] = 1
  196. }
  197. indexer.tableLock.Unlock()
  198. }
  199. if indexer.removeCacheLock.removeCachePointer > 0 &&
  200. (indexer.removeCacheLock.removeCachePointer >= indexer.initOptions.DocCacheSize ||
  201. forceUpdate) {
  202. removeCachedDocuments := indexer.removeCacheLock.removeCache[:indexer.removeCacheLock.removeCachePointer]
  203. indexer.removeCacheLock.removeCachePointer = 0
  204. indexer.removeCacheLock.Unlock()
  205. sort.Sort(removeCachedDocuments)
  206. indexer.RemoveDocuments(&removeCachedDocuments)
  207. return true
  208. }
  209. indexer.removeCacheLock.Unlock()
  210. return false
  211. }
  212. // 向反向索引表中删除 REMOVECACHE 中所有文档
  213. func (indexer *Indexer) RemoveDocuments(documents *types.DocumentsId) {
  214. if indexer.initialized == false {
  215. log.Fatal("索引器尚未初始化")
  216. }
  217. indexer.tableLock.Lock()
  218. defer indexer.tableLock.Unlock()
  219. // 更新文档关键词总长度,删除文档状态
  220. for _, docId := range *documents {
  221. indexer.totalTokenLength -= indexer.docTokenLengths[docId]
  222. delete(indexer.docTokenLengths, docId)
  223. delete(indexer.tableLock.docsState, docId)
  224. }
  225. for keyword, indices := range indexer.tableLock.table {
  226. indicesTop, indicesPointer := 0, 0
  227. documentsPointer := sort.Search(
  228. len(*documents), func(i int) bool { return (*documents)[i] >= indices.docIds[0] })
  229. // 双指针扫描,进行批量删除操作
  230. for ; documentsPointer < len(*documents) &&
  231. indicesPointer < indexer.getIndexLength(indices); indicesPointer++ {
  232. if indices.docIds[indicesPointer] < (*documents)[documentsPointer] {
  233. if indicesTop != indicesPointer {
  234. switch indexer.initOptions.IndexType {
  235. case types.LocationsIndex:
  236. indices.locations[indicesTop] = indices.locations[indicesPointer]
  237. case types.FrequenciesIndex:
  238. indices.frequencies[indicesTop] = indices.frequencies[indicesPointer]
  239. }
  240. indices.docIds[indicesTop] = indices.docIds[indicesPointer]
  241. }
  242. indicesTop++
  243. } else {
  244. documentsPointer++
  245. }
  246. }
  247. if indicesTop != indicesPointer {
  248. switch indexer.initOptions.IndexType {
  249. case types.LocationsIndex:
  250. indices.locations = append(
  251. indices.locations[:indicesTop], indices.locations[indicesPointer:]...)
  252. case types.FrequenciesIndex:
  253. indices.frequencies = append(
  254. indices.frequencies[:indicesTop], indices.frequencies[indicesPointer:]...)
  255. }
  256. indices.docIds = append(
  257. indices.docIds[:indicesTop], indices.docIds[indicesPointer:]...)
  258. }
  259. if len(indices.docIds) == 0 {
  260. delete(indexer.tableLock.table, keyword)
  261. }
  262. }
  263. }
  264. // 查找包含全部搜索键(AND操作)的文档
  265. // 当docIds不为nil时仅从docIds指定的文档中查找
  266. func (indexer *Indexer) Lookup(
  267. tokens []string, labels []string, docIds map[uint64]bool, countDocsOnly bool) (docs []types.IndexedDocument, numDocs int) {
  268. if indexer.initialized == false {
  269. log.Fatal("索引器尚未初始化")
  270. }
  271. if indexer.numDocuments == 0 {
  272. return
  273. }
  274. numDocs = 0
  275. // 合并关键词和标签为搜索键
  276. keywords := make([]string, len(tokens)+len(labels))
  277. copy(keywords, tokens)
  278. copy(keywords[len(tokens):], labels)
  279. indexer.tableLock.RLock()
  280. defer indexer.tableLock.RUnlock()
  281. table := make([]*KeywordIndices, len(keywords))
  282. for i, keyword := range keywords {
  283. indices, found := indexer.tableLock.table[keyword]
  284. if !found {
  285. // 当反向索引表中无此搜索键时直接返回
  286. return
  287. } else {
  288. // 否则加入反向表中
  289. table[i] = indices
  290. }
  291. }
  292. // 当没有找到时直接返回
  293. if len(table) == 0 {
  294. return
  295. }
  296. // 归并查找各个搜索键出现文档的交集
  297. // 从后向前查保证先输出DocId较大文档
  298. indexPointers := make([]int, len(table))
  299. for iTable := 0; iTable < len(table); iTable++ {
  300. indexPointers[iTable] = indexer.getIndexLength(table[iTable]) - 1
  301. }
  302. // 平均文本关键词长度,用于计算BM25
  303. avgDocLength := indexer.totalTokenLength / float32(indexer.numDocuments)
  304. for ; indexPointers[0] >= 0; indexPointers[0]-- {
  305. // 以第一个搜索键出现的文档作为基准,并遍历其他搜索键搜索同一文档
  306. baseDocId := indexer.getDocId(table[0], indexPointers[0])
  307. if docIds != nil {
  308. if _, found := docIds[baseDocId]; !found {
  309. continue
  310. }
  311. }
  312. iTable := 1
  313. found := true
  314. for ; iTable < len(table); iTable++ {
  315. // 二分法比简单的顺序归并效率高,也有更高效率的算法,
  316. // 但顺序归并也许是更好的选择,考虑到将来需要用链表重新实现
  317. // 以避免反向表添加新文档时的写锁。
  318. // TODO: 进一步研究不同求交集算法的速度和可扩展性。
  319. position, foundBaseDocId := indexer.searchIndex(table[iTable],
  320. 0, indexPointers[iTable], baseDocId)
  321. if foundBaseDocId {
  322. indexPointers[iTable] = position
  323. } else {
  324. if position == 0 {
  325. // 该搜索键中所有的文档ID都比baseDocId大,因此已经没有
  326. // 继续查找的必要。
  327. return
  328. } else {
  329. // 继续下一indexPointers[0]的查找
  330. indexPointers[iTable] = position - 1
  331. found = false
  332. break
  333. }
  334. }
  335. }
  336. if found {
  337. if docState, ok := indexer.tableLock.docsState[baseDocId]; !ok || docState != 0 {
  338. continue
  339. }
  340. indexedDoc := types.IndexedDocument{}
  341. // 当为LocationsIndex时计算关键词紧邻距离
  342. if indexer.initOptions.IndexType == types.LocationsIndex {
  343. // 计算有多少关键词是带有距离信息的
  344. numTokensWithLocations := 0
  345. for i, t := range table[:len(tokens)] {
  346. if len(t.locations[indexPointers[i]]) > 0 {
  347. numTokensWithLocations++
  348. }
  349. }
  350. if numTokensWithLocations != len(tokens) {
  351. if !countDocsOnly {
  352. docs = append(docs, types.IndexedDocument{
  353. DocId: baseDocId,
  354. })
  355. }
  356. numDocs++
  357. //当某个关键字对应多个文档且有lable关键字存在时,若直接break,将会丢失相当一部分搜索结果
  358. continue
  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. }