Debian Codegraph @

related/inverted_index.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package related holds code to help finding related content.
15 package related
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "maps"
22 "math"
23 "sort"
24 "strings"
25 "sync"
26 "time"
27
28 "github.com/gohugoio/hugo/common/collections"
29 "github.com/gohugoio/hugo/common/hmaps"
30 "github.com/gohugoio/hugo/compare"
31 "github.com/gohugoio/hugo/markup/tableofcontents"
32 "github.com/spf13/cast"
33
34 "github.com/gohugoio/hugo/common/types"
35 "github.com/mitchellh/mapstructure"
36 )
37
38 const (
39 TypeBasic = "basic"
40 TypeFragments = "fragments"
41 )
42
43 var validTypes = map[string]bool{
44 TypeBasic: true,
45 TypeFragments: true,
46 }
47
48 var (
49 _ Keyword = (*StringKeyword)(nil)
50 zeroDate = time.Time{}
51
52 // DefaultConfig is the default related config.
53 DefaultConfig = Config{
54 Threshold: 80,
55 Indices: IndicesConfig{
56 IndexConfig{Name: "keywords", Weight: 100, Type: TypeBasic},
57 IndexConfig{Name: "date", Weight: 10, Type: TypeBasic},
58 },
59 }
60 )
61
62 // Config is the top level configuration element used to configure how to retrieve
63 // related content in Hugo.
64 type Config struct {
65 // Only include matches >= threshold, a normalized rank between 0 and 100.
66 Threshold int
67
68 // To get stable "See also" sections we, by default, exclude newer related pages.
69 IncludeNewer bool
70
71 // Will lower case all string values and queries to the indices.
72 // May get better results, but at a slight performance cost.
73 ToLower bool
74
75 Indices IndicesConfig
76 }
77
78 // Add adds a given index.
79 func (c *Config) Add(index IndexConfig) {
80 if c.ToLower {
81 index.ToLower = true
82 }
83 c.Indices = append(c.Indices, index)
84 }
85
86 func (c *Config) HasType(s string) bool {
87 for _, i := range c.Indices {
88 if i.Type == s {
89 return true
90 }
91 }
92 return false
93 }
94
95 // IndicesConfig holds a set of index configurations.
96 type IndicesConfig []IndexConfig
97
98 // IndexConfig configures an index.
99 type IndexConfig struct {
100 // The index name. This directly maps to a field or Param name.
101 Name string
102
103 // The index type.
104 Type string
105
106 // Enable to apply a type specific filter to the results.
107 // This is currently only used for the "fragments" type.
108 ApplyFilter bool
109
110 // Contextual pattern used to convert the Param value into a string.
111 // Currently only used for dates. Can be used to, say, bump posts in the same
112 // time frame when searching for related documents.
113 // For dates it follows Go's time.Format patterns, i.e.
114 // "2006" for YYYY and "200601" for YYYYMM.
115 Pattern string
116
117 // This field's weight when doing multi-index searches. Higher is "better".
118 Weight int
119
120 // A percentage (0-100) used to remove common keywords from the index.
121 // As an example, setting this to 50 will remove all keywords that are
122 // used in more than 50% of the documents in the index.
123 CardinalityThreshold int
124
125 // Will lower case all string values in and queries tothis index.
126 // May get better accurate results, but at a slight performance cost.
127 ToLower bool
128 }
129
130 // Document is the interface an indexable document in Hugo must fulfill.
131 type Document interface {
132 // RelatedKeywords returns a list of keywords for the given index config.
133 RelatedKeywords(cfg IndexConfig) ([]Keyword, error)
134
135 // When this document was or will be published.
136 PublishDate() time.Time
137
138 // Name is used as an tiebreaker if both Weight and PublishDate are
139 // the same.
140 Name() string
141 }
142
143 // FragmentProvider is an optional interface that can be implemented by a Document.
144 type FragmentProvider interface {
145 Fragments(context.Context) *tableofcontents.Fragments
146
147 // For internal use.
148 ApplyFilterToHeadings(context.Context, func(*tableofcontents.Heading) bool) Document
149 }
150
151 // InvertedIndex holds an inverted index, also sometimes named posting list, which
152 // lists, for every possible search term, the documents that contain that term.
153 type InvertedIndex struct {
154 cfg Config
155 index map[string]map[Keyword][]Document
156 // Counts the number of documents added to each index.
157 indexDocCount map[string]int
158
159 minWeight int
160 maxWeight int
161
162 // No modifications after this is set.
163 finalized bool
164 }
165
166 func (idx *InvertedIndex) getIndexCfg(name string) (IndexConfig, bool) {
167 for _, conf := range idx.cfg.Indices {
168 if conf.Name == name {
169 return conf, true
170 }
171 }
172
173 return IndexConfig{}, false
174 }
175
176 // NewInvertedIndex creates a new InvertedIndex.
177 // Documents to index must be added in Add.
178 func NewInvertedIndex(cfg Config) *InvertedIndex {
179 idx := &InvertedIndex{index: make(map[string]map[Keyword][]Document), indexDocCount: make(map[string]int), cfg: cfg}
180 for _, conf := range cfg.Indices {
181 idx.index[conf.Name] = make(map[Keyword][]Document)
182 if conf.Weight < idx.minWeight {
183 // By default, the weight scale starts at 0, but we allow
184 // negative weights.
185 idx.minWeight = conf.Weight
186 }
187 if conf.Weight > idx.maxWeight {
188 idx.maxWeight = conf.Weight
189 }
190 }
191 return idx
192 }
193
194 // Add documents to the inverted index.
195 // The value must support == and !=.
196 func (idx *InvertedIndex) Add(ctx context.Context, docs ...Document) error {
197 if idx.finalized {
198 panic("index is finalized")
199 }
200 var err error
201 for _, config := range idx.cfg.Indices {
202 if config.Weight == 0 {
203 // Disabled
204 continue
205 }
206 setm := idx.index[config.Name]
207
208 for _, doc := range docs {
209 var added bool
210 var words []Keyword
211 words, err = doc.RelatedKeywords(config)
212 if err != nil {
213 continue
214 }
215
216 for _, keyword := range words {
217 added = true
218 setm[keyword] = append(setm[keyword], doc)
219 }
220
221 if config.Type == TypeFragments {
222 if fp, ok := doc.(FragmentProvider); ok {
223 for _, fragment := range fp.Fragments(ctx).Identifiers {
224 added = true
225 setm[FragmentKeyword(fragment)] = append(setm[FragmentKeyword(fragment)], doc)
226 }
227 }
228 }
229
230 if added {
231 idx.indexDocCount[config.Name]++
232 }
233 }
234 }
235
236 return err
237 }
238
239 func (idx *InvertedIndex) Finalize(ctx context.Context) error {
240 if idx.finalized {
241 return nil
242 }
243
244 for _, config := range idx.cfg.Indices {
245 if config.CardinalityThreshold == 0 {
246 continue
247 }
248 setm := idx.index[config.Name]
249 if idx.indexDocCount[config.Name] == 0 {
250 continue
251 }
252
253 // Remove high cardinality terms.
254 numDocs := idx.indexDocCount[config.Name]
255 for k, v := range setm {
256 percentageWithKeyword := int(math.Ceil(float64(len(v)) / float64(numDocs) * 100))
257 if percentageWithKeyword > config.CardinalityThreshold {
258 delete(setm, k)
259 }
260 }
261
262 }
263
264 idx.finalized = true
265
266 return nil
267 }
268
269 // queryElement holds the index name and keywords that can be used to compose a
270 // search for related content.
271 type queryElement struct {
272 Index string
273 Keywords []Keyword
274 }
275
276 func newQueryElement(index string, keywords ...Keyword) queryElement {
277 return queryElement{Index: index, Keywords: keywords}
278 }
279
280 type ranks []*rank
281
282 type rank struct {
283 Doc Document
284 Weight int
285 Matches int
286 }
287
288 func (r *rank) addWeight(w int) {
289 r.Weight += w
290 r.Matches++
291 }
292
293 var rankPool = sync.Pool{
294 New: func() any {
295 return &rank{}
296 },
297 }
298
299 func getRank(doc Document, weight int) *rank {
300 r := rankPool.Get().(*rank)
301 r.Doc = doc
302 r.Weight = weight
303 r.Matches = 1
304 return r
305 }
306
307 func putRank(r *rank) {
308 rankPool.Put(r)
309 }
310
311 func (r ranks) Len() int { return len(r) }
312 func (r ranks) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
313 func (r ranks) Less(i, j int) bool {
314 if r[i].Weight == r[j].Weight {
315 if r[i].Doc.PublishDate() == r[j].Doc.PublishDate() {
316 return r[i].Doc.Name() < r[j].Doc.Name()
317 }
318 return r[i].Doc.PublishDate().After(r[j].Doc.PublishDate())
319 }
320 return r[i].Weight > r[j].Weight
321 }
322
323 // SearchOpts holds the options for a related search.
324 type SearchOpts struct {
325 // The Document to search for related content for.
326 Document Document
327
328 // The keywords to search for.
329 NamedSlices []types.KeyValues
330
331 // The indices to search in.
332 Indices []string
333
334 // Fragments holds a list of special keywords that is used
335 // for indices configured as type "fragments".
336 // This will match the fragment identifiers of the documents.
337 Fragments []string
338 }
339
340 // Search finds the documents matching any of the keywords in the given indices
341 // against query options in opts.
342 // The resulting document set will be sorted according to number of matches
343 // and the index weights, and any matches with a rank below the configured
344 // threshold (normalize to 0..100) will be removed.
345 // If an index name is provided, only that index will be queried.
346 func (idx *InvertedIndex) Search(ctx context.Context, opts SearchOpts) ([]Document, error) {
347 var (
348 queryElements []queryElement
349 configs IndicesConfig
350 )
351
352 if len(opts.Indices) == 0 {
353 configs = idx.cfg.Indices
354 } else {
355 configs = make(IndicesConfig, len(opts.Indices))
356 for i, indexName := range opts.Indices {
357 cfg, found := idx.getIndexCfg(indexName)
358 if !found {
359 return nil, fmt.Errorf("index %q not found", indexName)
360 }
361 configs[i] = cfg
362 }
363 }
364
365 for _, cfg := range configs {
366 var keywords []Keyword
367 if opts.Document != nil {
368 k, err := opts.Document.RelatedKeywords(cfg)
369 if err != nil {
370 return nil, err
371 }
372 keywords = append(keywords, k...)
373 }
374 if cfg.Type == TypeFragments {
375 for _, fragment := range opts.Fragments {
376 keywords = append(keywords, FragmentKeyword(fragment))
377 }
378 if opts.Document != nil {
379 if fp, ok := opts.Document.(FragmentProvider); ok {
380 for _, fragment := range fp.Fragments(ctx).Identifiers {
381 keywords = append(keywords, FragmentKeyword(fragment))
382 }
383 }
384 }
385
386 }
387 queryElements = append(queryElements, newQueryElement(cfg.Name, keywords...))
388 }
389 for _, slice := range opts.NamedSlices {
390 var keywords []Keyword
391 key := slice.KeyString()
392 if key == "" {
393 return nil, fmt.Errorf("index %q not valid", slice.Key)
394 }
395 conf, found := idx.getIndexCfg(key)
396 if !found {
397 return nil, fmt.Errorf("index %q not found", key)
398 }
399
400 for _, val := range slice.Values {
401 k, err := conf.ToKeywords(val)
402 if err != nil {
403 return nil, err
404 }
405 keywords = append(keywords, k...)
406 }
407 queryElements = append(queryElements, newQueryElement(conf.Name, keywords...))
408 }
409
410 if opts.Document != nil {
411 return idx.searchDate(ctx, opts.Document, opts.Document.PublishDate(), queryElements...)
412 }
413 return idx.search(ctx, queryElements...)
414 }
415
416 func (cfg IndexConfig) stringToKeyword(s string) Keyword {
417 if cfg.ToLower {
418 s = strings.ToLower(s)
419 }
420 if cfg.Type == TypeFragments {
421 return FragmentKeyword(s)
422 }
423 return StringKeyword(s)
424 }
425
426 // ToKeywords returns a Keyword slice of the given input.
427 func (cfg IndexConfig) ToKeywords(v any) ([]Keyword, error) {
428 var keywords []Keyword
429
430 switch vv := v.(type) {
431 case string:
432 keywords = append(keywords, cfg.stringToKeyword(vv))
433 case []string:
434 vvv := make([]Keyword, len(vv))
435 for i := range vvv {
436 vvv[i] = cfg.stringToKeyword(vv[i])
437 }
438 keywords = append(keywords, vvv...)
439 case []any:
440 return cfg.ToKeywords(cast.ToStringSlice(vv))
441 case time.Time:
442 layout := "2006"
443 if cfg.Pattern != "" {
444 layout = cfg.Pattern
445 }
446 keywords = append(keywords, StringKeyword(vv.Format(layout)))
447 case nil:
448 return keywords, nil
449 default:
450 return keywords, fmt.Errorf("indexing currently not supported for index %q and type %T", cfg.Name, vv)
451 }
452
453 return keywords, nil
454 }
455
456 func (idx *InvertedIndex) search(ctx context.Context, query ...queryElement) ([]Document, error) {
457 return idx.searchDate(ctx, nil, zeroDate, query...)
458 }
459
460 func (idx *InvertedIndex) searchDate(ctx context.Context, self Document, upperDate time.Time, query ...queryElement) ([]Document, error) {
461 matchm := make(map[Document]*rank, 200)
462 defer func() {
463 for _, r := range matchm {
464 putRank(r)
465 }
466 }()
467
468 applyDateFilter := !idx.cfg.IncludeNewer && !upperDate.IsZero()
469 var fragmentsFilter collections.SortedStringSlice
470
471 for _, el := range query {
472 setm, found := idx.index[el.Index]
473 if !found {
474 return []Document{}, fmt.Errorf("index for %q not found", el.Index)
475 }
476
477 config, found := idx.getIndexCfg(el.Index)
478 if !found {
479 return []Document{}, fmt.Errorf("index config for %q not found", el.Index)
480 }
481
482 for _, kw := range el.Keywords {
483 if docs, found := setm[kw]; found {
484 for _, doc := range docs {
485 if compare.Eq(doc, self) {
486 continue
487 }
488
489 if applyDateFilter {
490 // Exclude newer than the limit given
491 if doc.PublishDate().After(upperDate) {
492 continue
493 }
494 }
495
496 if config.Type == TypeFragments && config.ApplyFilter {
497 if fkw, ok := kw.(FragmentKeyword); ok {
498 fragmentsFilter = append(fragmentsFilter, string(fkw))
499 }
500 }
501
502 r, found := matchm[doc]
503 if !found {
504 r = getRank(doc, config.Weight)
505 matchm[doc] = r
506 } else {
507 r.addWeight(config.Weight)
508 }
509 }
510 }
511 }
512 }
513
514 if len(matchm) == 0 {
515 return []Document{}, nil
516 }
517
518 matches := make(ranks, 0, 100)
519
520 for _, v := range matchm {
521 avgWeight := v.Weight / v.Matches
522 weight := norm(avgWeight, idx.minWeight, idx.maxWeight)
523 threshold := idx.cfg.Threshold / v.Matches
524
525 if weight >= threshold {
526 matches = append(matches, v)
527 }
528 }
529
530 sort.Stable(matches)
531 sort.Strings(fragmentsFilter)
532
533 result := make([]Document, len(matches))
534
535 for i, m := range matches {
536 result[i] = m.Doc
537
538 if len(fragmentsFilter) > 0 {
539 if dp, ok := result[i].(FragmentProvider); ok {
540 result[i] = dp.ApplyFilterToHeadings(ctx, func(h *tableofcontents.Heading) bool {
541 return fragmentsFilter.Contains(h.ID)
542 })
543 }
544 }
545 }
546
547 return result, nil
548 }
549
550 // normalizes num to a number between 0 and 100.
551 func norm(num, min, max int) int {
552 if min > max {
553 panic("min > max")
554 }
555 return int(math.Floor((float64(num-min) / float64(max-min) * 100) + 0.5))
556 }
557
558 // DecodeConfig decodes a slice of map into Config.
559 func DecodeConfig(m hmaps.Params) (Config, error) {
560 if m == nil {
561 return Config{}, errors.New("no related config provided")
562 }
563
564 if len(m) == 0 {
565 return Config{}, errors.New("empty related config provided")
566 }
567
568 var c Config
569
570 if err := mapstructure.WeakDecode(m, &c); err != nil {
571 return c, err
572 }
573
574 if c.Threshold < 0 || c.Threshold > 100 {
575 return Config{}, errors.New("related threshold must be between 0 and 100")
576 }
577
578 if c.ToLower {
579 for i := range c.Indices {
580 c.Indices[i].ToLower = true
581 }
582 }
583 for i := range c.Indices {
584 // Lower case name.
585 c.Indices[i].Name = strings.ToLower(c.Indices[i].Name)
586
587 icfg := c.Indices[i]
588 if icfg.Type == "" {
589 c.Indices[i].Type = TypeBasic
590 }
591 if !validTypes[c.Indices[i].Type] {
592 return c, fmt.Errorf("invalid index type %q. Must be one of %v", c.Indices[i].Type, maps.Keys(validTypes))
593 }
594 if icfg.CardinalityThreshold < 0 || icfg.CardinalityThreshold > 100 {
595 return Config{}, errors.New("cardinalityThreshold threshold must be between 0 and 100")
596 }
597 }
598
599 return c, nil
600 }
601
602 // StringKeyword is a string search keyword.
603 type StringKeyword string
604
605 func (s StringKeyword) String() string {
606 return string(s)
607 }
608
609 // FragmentKeyword represents a document fragment.
610 type FragmentKeyword string
611
612 func (f FragmentKeyword) String() string {
613 return string(f)
614 }
615
616 // Keyword is the interface a keyword in the search index must implement.
617 type Keyword interface {
618 String() string
619 }
620
621 // StringsToKeywords converts the given slice of strings to a slice of Keyword.
622 func (cfg IndexConfig) StringsToKeywords(s ...string) []Keyword {
623 kw := make([]Keyword, len(s))
624
625 for i := range s {
626 kw[i] = cfg.stringToKeyword(s[i])
627 }
628
629 return kw
630 }