You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.3 KiB

  1. // Copyright 2016 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package indexer
  5. import (
  6. "fmt"
  7. "strconv"
  8. "github.com/blevesearch/bleve"
  9. "github.com/blevesearch/bleve/analysis/token/unicodenorm"
  10. "github.com/blevesearch/bleve/mapping"
  11. "github.com/blevesearch/bleve/search/query"
  12. )
  13. // indexerID a bleve-compatible unique identifier for an integer id
  14. func indexerID(id int64) string {
  15. return strconv.FormatInt(id, 36)
  16. }
  17. // idOfIndexerID the integer id associated with an indexer id
  18. func idOfIndexerID(indexerID string) (int64, error) {
  19. id, err := strconv.ParseInt(indexerID, 36, 64)
  20. if err != nil {
  21. return 0, fmt.Errorf("Unexpected indexer ID %s: %v", indexerID, err)
  22. }
  23. return id, nil
  24. }
  25. // numericEqualityQuery a numeric equality query for the given value and field
  26. func numericEqualityQuery(value int64, field string) *query.NumericRangeQuery {
  27. f := float64(value)
  28. tru := true
  29. q := bleve.NewNumericRangeInclusiveQuery(&f, &f, &tru, &tru)
  30. q.SetField(field)
  31. return q
  32. }
  33. func newMatchPhraseQuery(matchPhrase, field, analyzer string) *query.MatchPhraseQuery {
  34. q := bleve.NewMatchPhraseQuery(matchPhrase)
  35. q.FieldVal = field
  36. q.Analyzer = analyzer
  37. return q
  38. }
  39. const unicodeNormalizeName = "unicodeNormalize"
  40. func addUnicodeNormalizeTokenFilter(m *mapping.IndexMappingImpl) error {
  41. return m.AddCustomTokenFilter(unicodeNormalizeName, map[string]interface{}{
  42. "type": unicodenorm.Name,
  43. "form": unicodenorm.NFC,
  44. })
  45. }
  46. // Update represents an update to an indexer
  47. type Update interface {
  48. addToBatch(batch *bleve.Batch) error
  49. }
  50. const maxBatchSize = 16
  51. // Batch batch of indexer updates that automatically flushes once it
  52. // reaches a certain size
  53. type Batch struct {
  54. batch *bleve.Batch
  55. index bleve.Index
  56. }
  57. // Add add update to batch, possibly flushing
  58. func (batch *Batch) Add(update Update) error {
  59. if err := update.addToBatch(batch.batch); err != nil {
  60. return err
  61. }
  62. return batch.flushIfFull()
  63. }
  64. func (batch *Batch) flushIfFull() error {
  65. if batch.batch.Size() >= maxBatchSize {
  66. return batch.Flush()
  67. }
  68. return nil
  69. }
  70. // Flush manually flush the batch, regardless of its size
  71. func (batch *Batch) Flush() error {
  72. if err := batch.index.Batch(batch.batch); err != nil {
  73. return err
  74. }
  75. batch.batch.Reset()
  76. return nil
  77. }