indexer.go 18 KB

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