mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-12-05 05:43:36 -05:00
350 lines
9.7 KiB
Go
350 lines
9.7 KiB
Go
package bleve
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/blevesearch/bleve/v2"
|
|
"github.com/blevesearch/bleve/v2/index/scorch"
|
|
"github.com/blevesearch/bleve/v2/search/query"
|
|
storageProvider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
|
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
|
|
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
|
|
"github.com/opencloud-eu/reva/v3/pkg/utils"
|
|
"google.golang.org/protobuf/types/known/timestamppb"
|
|
|
|
"github.com/opencloud-eu/opencloud/pkg/log"
|
|
"github.com/opencloud-eu/opencloud/services/search/pkg/aggregation"
|
|
"github.com/opencloud-eu/opencloud/services/search/pkg/mapping"
|
|
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
|
|
|
|
searchMessage "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
|
|
searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
|
|
searchQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query"
|
|
bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve"
|
|
)
|
|
|
|
const defaultBatchSize = 50
|
|
|
|
var _ search.Engine = (*Backend)(nil) // ensure Backend implements Engine
|
|
|
|
type Backend struct {
|
|
index *serialIndex
|
|
log log.Logger
|
|
optimizeMu sync.Mutex
|
|
}
|
|
|
|
func NewBackend(index bleve.Index, log log.Logger) *Backend {
|
|
return &Backend{
|
|
index: &serialIndex{bleveIndex: index},
|
|
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.
|
|
func (b *Backend) Search(ctx context.Context, sir *search.IndexQuery) (*search.IndexResult, error) {
|
|
createdQuery, err := bleveQuery.Compiler{}.Compile(searchQuery.Normalize(sir.Query, searchQuery.ResolveField))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
q := bleve.NewConjunctionQuery(
|
|
// Skip documents that have been marked as deleted
|
|
&query.BoolFieldQuery{
|
|
Bool: false,
|
|
FieldVal: "Deleted",
|
|
},
|
|
createdQuery,
|
|
)
|
|
|
|
filters, err := aggregationFilterQueries(sir.AggregationFilters)
|
|
if err != nil {
|
|
return nil, errtypes.BadRequest(err.Error())
|
|
}
|
|
q.Conjuncts = append(q.Conjuncts, filters...)
|
|
|
|
if sir.Ref != nil {
|
|
q.Conjuncts = append(
|
|
q.Conjuncts,
|
|
&query.TermQuery{
|
|
FieldVal: "RootID",
|
|
Term: storagespace.FormatResourceID(
|
|
&storageProvider.ResourceId{
|
|
StorageId: sir.Ref.GetResourceId().GetStorageId(),
|
|
SpaceId: sir.Ref.GetResourceId().GetSpaceId(),
|
|
OpaqueId: sir.Ref.GetResourceId().GetOpaqueId(),
|
|
},
|
|
),
|
|
},
|
|
)
|
|
// Scope below the space root: restrict at query level so totals and
|
|
// paging respect the path too. The folder term matches the folder and
|
|
// its descendants (see PathAnalyzer).
|
|
if requestedPath := utils.MakeRelativePath(sir.Ref.Path); requestedPath != "." {
|
|
q.Conjuncts = append(q.Conjuncts, &query.TermQuery{FieldVal: "Path", Term: requestedPath})
|
|
}
|
|
}
|
|
|
|
bleveReq := bleve.NewSearchRequest(q)
|
|
bleveReq.Highlight = bleve.NewHighlight()
|
|
// ties by id, like the cross-space merge
|
|
bleveReq.SortBy([]string{"-_score", "_id"})
|
|
bleveReq.Size = search.EnginePageSize(sir.PageSize, math.MaxInt)
|
|
|
|
collector, err := newAggCollector(sir.Aggregations)
|
|
if err != nil {
|
|
return nil, errtypes.BadRequest(err.Error())
|
|
}
|
|
if collector != nil {
|
|
ctx = collector.withContext(ctx)
|
|
}
|
|
|
|
bleveReq.Fields = []string{"*"}
|
|
res, err := b.index.SearchInContext(ctx, bleveReq)
|
|
if errors.Is(err, aggregation.ErrTooManyBuckets) {
|
|
return nil, errtypes.BadRequest(err.Error())
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
matches := make([]*searchMessage.Match, 0, len(res.Hits))
|
|
totalMatches := res.Total
|
|
for _, hit := range res.Hits {
|
|
rootID, err := storagespace.ParseID(getFieldValue[string](hit.Fields, "RootID"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
rID, err := storagespace.ParseID(getFieldValue[string](hit.Fields, "ID"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
pID, _ := storagespace.ParseID(getFieldValue[string](hit.Fields, "ParentID"))
|
|
match := &searchMessage.Match{
|
|
Score: float32(hit.Score),
|
|
Entity: &searchMessage.Entity{
|
|
Ref: &searchMessage.Reference{
|
|
ResourceId: resourceIDtoSearchID(rootID),
|
|
Path: getFieldValue[string](hit.Fields, "Path"),
|
|
},
|
|
Id: resourceIDtoSearchID(rID),
|
|
Name: getFieldValue[string](hit.Fields, "Name"),
|
|
ParentId: resourceIDtoSearchID(pID),
|
|
Size: uint64(getFieldValue[float64](hit.Fields, "Size")),
|
|
Type: uint64(getFieldValue[float64](hit.Fields, "Type")),
|
|
MimeType: getFieldValue[string](hit.Fields, "MimeType"),
|
|
Deleted: getFieldValue[bool](hit.Fields, "Deleted"),
|
|
Tags: getFieldSliceValue[string](hit.Fields, "Tags"),
|
|
Favorites: getFieldSliceValue[string](hit.Fields, "Favorites"),
|
|
Highlights: getFragmentValue(hit.Fragments, "Content", 0),
|
|
Audio: hitToFacet[searchMessage.Audio](hit.Fields, "audio"),
|
|
Image: hitToFacet[searchMessage.Image](hit.Fields, "image"),
|
|
Location: hitToFacet[searchMessage.GeoCoordinates](hit.Fields, "location"),
|
|
Photo: hitToFacet[searchMessage.Photo](hit.Fields, "photo"),
|
|
Video: hitToFacet[searchMessage.Video](hit.Fields, "video"),
|
|
MotionPhoto: hitToFacet[searchMessage.MotionPhoto](hit.Fields, "motionPhoto"),
|
|
LivePhoto: hitToFacet[searchMessage.LivePhoto](hit.Fields, "livePhoto"),
|
|
},
|
|
}
|
|
|
|
if mtime, err := time.Parse(time.RFC3339, getFieldValue[string](hit.Fields, "Mtime")); err == nil {
|
|
match.Entity.LastModifiedTime = ×tamppb.Timestamp{Seconds: mtime.Unix(), Nanos: int32(mtime.Nanosecond())}
|
|
}
|
|
|
|
matches = append(matches, match)
|
|
}
|
|
|
|
var aggregations []*searchService.AggregationResult
|
|
if collector != nil {
|
|
aggregations = collector.results()
|
|
if err := aggregation.CheckBuckets(aggregations); err != nil {
|
|
return nil, errtypes.BadRequest(err.Error())
|
|
}
|
|
}
|
|
|
|
return &search.IndexResult{
|
|
Matches: matches,
|
|
TotalMatches: int32(totalMatches),
|
|
Aggregations: aggregations,
|
|
}, nil
|
|
}
|
|
|
|
func (b *Backend) Get(_ context.Context, id string) (*search.Resource, error) {
|
|
return searchResourceByID(id, b.index)
|
|
}
|
|
|
|
// Update holds the batch lock from the read to the write, so a batch pushed in
|
|
// between is not overwritten; a batch built before the update and pushed after
|
|
// it still writes the tags it read
|
|
func (b *Backend) Update(_ context.Context, id string, u search.MetadataUpdate) error {
|
|
b.index.batchMu.Lock()
|
|
defer b.index.batchMu.Unlock()
|
|
|
|
r, err := searchResourceByID(id, b.index)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r.Tags = u.Tags
|
|
r.Favorites = u.Favorites
|
|
|
|
doc, err := mapping.PrepareForIndex(r, r.SearchFieldOverrides())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
batch := b.index.NewBatch()
|
|
err = batch.Index(id, doc)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return b.index.bleveIndex.Batch(batch)
|
|
}
|
|
|
|
func (b *Backend) DocCount() (uint64, error) {
|
|
return b.index.DocCount()
|
|
}
|
|
|
|
// Optimize merges all segments into one while the index stays in use
|
|
func (b *Backend) Optimize(ctx context.Context) error {
|
|
// scorch refuses a second merge with an error only its message tells apart
|
|
if !b.optimizeMu.TryLock() {
|
|
return search.ErrOptimizeInProgress
|
|
}
|
|
defer b.optimizeMu.Unlock()
|
|
|
|
advanced, err := b.index.Advanced()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s, ok := advanced.(*scorch.Scorch)
|
|
if !ok {
|
|
return fmt.Errorf("%w: %T", search.ErrOptimizeUnsupported, advanced)
|
|
}
|
|
// a nil plan merges into a single segment. a failing merge is retried by
|
|
// scorch without end and never returns, only cancelling ctx ends the wait
|
|
err = s.ForceMerge(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// scorch reports a cancelled merge as done, and so a closed index
|
|
return ctx.Err()
|
|
}
|
|
|
|
func (b *Backend) Upsert(id string, r search.Resource) error {
|
|
batch, err := b.NewBatch(defaultBatchSize)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := batch.Upsert(id, r); err != nil {
|
|
return err
|
|
}
|
|
|
|
return batch.Push()
|
|
}
|
|
|
|
func (b *Backend) Move(id, parentID, targetPath string) error {
|
|
batch, err := b.NewBatch(defaultBatchSize)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := batch.Move(id, parentID, targetPath); err != nil {
|
|
return err
|
|
}
|
|
|
|
return batch.Push()
|
|
}
|
|
|
|
func (b *Backend) Delete(id string) error {
|
|
batch, err := b.NewBatch(defaultBatchSize)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := batch.Delete(id); err != nil {
|
|
return err
|
|
}
|
|
|
|
return batch.Push()
|
|
}
|
|
|
|
func (b *Backend) Restore(id string) error {
|
|
batch, err := b.NewBatch(defaultBatchSize)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := batch.Restore(id); err != nil {
|
|
return err
|
|
}
|
|
|
|
return batch.Push()
|
|
}
|
|
|
|
func (b *Backend) Purge(id string, onlyDeleted bool) error {
|
|
batch, err := b.NewBatch(defaultBatchSize)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := batch.Purge(id, onlyDeleted); err != nil {
|
|
return err
|
|
}
|
|
|
|
return batch.Push()
|
|
}
|
|
|
|
func (b *Backend) PurgeSpace(rootID string) error {
|
|
for {
|
|
req := bleve.NewSearchRequest(&query.TermQuery{FieldVal: "RootID", Term: rootID})
|
|
req.Size = defaultBatchSize
|
|
|
|
res, err := b.index.Search(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if res.Hits.Len() == 0 {
|
|
return nil
|
|
}
|
|
|
|
batch := b.index.NewBatch()
|
|
for _, hit := range res.Hits {
|
|
batch.Delete(hit.ID)
|
|
}
|
|
|
|
if err := b.index.Batch(batch); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
func (b *Backend) NewBatch(size int) (search.BatchOperator, error) {
|
|
return NewBatch(b.index, size)
|
|
}
|