diff --git a/services/search/README.md b/services/search/README.md index 68ea8854aa..ee34f2ddea 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -27,6 +27,12 @@ The following optional settings can be set: * `SEARCH_ENGINE_BLEVE_DATA_PATH=/path/to/bleve/index` (default: `$OC_BASE_DATA_PATH/search`): Path to store the bleve index. +#### Memory + +Bleve stores the index in segments and merges smaller segments into larger ones in the background. A merge keeps the positions of each word across the whole new segment in memory, so it can briefly need much more memory than indexing or searching. How much depends on the size of the segments, and they grow with the index. + +This mostly matters with content extraction and many large text files, such as books or long documents. As a rough guide, keep about a tenth of the index size (the size of the bleve directory in the data path) free in addition to what OpenCloud otherwise uses, and expect that to grow along with the index. Merges run whenever bleve decides to, not only during a reindex. If the search service is killed for running out of memory while or after indexing, give it more memory. + ### OpenSearch OpenSearch is a distributed, RESTful search and analytics engine capable of addressing a growing number of use cases. diff --git a/services/search/pkg/bleve/backend.go b/services/search/pkg/bleve/backend.go index d8426e5435..a92fb7e16f 100644 --- a/services/search/pkg/bleve/backend.go +++ b/services/search/pkg/bleve/backend.go @@ -3,6 +3,7 @@ package bleve import ( "context" "math" + "sync" "time" "github.com/blevesearch/bleve/v2" @@ -34,12 +35,31 @@ type Backend struct { func NewBackend(index bleve.Index, queryCreator searchQuery.Creator[query.Query], log log.Logger) *Backend { return &Backend{ - index: index, + index: &serialIndex{bleveIndex: index}, queryCreator: queryCreator, log: log, } } +// bleveIndex lets serialIndex embed bleve.Index, whose Index method would clash +// with an embedded field of the same name +type bleveIndex = bleve.Index + +// serialIndex runs one batch at a time. bleve analyzes a batch through a pool of +// workers shared by all batches and keeps the whole analysis in memory until the +// batch is written, so batches running side by side (e.g. spaces reindexed +// concurrently) add little throughput but stack up their memory. +type serialIndex struct { + bleveIndex + batchMu sync.Mutex +} + +func (i *serialIndex) Batch(b *bleve.Batch) error { + i.batchMu.Lock() + defer i.batchMu.Unlock() + return i.bleveIndex.Batch(b) +} + // Search executes a search request operation within the index. // Returns a SearchIndexResponse object or an error. func (b *Backend) Search(_ context.Context, sir *searchService.SearchIndexRequest) (*searchService.SearchIndexResponse, error) { diff --git a/services/search/pkg/bleve/batch.go b/services/search/pkg/bleve/batch.go index 022e75d86d..b706f4c92c 100644 --- a/services/search/pkg/bleve/batch.go +++ b/services/search/pkg/bleve/batch.go @@ -16,11 +16,18 @@ import ( var _ search.BatchOperator = (*Batch)(nil) // ensure Batch implements BatchOperator +// maxBatchBytes caps the document data a batch collects before it is pushed. +// bleve analyzes a whole batch in memory before writing it, and with term +// vectors that costs more than ten times the text, so a document count alone +// does not bound memory once documents carry extracted content. +const maxBatchBytes = 16 * 1024 * 1024 + type Batch struct { - batch *bleve.Batch - index bleve.Index - size int - log log.Logger + batch *bleve.Batch + index bleve.Index + size int + maxBytes uint64 + log log.Logger } func NewBatch(index bleve.Index, size int) (*Batch, error) { @@ -29,9 +36,10 @@ func NewBatch(index bleve.Index, size int) (*Batch, error) { } return &Batch{ - batch: index.NewBatch(), - index: index, - size: size, + batch: index.NewBatch(), + index: index, + size: size, + maxBytes: maxBatchBytes, }, nil } @@ -49,6 +57,13 @@ func (b *Batch) indexResource(id string, r search.Resource) error { if err != nil { return err } + // push first if r would overflow the batch, so a batch holds at most + // maxBytes or a single larger document + if b.batch.Size() > 0 && b.batch.TotalDocsSize()+uint64(len(r.Content)) > b.maxBytes { + if err := b.Push(); err != nil { + return err + } + } return b.batch.Index(id, doc) } @@ -142,13 +157,18 @@ func (b *Batch) pushing(fn func(*search.Resource) error) func(*search.Resource) if err := fn(resource); err != nil { return err } - if b.batch.Size() >= b.size { + if b.full() { return b.Push() } return nil } } +// full reports whether the batch holds enough documents or enough data to be pushed +func (b *Batch) full() bool { + return b.batch.Size() >= b.size || b.batch.TotalDocsSize() >= b.maxBytes +} + func (b *Batch) Push() error { if b.batch.Size() == 0 { return nil @@ -168,7 +188,7 @@ func (b *Batch) withSizeLimit(f func() error) error { return err } - if b.batch.Size() >= b.size { + if b.full() { return b.Push() } diff --git a/services/search/pkg/bleve/batch_test.go b/services/search/pkg/bleve/batch_test.go new file mode 100644 index 0000000000..bf42ff787f --- /dev/null +++ b/services/search/pkg/bleve/batch_test.go @@ -0,0 +1,145 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package bleve_test + +import ( + "fmt" + "strings" + "sync" + "time" + + bleveSearch "github.com/blevesearch/bleve/v2" + sprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "github.com/opencloud-eu/opencloud/pkg/log" + "github.com/opencloud-eu/opencloud/services/search/pkg/bleve" + "github.com/opencloud-eu/opencloud/services/search/pkg/content" + bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve" + "github.com/opencloud-eu/opencloud/services/search/pkg/search" +) + +type bleveIndex = bleveSearch.Index + +// batchProbe records the batches written to the index and how many ran at the +// same time +type batchProbe struct { + bleveIndex + mu sync.Mutex + sizes []int + running int + peak int +} + +func (p *batchProbe) Batch(b *bleveSearch.Batch) error { + p.mu.Lock() + p.sizes = append(p.sizes, b.Size()) + p.running++ + p.peak = max(p.peak, p.running) + p.mu.Unlock() + + // long enough for batches pushed together to overlap if nothing serializes them + time.Sleep(20 * time.Millisecond) + err := p.bleveIndex.Batch(b) + + p.mu.Lock() + p.running-- + p.mu.Unlock() + return err +} + +var _ = Describe("Batch", func() { + var idx bleveSearch.Index + + BeforeEach(func() { + mapping, err := bleve.NewMapping() + Expect(err).ToNot(HaveOccurred()) + idx, err = bleveSearch.NewMemOnly(mapping) + Expect(err).ToNot(HaveOccurred()) + DeferCleanup(func() { Expect(idx.Close()).To(Succeed()) }) + }) + + file := func(i int, text string) search.Resource { + return search.Resource{ + ID: fmt.Sprintf("1$2!%d", i), + RootID: "1$2!2", + ParentID: "1$2!2", + Path: fmt.Sprintf("./f%d.txt", i), + Type: uint64(sprovider.ResourceType_RESOURCE_TYPE_FILE), + Document: content.Document{Name: fmt.Sprintf("f%d.txt", i), Content: text}, + } + } + + Describe("Upsert", func() { + It("pushes the batch before a document that would overflow it", func() { + batch, err := bleve.NewBatch(idx, 100) + Expect(err).ToNot(HaveOccurred()) + bleve.SetMaxBytes(batch, 64*1024) + text := strings.Repeat("lorem ipsum ", 40*1024/12) + + first := file(1, text) + Expect(batch.Upsert(first.ID, first)).To(Succeed()) + Expect(idx.DocCount()).To(BeZero()) + + second := file(2, text) + Expect(batch.Upsert(second.ID, second)).To(Succeed()) + Expect(idx.DocCount()).To(Equal(uint64(1))) + + Expect(batch.Push()).To(Succeed()) + Expect(idx.DocCount()).To(Equal(uint64(2))) + }) + + It("pushes a document larger than the limit in a batch of its own", func() { + probe := &batchProbe{bleveIndex: idx} + batch, err := bleve.NewBatch(probe, 100) + Expect(err).ToNot(HaveOccurred()) + bleve.SetMaxBytes(batch, 64*1024) + + for i, text := range []string{"lorem ipsum", strings.Repeat("lorem ipsum ", 100*1024/12), "lorem ipsum"} { + r := file(i, text) + Expect(batch.Upsert(r.ID, r)).To(Succeed()) + } + Expect(batch.Push()).To(Succeed()) + + Expect(probe.sizes).To(Equal([]int{1, 1, 1})) + }) + + It("collects small documents up to the count limit", func() { + batch, err := bleve.NewBatch(idx, 3) + Expect(err).ToNot(HaveOccurred()) + bleve.SetMaxBytes(batch, 64*1024) + + for i := range 2 { + r := file(i, "lorem ipsum") + Expect(batch.Upsert(r.ID, r)).To(Succeed()) + } + Expect(idx.DocCount()).To(BeZero()) + + r := file(2, "lorem ipsum") + Expect(batch.Upsert(r.ID, r)).To(Succeed()) + Expect(idx.DocCount()).To(Equal(uint64(3))) + }) + }) + + Describe("Push", func() { + It("runs one batch at a time when several are pushed together", func() { + probe := &batchProbe{bleveIndex: idx} + eng := bleve.NewBackend(probe, bleveQuery.DefaultCreator, log.NopLogger()) + + var wg sync.WaitGroup + for i := range 4 { + wg.Go(func() { + defer GinkgoRecover() + r := file(i, "lorem ipsum") + Expect(eng.Upsert(r.ID, r)).To(Succeed()) + }) + } + wg.Wait() + + Expect(probe.peak).To(Equal(1)) + Expect(eng.DocCount()).To(Equal(uint64(4))) + }) + }) +}) diff --git a/services/search/pkg/bleve/export_test.go b/services/search/pkg/bleve/export_test.go new file mode 100644 index 0000000000..f3a694d9f8 --- /dev/null +++ b/services/search/pkg/bleve/export_test.go @@ -0,0 +1,9 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package bleve + +// SetMaxBytes lowers the data limit of b, so tests don't need megabytes of content +func SetMaxBytes(b *Batch, n uint64) { + b.maxBytes = n +}