Debian Codegraph @

eutils/poster.go

raw
1 // ===========================================================================
2 //
3 // PUBLIC DOMAIN NOTICE
4 // National Center for Biotechnology Information (NCBI)
5 //
6 // This software/database is a "United States Government Work" under the
7 // terms of the United States Copyright Act. It was written as part of
8 // the author's official duties as a United States Government employee and
9 // thus cannot be copyrighted. This software/database is freely available
10 // to the public for use. The National Library of Medicine and the U.S.
11 // Government do not place any restriction on its use or reproduction.
12 // We would, however, appreciate having the NCBI and the author cited in
13 // any work or product based on this material.
14 //
15 // Although all reasonable efforts have been taken to ensure the accuracy
16 // and reliability of the software and data, the NLM and the U.S.
17 // Government do not and cannot warrant the performance or results that
18 // may be obtained by using this software or data. The NLM and the U.S.
19 // Government disclaim all warranties, express or implied, including
20 // warranties of performance, merchantability or fitness for any particular
21 // purpose.
22 //
23 // ===========================================================================
24 //
25 // File Name: poster.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "bytes"
36 "encoding/binary"
37 "fmt"
38 "github.com/klauspost/pgzip"
39 "github.com/surgebase/porter2"
40 "io"
41 "os"
42 "path/filepath"
43 "slices"
44 "strconv"
45 "strings"
46 "sync"
47 )
48
49 // POSTINGS FILE CREATION FROM MERGED INVERTED INDEX FILES
50
51 // UintsToVarints converts a set of integers to compact variable byte length unsigned integers
52 func UintsToVarints(vals []uint32) []byte {
53
54 var buffr []byte
55
56 appendOneVarint := func(val uint32) {
57
58 var buf []byte
59
60 buf = binary.AppendUvarint(buf, uint64(val))
61
62 // append variable byte length unsigned integer
63 buffr = append(buffr, buf...)
64 }
65
66 for _, val := range vals {
67 appendOneVarint(val)
68 }
69
70 return buffr
71 }
72
73 // VarintsToUints converts a set of variable byte length unsigned integers back to integers
74 func VarintsToUints(buf []byte) []uint32 {
75
76 var data []uint32
77
78 buffr := buf[:]
79
80 for len(buffr) > 0 {
81 val, n := binary.Uvarint(buffr)
82 if n < 1 {
83 break
84 }
85
86 data = append(data, uint32(val))
87
88 buffr = buffr[n:]
89 }
90
91 return data
92 }
93
94 // CreatePromoters creates term lists and postings files from merged inverted
95 // index files. All specified fields (e.g., "TITL TIAB YEAR TREE") are completed
96 // in a single scan of the inverted files.
97 //
98 // Postings consist of three files (.mst, .trm, and .pst) for all terms, plus
99 // two additional files (.uqi and .ofs) for terms with position data.
100 //
101 // Master index files (with .mst suffixes) contain pairs of 32-bit values, in
102 // little endian form, pointing to an offset into the term list (.trm files,
103 // saved as lines of text words), and an offset into the postings list (.pst
104 // files, containing 32-bit PMIDs).
105 //
106 // For position data, the .uqi file is parallel to the .pst file (one entry
107 // for each PMID associated with a given term), and contains 32-bit offsets
108 // to variable byte encoded paragraph position values.
109 //
110 // An extra entry at the end, pointing just past the end of data, allows
111 // the length of a term, or the size of a postings list, or the number of
112 // positions for a term in a given PMID, to be calculated as the difference
113 // between two adjacent pointers.
114 //
115 // The number of term positions per PMID is the term frequency (TF). (This
116 // now cannot be calculated without unpacking the variable length data.) The
117 // number of PMIDs per term is the document frequency (DF). All that remains
118 // for calculating TF-IDF term weights, which can support ranked retrieval,
119 // is the total number of live PubMed documents, which could easily be saved
120 // during indexing.
121 func CreatePromoters(prom, db, fields string, isLink bool, files []string) <-chan string {
122
123 if files == nil {
124 return nil
125 }
126
127 // obtain paths from environment variable(s)
128 postingsBase := GetLocalArchiveFolder(db, "Postings", true)
129
130 // check to make sure local postings directory is mounted
131 _, err := os.Stat(postingsBase)
132 if err != nil && os.IsNotExist(err) {
133 DisplayError("Local postings directory '%s' is not mounted", postingsBase)
134 os.Exit(1)
135 }
136
137 out := make(chan string, chanDepth)
138 if out == nil {
139 DisplayError("Unable to create promoter channel")
140 os.Exit(1)
141 }
142
143 flds := strings.Split(fields, " ")
144
145 // xmlPromoter saves records in a single set of term/posting files
146 xmlPromoter := func(wg *sync.WaitGroup, fileName string, out chan<- string) {
147
148 defer wg.Done()
149
150 f, err := os.Open(fileName)
151 if err != nil {
152 DisplayError("Unable to open input file '%s'", fileName)
153 os.Exit(1)
154 }
155
156 // close input file when all records have been processed
157 defer f.Close()
158
159 var in io.Reader
160
161 in = f
162
163 // if suffix is ".gz", use decompressor
164 iszip := false
165 if strings.HasSuffix(fileName, ".gz") {
166 iszip = true
167 }
168
169 if iszip {
170 brd := bufio.NewReader(f)
171 if brd == nil {
172 DisplayError("Unable to create buffered reader on '%s'", fileName)
173 os.Exit(1)
174 }
175 // using parallel pgzip for better performance on large files
176 zpr, err := pgzip.NewReader(brd)
177 if err != nil {
178 DisplayError("Unable to create decompressor on '%s'", fileName)
179 os.Exit(1)
180 }
181
182 // close decompressor when all records have been processed
183 defer zpr.Close()
184
185 // use decompressor for reading file
186 in = zpr
187 }
188
189 rdr := CreateXMLStreamer(in, nil)
190
191 if rdr == nil {
192 DisplayError("Unable to create XML Block Reader")
193 os.Exit(1)
194 }
195
196 getOnePosting := func(field, text string) (string, []int32, []string) {
197
198 var data []int32
199 var atts []string
200
201 term := ""
202
203 doPromote := func(tag, attr, content string) {
204
205 if tag == "InvKey" {
206
207 // term used for postings file name
208 term = content
209
210 term = strings.ToLower(term)
211
212 } else if tag == field {
213
214 // convert UID string to integer
215 if content == "" {
216 DisplayError("Empty UID for term '%s'", term)
217 return
218 }
219 value, err := strconv.ParseInt(content, 10, 32)
220 if err != nil {
221 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
222 return
223 }
224 data = append(data, int32(value))
225
226 if strings.HasPrefix(attr, "pos=\"") {
227 attr = attr[5:]
228 lgth := len(attr)
229 if lgth > 1 && attr[lgth-1] == '"' {
230 // "
231 attr = attr[:lgth-1]
232 }
233 atts = append(atts, attr)
234 }
235 }
236 }
237
238 // explore data fields
239 StreamValues(text[:], "InvDocument", doPromote)
240
241 if term == "" || len(data) < 1 {
242 return "", nil, nil
243 }
244
245 return term, data, atts
246 }
247
248 var (
249 termPos int32
250 postPos int32
251 ofstPos int32
252
253 indxList bytes.Buffer
254 termList bytes.Buffer
255 postList bytes.Buffer
256 uqidList bytes.Buffer
257 ofstList bytes.Buffer
258 )
259
260 retlength := len("\n")
261
262 addPositions := func(attr string) {
263
264 binary.Write(&uqidList, binary.LittleEndian, ofstPos)
265
266 var vals []uint32
267
268 atrs := strings.Split(attr, ",")
269 for _, att := range atrs {
270 if att == "" {
271 continue
272 }
273 value, err := strconv.ParseInt(att, 10, 32)
274 if err != nil {
275 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
276 return
277 }
278 vals = append(vals, uint32(value))
279 }
280
281 if len(vals) < 1 {
282 return
283 }
284
285 buffr := UintsToVarints(vals)
286 if len(buffr) < 1 {
287 return
288 }
289
290 // positions are variable byte length encoded unsigned integers
291 binary.Write(&ofstList, binary.LittleEndian, buffr)
292
293 ofstPos += int32(len(buffr))
294 }
295
296 addOnePosting := func(term string, data []int32, atts []string) {
297
298 tlength := len(term)
299 dlength := len(data)
300 alength := len(atts)
301
302 // write to term list buffer
303 termList.WriteString(term[:])
304 termList.WriteString("\n")
305
306 // write to postings buffer
307 binary.Write(&postList, binary.LittleEndian, data)
308
309 // write to master index buffer
310 binary.Write(&indxList, binary.LittleEndian, termPos)
311 binary.Write(&indxList, binary.LittleEndian, postPos)
312
313 postPos += int32(dlength * 4)
314 termPos += int32(tlength + retlength)
315
316 // return if no position attributes
317 if alength < 1 {
318 return
319 }
320 if dlength != alength {
321 fmt.Fprintf(os.Stderr, "dlength %d, alength %d\n", dlength, alength)
322 return
323 }
324
325 // write term offset list for each UID
326 for _, attr := range atts {
327 // now using variable byte length unsigned integers instead of uint16
328 addPositions(attr)
329 }
330 }
331
332 topOffMaster := func() {
333
334 // phantom term and postings positions eliminates special case calculation at end
335 binary.Write(&indxList, binary.LittleEndian, termPos)
336 binary.Write(&indxList, binary.LittleEndian, postPos)
337 binary.Write(&uqidList, binary.LittleEndian, ofstPos)
338 }
339
340 writeFile := func(dpath, fname string, bfr bytes.Buffer) {
341
342 fpath := filepath.Join(dpath, fname)
343 if fpath == "" {
344 return
345 }
346
347 // overwrites and truncates existing file
348 fl, err := os.Create(fpath)
349 if err != nil {
350 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
351 return
352 }
353
354 data := bfr.Bytes()
355
356 wrtr := bufio.NewWriter(fl)
357
358 _, err = wrtr.Write(data)
359 if err != nil {
360 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
361 }
362
363 wrtr.Flush()
364
365 // fl.Sync()
366
367 fl.Close()
368 }
369
370 writeFiveFiles := func(field, key string) {
371
372 dpath, ky := PostingPath(postingsBase, field, key, isLink)
373 if dpath == "" {
374 return
375 }
376
377 // make subdirectories, if necessary
378 err := os.MkdirAll(dpath, os.ModePerm)
379 if err != nil {
380 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
381 return
382 }
383
384 writeFile(dpath, ky+"."+field+".trm", termList)
385
386 writeFile(dpath, ky+"."+field+".pst", postList)
387
388 writeFile(dpath, ky+"."+field+".mst", indxList)
389
390 // only write position index and offset data files
391 // for fields with position attributes recorded
392 if uqidList.Len() > 0 && ofstList.Len() > 0 {
393
394 writeFile(dpath, ky+"."+field+".uqi", uqidList)
395
396 writeFile(dpath, ky+"."+field+".ofs", ofstList)
397 }
398 }
399
400 processOneField := func(field string, recs []string) {
401
402 tag := ""
403
404 for _, str := range recs {
405
406 term, data, atts := getOnePosting(field, str)
407
408 if term == "" || data == nil {
409 continue
410 }
411
412 // use first few characters of identifier
413 if tag == "" {
414 if isLink {
415 tag = term
416 if len(tag) > LinkLen {
417 tag = tag[:LinkLen]
418 }
419 } else {
420 tag = IdentifierKey(term)
421 }
422 }
423
424 addOnePosting(term, data, atts)
425 }
426
427 if tag != "" {
428
429 topOffMaster()
430 writeFiveFiles(field, tag)
431 }
432
433 // reset buffers and position counters
434 termPos = 0
435 postPos = 0
436 ofstPos = 0
437
438 indxList.Reset()
439 termList.Reset()
440 postList.Reset()
441 uqidList.Reset()
442 ofstList.Reset()
443 }
444
445 find := ParseIndex("InvKey")
446
447 currTag := ""
448 prevTag := ""
449
450 var arry []string
451
452 // read next array of InvDocument records with same key
453 PartitionXML("InvDocument", "", false, rdr,
454 func(str string) {
455
456 id := FindIdentifier(str[:], "InvDocument", find)
457 if id == "" {
458 return
459 }
460
461 if isLink {
462 if len(id) > LinkLen {
463 id = id[:LinkLen]
464 }
465 currTag = id
466 } else {
467 // use first few characters of identifier
468 currTag = IdentifierKey(id)
469 }
470
471 if prevTag != currTag {
472
473 // after IdentifierKey converts space to underscore,
474 // okay that xxx_ and xxx0 will be out of alphabetical order
475
476 // records with same identifier key as a unit
477 if prevTag != "" {
478 for _, fld := range flds {
479 processOneField(fld, arry)
480 }
481 out <- prevTag
482 }
483
484 // empty the slice
485 arry = nil
486 }
487
488 // collect next InvDocument record
489 arry = append(arry, str[:])
490
491 prevTag = currTag
492 })
493
494 if arry != nil {
495
496 // remaining records with last identifier key
497 for _, fld := range flds {
498 processOneField(fld, arry)
499 }
500 out <- prevTag
501 }
502 }
503
504 var wg sync.WaitGroup
505
506 // launch multiple promoter goroutines
507 for _, str := range files {
508 wg.Add(1)
509 go xmlPromoter(&wg, str, out)
510 }
511
512 // launch separate anonymous goroutine to wait until all promoters are done
513 go func() {
514 wg.Wait()
515 close(out)
516 }()
517
518 return out
519 }
520
521 // POSTINGS FILE LOW-LEVEL USAGE FUNCTIONS
522
523 // Master points to a term and to its postings data
524 type Master struct {
525 TermOffset int32
526 PostOffset int32
527 }
528
529 // Arrays contains postings lists and word offsets
530 type Arrays struct {
531 Data []int32
532 Ofst [][]uint32
533 Dist int
534 }
535
536 func commonOpenFile(dpath, fname string) (*os.File, int64) {
537
538 fpath := filepath.Join(dpath, fname)
539 if fpath == "" {
540 return nil, 0
541 }
542
543 inFile, err := os.Open(fpath)
544 if err != nil && os.IsNotExist(err) {
545 return nil, 0
546 }
547 if err != nil {
548 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
549 return nil, 0
550 }
551
552 fi, err := inFile.Stat()
553 if err != nil {
554 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
555 return nil, 0
556 }
557
558 size := fi.Size()
559
560 return inFile, size
561 }
562
563 func readMasterIndex(dpath, key, field string) []Master {
564
565 inFile, size := commonOpenFile(dpath, key+"."+field+".mst")
566 if inFile == nil {
567 return nil
568 }
569
570 defer inFile.Close()
571
572 data := make([]Master, size/8)
573 if data == nil || len(data) < 1 {
574 return nil
575 }
576
577 err := binary.Read(inFile, binary.LittleEndian, &data)
578 if err != nil {
579 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
580 return nil
581 }
582
583 return data
584 }
585
586 func readTermList(dpath, key, field string) []byte {
587
588 inFile, size := commonOpenFile(dpath, key+"."+field+".trm")
589 if inFile == nil {
590 return nil
591 }
592
593 defer inFile.Close()
594
595 data := make([]byte, size)
596 if data == nil || len(data) < 1 {
597 return nil
598 }
599
600 err := binary.Read(inFile, binary.LittleEndian, &data)
601 if err != nil {
602 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
603 return nil
604 }
605
606 return data
607 }
608
609 func readPostingData(dpath, key, field string, offset int32, size int32) []int32 {
610
611 inFile, _ := commonOpenFile(dpath, key+"."+field+".pst")
612 if inFile == nil {
613 return nil
614 }
615
616 defer inFile.Close()
617
618 data := make([]int32, size/4)
619 if data == nil || len(data) < 1 {
620 return nil
621 }
622
623 _, err := inFile.Seek(int64(offset), io.SeekStart)
624 if err != nil {
625 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
626 return nil
627 }
628
629 err = binary.Read(inFile, binary.LittleEndian, data)
630 if err != nil {
631 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
632 return nil
633 }
634
635 return data
636 }
637
638 func readPositionIndex(dpath, key, field string, offset int32, size int32) []int32 {
639
640 inFile, _ := commonOpenFile(dpath, key+"."+field+".uqi")
641 if inFile == nil {
642 return nil
643 }
644
645 defer inFile.Close()
646
647 data := make([]int32, size/4)
648 if data == nil || len(data) < 1 {
649 return nil
650 }
651
652 _, err := inFile.Seek(int64(offset), io.SeekStart)
653 if err != nil {
654 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
655 return nil
656 }
657
658 err = binary.Read(inFile, binary.LittleEndian, data)
659 if err != nil {
660 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
661 return nil
662 }
663
664 return data
665 }
666
667 func readOffsetData(dpath, key, field string, offset int32, size int32) []byte {
668
669 inFile, _ := commonOpenFile(dpath, key+"."+field+".ofs")
670 if inFile == nil {
671 return nil
672 }
673
674 defer inFile.Close()
675
676 data := make([]byte, size)
677 if data == nil {
678 return nil
679 }
680
681 _, err := inFile.Seek(int64(offset), io.SeekStart)
682 if err != nil {
683 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
684 return nil
685 }
686
687 err = binary.Read(inFile, binary.LittleEndian, data)
688 if err != nil {
689 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
690 return nil
691 }
692
693 return data
694 }
695
696 func readMasterIndexFuture(dpath, key, field string) <-chan []Master {
697
698 out := make(chan []Master, chanDepth)
699 if out == nil {
700 DisplayError("Unable to create master index channel")
701 os.Exit(1)
702 }
703
704 // masterIndexFuture asynchronously gets a master file and sends results through channel
705 masterIndexFuture := func(dpath, key, field string, out chan<- []Master) {
706
707 data := readMasterIndex(dpath, key, field)
708
709 out <- data
710
711 close(out)
712 }
713
714 // launch single future goroutine
715 go masterIndexFuture(dpath, key, field, out)
716
717 return out
718 }
719
720 func readTermListFuture(dpath, key, field string) <-chan []byte {
721
722 out := make(chan []byte, chanDepth)
723 if out == nil {
724 DisplayError("Unable to create term list channel")
725 os.Exit(1)
726 }
727
728 // termListFuture asynchronously gets a term list file and sends results through channel
729 termListFuture := func(dpath, key, field string, out chan<- []byte) {
730
731 data := readTermList(dpath, key, field)
732
733 out <- data
734
735 close(out)
736 }
737
738 // launch single future goroutine
739 go termListFuture(dpath, key, field, out)
740
741 return out
742 }
743
744 func getPostingIDs(prom, term, field string, simple, isLink bool) ([]int32, [][]uint32) {
745
746 dpath, key := PostingPath(prom, field, term, isLink)
747 if dpath == "" {
748 return nil, nil
749 }
750
751 // schedule asynchronous fetching
752 mi := readMasterIndexFuture(dpath, key, field)
753
754 tl := readTermListFuture(dpath, key, field)
755
756 // fetch master index and term list
757 indx := <-mi
758
759 trms := <-tl
760
761 if indx == nil || len(indx) < 1 {
762 return nil, nil
763 }
764
765 if trms == nil || len(trms) < 1 {
766 return nil, nil
767 }
768
769 // master index is padded with phantom term and postings position
770 numTerms := len(indx) - 1
771
772 strs := make([]string, numTerms)
773 if strs == nil || len(strs) < 1 {
774 return nil, nil
775 }
776
777 retlength := int32(len("\n"))
778
779 // populate array of strings from term list
780 for i, j := 0, 1; i < numTerms; i++ {
781 from := indx[i].TermOffset
782 to := indx[j].TermOffset - retlength
783 j++
784 txt := string(trms[from:to])
785 strs[i] = txt
786 }
787
788 // change protecting underscore to space
789 term = strings.Replace(term, "_", " ", -1)
790
791 // if term ends with dollar sign, use porter2 stemming, then add asterisk
792 if strings.HasSuffix(term, "$") && term != "$" {
793 term = strings.TrimSuffix(term, "$")
794 term = porter2.Stem(term)
795 term += "*"
796 }
797
798 isWildCard := false
799 if strings.HasSuffix(term, "*") && term != "*" {
800 tlen := len(term)
801 isWildCard = true
802 term = strings.TrimSuffix(term, "*")
803 pdlen := len(PostingDir(term))
804 if tlen < pdlen {
805 fmt.Fprintf(os.Stderr, "Wildcard term '%s' must be at least %d characters long - ignoring this word\n", term, pdlen)
806 return nil, nil
807 }
808 }
809
810 // binary search in term list
811 L, R := 0, numTerms-1
812 for L < R {
813 mid := (L + R) / 2
814 if strs[mid] < term {
815 L = mid + 1
816 } else {
817 R = mid
818 }
819 }
820
821 // wild card search scans term lists, fuses adjacent postings lists
822 if isWildCard {
823 if R < numTerms && strings.HasPrefix(strs[R], term) {
824 offset := indx[R].PostOffset
825 for R < numTerms && strings.HasPrefix(strs[R], term) {
826 R++
827 }
828 size := indx[R].PostOffset - offset
829
830 // read relevant postings list section
831 data := readPostingData(dpath, key, field, offset, size)
832 if data == nil || len(data) < 1 {
833 return nil, nil
834 }
835
836 if simple {
837
838 merged := make(map[int32]bool)
839
840 // combine all postings in term range
841 for _, val := range data {
842 merged[val] = true
843 }
844
845 fused := make([]int32, len(merged))
846
847 // convert map to slice
848 i := 0
849 for num := range merged {
850 fused[i] = num
851 i++
852 }
853
854 slices.Sort(fused)
855
856 return fused, nil
857 }
858
859 // read relevant word position section, includes phantom offset at end
860 uqis := readPositionIndex(dpath, key, field, offset, size+4)
861 if uqis == nil {
862 return nil, nil
863 }
864 ulen := len(uqis)
865 if ulen < 1 {
866 return nil, nil
867 }
868
869 from := uqis[0]
870 to := uqis[ulen-1]
871
872 // read offset section
873 ofst := readOffsetData(dpath, key, field, from, to-from)
874 if ofst == nil {
875 return nil, nil
876 }
877
878 combo := make(map[int32][]uint32)
879
880 addPositions := func(uid int32, pos uint32) {
881
882 arrs, ok := combo[uid]
883 if !ok {
884 arrs = make([]uint32, 0, 1)
885 }
886 arrs = append(arrs, pos)
887 combo[uid] = arrs
888 }
889
890 // populate array of positions per UID
891 for i, j, k := 0, 1, int32(0); i < ulen-1; i++ {
892 uid := data[i]
893 num := (uqis[j] - uqis[i])
894 j++
895 posns := VarintsToUints(ofst[k : k+num])
896 for _, pos := range posns {
897 addPositions(uid, pos)
898 }
899 k += num
900 }
901
902 fused := make([]int32, len(combo))
903
904 // convert map to slice
905 i := 0
906 for num := range combo {
907 fused[i] = num
908 i++
909 }
910
911 slices.Sort(fused)
912
913 // make array of uint32 arrays, populate for each UID
914 arrs := make([][]uint32, ulen-1)
915 if arrs == nil {
916 return nil, nil
917 }
918
919 for j, uid := range fused {
920 posn := combo[uid]
921
922 if len(posn) > 1 {
923 slices.Sort(posn)
924 }
925
926 arrs[j] = posn
927 }
928
929 return fused, arrs
930 }
931
932 return nil, nil
933 }
934
935 // regular search requires exact match from binary search
936 if R < numTerms && strs[R] == term {
937
938 offset := indx[R].PostOffset
939 size := indx[R+1].PostOffset - offset
940
941 // read relevant postings list section
942 data := readPostingData(dpath, key, field, offset, size)
943 if data == nil || len(data) < 1 {
944 return nil, nil
945 }
946
947 if simple {
948 return data, nil
949 }
950
951 // read relevant word position section, includes phantom offset at end
952 uqis := readPositionIndex(dpath, key, field, offset, size+4)
953 if uqis == nil {
954 return nil, nil
955 }
956 ulen := len(uqis)
957 if ulen < 1 {
958 return nil, nil
959 }
960
961 from := uqis[0]
962 to := uqis[ulen-1]
963
964 // read offset section
965 ofst := readOffsetData(dpath, key, field, from, to-from)
966 if ofst == nil {
967 return nil, nil
968 }
969
970 // make array of uint32 arrays, populate for each UID
971 arrs := make([][]uint32, ulen)
972 if arrs == nil || len(arrs) < 1 {
973 return nil, nil
974 }
975
976 // populate array of positions per UID
977 for i, j, k := 0, 1, int32(0); i < ulen-1; i++ {
978 num := (uqis[j] - uqis[i])
979 j++
980 arrs[i] = VarintsToUints(ofst[k : k+num])
981 k += num
982 }
983
984 return data, arrs
985 }
986
987 return nil, nil
988 }
989
990 func postingIDsFuture(base, term, field string, dist int, isLink bool) <-chan Arrays {
991
992 out := make(chan Arrays, chanDepth)
993 if out == nil {
994 DisplayError("Unable to create postings channel")
995 os.Exit(1)
996 }
997
998 // postingFuture asynchronously gets posting IDs and sends results through channel
999 postingFuture := func(base, term, field string, dist int, out chan<- Arrays) {
1000
1001 data, ofst := getPostingIDs(base, term, field, false, isLink)
1002
1003 out <- Arrays{Data: data, Ofst: ofst, Dist: dist}
1004
1005 close(out)
1006 }
1007
1008 // launch single future goroutine
1009 go postingFuture(base, term, field, dist, out)
1010
1011 return out
1012 }
1013
1014 // BOOLEAN OPERATIONS FOR POSTINGS LISTS
1015
1016 func extendPositionalIDs(N []int32, np [][]uint32, M []int32, mp [][]uint32, delta int, proc func(pn, pm []uint32, dlt uint32) []uint32) ([]int32, [][]uint32) {
1017
1018 if proc == nil {
1019 return nil, nil
1020 }
1021
1022 n, m := len(N), len(M)
1023
1024 if n < 1 || len(np) < 1 {
1025 return M, mp
1026 }
1027 if m < 1 || len(mp) < 1 {
1028 return N, np
1029 }
1030
1031 // order matters when extending phrase or testing proximity, do not swap lists based on size
1032
1033 sz := n
1034 if sz > m {
1035 sz = m
1036 }
1037
1038 if sz < 1 {
1039 return N, np
1040 }
1041
1042 res := make([]int32, sz)
1043 ofs := make([][]uint32, sz)
1044
1045 if res == nil || len(res) < 1 || ofs == nil || len(ofs) < 1 {
1046 return nil, nil
1047 }
1048
1049 i, j, k := 0, 0, 0
1050
1051 // use local variables for speed
1052 en, em := N[i], M[j]
1053
1054 for {
1055 // do inequality tests first
1056 if en < em {
1057 i++
1058 if i == n {
1059 break
1060 }
1061 en = N[i]
1062 } else if en > em {
1063 j++
1064 if j == m {
1065 break
1066 }
1067 em = M[j]
1068 } else {
1069 // specific callbacks test position arrays to match terms by adjacency or phrases by proximity
1070 adj := proc(np[i], mp[j], uint32(delta))
1071 if adj != nil && len(adj) > 0 {
1072 res[k] = en
1073 ofs[k] = adj
1074 k++
1075 }
1076 i++
1077 j++
1078 if i == n || j == m {
1079 break
1080 }
1081 en = N[i]
1082 em = M[j]
1083 }
1084 }
1085
1086 // truncate output arrays to actual size of intersection
1087 res = res[:k]
1088 ofs = ofs[:k]
1089
1090 return res, ofs
1091 }
1092
1093 func intersectIDs(N, M []int32) []int32 {
1094
1095 n, m := len(N), len(M)
1096
1097 // if either list is empty, intersection is empty
1098 if n < 1 || m < 1 {
1099 return nil
1100 }
1101
1102 // swap to make M the smaller list
1103 if n < m {
1104 N, M = M, N
1105 n, m = m, n
1106 }
1107
1108 if m < 1 {
1109 return N
1110 }
1111
1112 res := make([]int32, m)
1113
1114 i, j, k := 0, 0, 0
1115
1116 // use local variables for speed
1117 en, em := N[i], M[j]
1118
1119 for {
1120 // do inequality tests first
1121 if en < em {
1122 // index to larger list most likely to be advanced
1123 i++
1124 if i == n {
1125 break
1126 }
1127 en = N[i]
1128 } else if en > em {
1129 j++
1130 if j == m {
1131 break
1132 }
1133 em = M[j]
1134 } else {
1135 // equality (intersection match) least likely
1136 res[k] = en
1137 k++
1138 i++
1139 j++
1140 if i == n || j == m {
1141 break
1142 }
1143 en = N[i]
1144 em = M[j]
1145 }
1146 }
1147
1148 // truncate output array to actual size of intersection
1149 res = res[:k]
1150
1151 return res
1152 }
1153
1154 // if m * log(n) < m + n, binary search has fewer comparisons, but processor memory caches make linear algorithm faster
1155 /*
1156 func intersectBinary(N, M []int32) []int32 {
1157
1158 if N == nil {
1159 return M
1160 }
1161 if M == nil {
1162 return N
1163 }
1164
1165 n, m := len(N), len(M)
1166
1167 // swap to make M the smaller list
1168 if n < m {
1169 N, M = M, N
1170 n, m = m, n
1171 }
1172
1173 if m < 1 {
1174 return N
1175 }
1176
1177 k := 0
1178
1179 res := make([]int32, m)
1180
1181 for _, uid := range M {
1182 // inline binary search is faster than sort.Search
1183 L, R := 0, n-1
1184 for L < R {
1185 mid := (L + R) / 2
1186 if N[mid] < uid {
1187 L = mid + 1
1188 } else {
1189 R = mid
1190 }
1191 }
1192 // R := sort.Search(len(N), func(i int) bool { return N[i] >= uid })
1193 if R < n && N[R] == uid {
1194 res[k] = uid
1195 k++
1196 // remove leading part of N for slight speed gain
1197 N = N[R:]
1198 n = len(N)
1199 }
1200 }
1201
1202 res = res[:k]
1203
1204 return res
1205 }
1206 */
1207
1208 func combineIDs(N, M []int32) []int32 {
1209
1210 n, m := len(N), len(M)
1211
1212 if n < 1 {
1213 return M
1214 }
1215 if m < 1 {
1216 return N
1217 }
1218
1219 // swap to make M the smaller list
1220 if n < m {
1221 N, M = M, N
1222 n, m = m, n
1223 }
1224
1225 if m < 1 {
1226 return N
1227 }
1228
1229 i, j, k := 0, 0, 0
1230
1231 res := make([]int32, n+m)
1232
1233 for i < n && j < m {
1234 if N[i] < M[j] {
1235 res[k] = N[i]
1236 k++
1237 i++
1238 } else if N[i] > M[j] {
1239 res[k] = M[j]
1240 k++
1241 j++
1242 } else {
1243 res[k] = N[i]
1244 k++
1245 i++
1246 j++
1247 }
1248 }
1249 for i < n {
1250 res[k] = N[i]
1251 k++
1252 i++
1253 }
1254 for j < m {
1255 res[k] = M[j]
1256 k++
1257 j++
1258 }
1259
1260 res = res[:k]
1261
1262 return res
1263 }
1264
1265 func excludeIDs(N, M []int32) []int32 {
1266
1267 n, m := len(N), len(M)
1268
1269 if n < 1 {
1270 return nil
1271 }
1272 if m < 1 {
1273 return N
1274 }
1275
1276 res := make([]int32, n)
1277
1278 i, j, k := 0, 0, 0
1279
1280 // use local variables for speed
1281 en, em := N[i], M[j]
1282
1283 for {
1284 // do inequality tests first
1285 if en < em {
1286 // item is not excluded
1287 res[k] = en
1288 k++
1289 i++
1290 if i == n {
1291 break
1292 }
1293 en = N[i]
1294 } else if en > em {
1295 // advance second list pointer
1296 j++
1297 if j == m {
1298 break
1299 }
1300 em = M[j]
1301 } else {
1302 // exclude
1303 i++
1304 j++
1305 if i == n || j == m {
1306 break
1307 }
1308 en = N[i]
1309 em = M[j]
1310 }
1311 }
1312
1313 // truncate output array to actual size of result
1314 res = res[:k]
1315
1316 return res
1317 }