forked from
tangled.org/core
Monorepo for Tangled — https://tangled.org
1// Copyright 2021 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
3
4package bleveutil
5
6import (
7 "github.com/blevesearch/bleve/v2"
8)
9
10// FlushingBatch is a batch of operations that automatically flushes to the
11// underlying index once it reaches a certain size.
12type FlushingBatch struct {
13 maxBatchSize int
14 batch *bleve.Batch
15 index bleve.Index
16}
17
18// NewFlushingBatch creates a new flushing batch for the specified index. Once
19// the number of operations in the batch reaches the specified limit, the batch
20// automatically flushes its operations to the index.
21func NewFlushingBatch(index bleve.Index, maxBatchSize int) *FlushingBatch {
22 return &FlushingBatch{
23 maxBatchSize: maxBatchSize,
24 batch: index.NewBatch(),
25 index: index,
26 }
27}
28
29// Index add a new index to batch
30func (b *FlushingBatch) Index(id string, data any) error {
31 if err := b.batch.Index(id, data); err != nil {
32 return err
33 }
34 return b.flushIfFull()
35}
36
37// Delete add a delete index to batch
38func (b *FlushingBatch) Delete(id string) error {
39 b.batch.Delete(id)
40 return b.flushIfFull()
41}
42
43func (b *FlushingBatch) flushIfFull() error {
44 if b.batch.Size() < b.maxBatchSize {
45 return nil
46 }
47 return b.Flush()
48}
49
50// Flush submit the batch and create a new one
51func (b *FlushingBatch) Flush() error {
52 err := b.index.Batch(b.batch)
53 if err != nil {
54 return err
55 }
56 b.batch = b.index.NewBatch()
57 return nil
58}