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