├── .vscode ├── settings.json └── launch.json ├── api └── dnf │ ├── matcher │ ├── util.go │ ├── pq │ │ ├── pq_test.go │ │ └── pq.go │ ├── ranker.go │ ├── posting_lists_test.go │ ├── match_all.go │ ├── posting_lists.go │ ├── match_top.go │ └── matcher_test.go │ ├── indexer │ ├── op.go │ ├── indexer.go │ ├── meta.go │ ├── posting │ │ ├── entry_test.go │ │ ├── list_test.go │ │ ├── list.go │ │ └── entry.go │ ├── record.go │ ├── immutable_indexer.go │ ├── shard.go │ └── mutable_indexer.go │ ├── expr │ ├── conjunction.go │ ├── attribute.go │ ├── assignment_test.go │ └── assignment.go │ ├── scorer │ └── scorer.go │ └── tools │ └── bench.go ├── go.mod ├── .github └── workflows │ └── go.yml ├── .gitignore ├── Makefile ├── go.sum ├── README.md └── LICENSE /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "go.testFlags": ["-v"] 3 | } -------------------------------------------------------------------------------- /api/dnf/matcher/util.go: -------------------------------------------------------------------------------- 1 | package matcher 2 | 3 | func min(a int, b int) int { 4 | if a < b { 5 | return a 6 | } 7 | return b 8 | } 9 | -------------------------------------------------------------------------------- /api/dnf/indexer/op.go: -------------------------------------------------------------------------------- 1 | package indexer 2 | 3 | type IndexOp struct { 4 | OpType string 5 | Data interface{} 6 | } 7 | 8 | func (i *IndexOp) Type() string { 9 | return i.OpType 10 | } 11 | 12 | func (i *IndexOp) Context() interface{} { 13 | return i.Data 14 | } 15 | -------------------------------------------------------------------------------- /api/dnf/indexer/indexer.go: -------------------------------------------------------------------------------- 1 | package indexer 2 | 3 | import ( 4 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 5 | ) 6 | 7 | // Indexer defines the top level indexer interface 8 | type Indexer interface { 9 | MaxKSize() int 10 | Get(conjunctionSize int, labels expr.Assignment) []*Record 11 | } 12 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/csimplestring/bool-expr-indexer 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/csimplestring/deheap v1.0.0 7 | github.com/csimplestring/go-cow-loader v0.0.2 8 | github.com/dchest/uniuri v0.0.0-20200228104902-7aecb25e1fe5 9 | github.com/orcaman/concurrent-map v0.0.0-20210501183033-44dafcb38ecc 10 | github.com/stretchr/testify v1.7.0 11 | ) 12 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | 2 | 3 | { 4 | // Use IntelliSense to learn about possible attributes. 5 | // Hover to view descriptions of existing attributes. 6 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 7 | "version": "0.2.0", 8 | "configurations": [ 9 | 10 | 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Set up Go 17 | uses: actions/setup-go@v2 18 | with: 19 | go-version: 1.16 20 | 21 | - name: Build 22 | run: go build -v ./... 23 | 24 | - name: Test 25 | run: go test -race -v -cover ./... 26 | -------------------------------------------------------------------------------- /api/dnf/expr/conjunction.go: -------------------------------------------------------------------------------- 1 | package expr 2 | 3 | // Conjunction consists of a slice of Attributes, which are combined with 'AND' logic. 4 | type Conjunction struct { 5 | ID int 6 | Attributes []*Attribute 7 | } 8 | 9 | // GetKSize is the size of attributes in c, excluding any 'not-included' type attribute 10 | func (c *Conjunction) GetKSize() int { 11 | ksize := 0 12 | for _, a := range c.Attributes { 13 | if a.Contains { 14 | ksize++ 15 | } 16 | } 17 | return ksize 18 | } 19 | 20 | // NewConjunction creates a new Conjunction 21 | func NewConjunction(ID int, attrs []*Attribute) *Conjunction { 22 | 23 | return &Conjunction{ 24 | ID: ID, 25 | Attributes: attrs, 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /api/dnf/expr/attribute.go: -------------------------------------------------------------------------------- 1 | package expr 2 | 3 | // Attribute is the pair of key-value, e.g., age:10, representing 'belongs to' 4 | // The value here is discrete, but for range values, like age < 40, we can convert it into multiple pairs: 5 | // age < 40 ---> age = 10, age = 20, age = 30, the granularity is 10. 6 | // 7 | // Name and Values are internally represented as int value, to save memory space, there should be a mapping 8 | // between the integer and human readable string, like: 9 | // Name: browser -> 1, os -> 2 10 | // Value: Chrome -> 1, Safari -> 2 11 | // 12 | // TODO: for longer range values such as dates, using a hierarchy structure to convert 13 | type Attribute struct { 14 | Name string 15 | Values []string 16 | Weights []uint32 17 | Contains bool 18 | } 19 | -------------------------------------------------------------------------------- /api/dnf/expr/assignment_test.go: -------------------------------------------------------------------------------- 1 | package expr 2 | 3 | import "testing" 4 | 5 | func TestValidateAssignment(t *testing.T) { 6 | type args struct { 7 | a Assignment 8 | } 9 | tests := []struct { 10 | name string 11 | args args 12 | wantErr bool 13 | }{ 14 | { 15 | "", 16 | args{a: Assignment{ 17 | {Name: "a", Value: "foo"}, 18 | }}, 19 | false, 20 | }, 21 | { 22 | "", 23 | args{a: Assignment{ 24 | {Name: "a", Value: "foo"}, 25 | {Name: "b", Value: "bar"}, 26 | {Name: "b", Value: "coo"}, 27 | }}, 28 | true, 29 | }, 30 | } 31 | for _, tt := range tests { 32 | t.Run(tt.name, func(t *testing.T) { 33 | if err := ValidateAssignment(tt.args.a); (err != nil) != tt.wantErr { 34 | t.Errorf("ValidateAssignment() error = %v, wantErr %v", err, tt.wantErr) 35 | } 36 | }) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /api/dnf/indexer/meta.go: -------------------------------------------------------------------------------- 1 | package indexer 2 | 3 | import ( 4 | "strconv" 5 | 6 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 7 | 8 | cmap "github.com/orcaman/concurrent-map" 9 | ) 10 | 11 | // metadata contains all the meta stats. 12 | type metadata struct { 13 | forwardIdx *forwardIndex 14 | } 15 | 16 | // forwardIndex keeps all the conjunctions. 17 | type forwardIndex struct { 18 | m cmap.ConcurrentMap 19 | } 20 | 21 | // Set sets the ID to conjunction. 22 | func (f *forwardIndex) Set(ID int, conjunction *expr.Conjunction) { 23 | f.m.Set(strconv.Itoa(ID), conjunction) 24 | } 25 | 26 | // Get gets the conjunction by ID. 27 | func (f *forwardIndex) Get(ID int) (*expr.Conjunction, bool) { 28 | v, exist := f.m.Get(strconv.Itoa(ID)) 29 | if !exist { 30 | return nil, false 31 | } 32 | 33 | return v.(*expr.Conjunction), true 34 | } 35 | -------------------------------------------------------------------------------- /api/dnf/scorer/scorer.go: -------------------------------------------------------------------------------- 1 | package scorer 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | type Scorer interface { 9 | SetUB(name, value string, ub int) 10 | GetUB(name, value string) int 11 | } 12 | 13 | func NewMapScorer() Scorer { 14 | return &staticMapScorer{ 15 | m: make(map[string]int), 16 | } 17 | } 18 | 19 | type staticMapScorer struct { 20 | sync.RWMutex 21 | m map[string]int 22 | } 23 | 24 | func (s *staticMapScorer) key(name, value string) string { 25 | return fmt.Sprintf("%s:%s", name, value) 26 | } 27 | 28 | func (s *staticMapScorer) SetUB(name string, value string, ub int) { 29 | key := s.key(name, value) 30 | 31 | s.Lock() 32 | s.m[key] = ub 33 | s.Unlock() 34 | } 35 | 36 | func (s *staticMapScorer) GetUB(name string, value string) int { 37 | key := s.key(name, value) 38 | 39 | s.RLock() 40 | defer s.RUnlock() 41 | 42 | return s.m[key] 43 | } 44 | -------------------------------------------------------------------------------- /api/dnf/indexer/posting/entry_test.go: -------------------------------------------------------------------------------- 1 | package posting 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_EntryInt32(t *testing.T) { 10 | 11 | e, err := NewEntryInt32(2, true, 100) 12 | assert.NoError(t, err) 13 | assert.Equal(t, uint32(2), e.CID()) 14 | assert.Equal(t, true, e.Contains()) 15 | assert.Equal(t, uint32(100), e.Score()) 16 | 17 | e, err = NewEntryInt32(1, false, 99) 18 | assert.NoError(t, err) 19 | assert.Equal(t, uint32(1), e.CID()) 20 | assert.Equal(t, false, e.Contains()) 21 | assert.Equal(t, uint32(99), e.Score()) 22 | 23 | e, err = NewEntryInt32(1, false, 101) 24 | assert.Error(t, err) 25 | 26 | e, err = NewEntryInt32(167772150, false, 99) 27 | assert.Error(t, err) 28 | } 29 | 30 | func Benchmark_EntryInt32(b *testing.B) { 31 | 32 | for i := 0; i < b.N; i++ { 33 | e, err := NewEntryInt32(100, true, 100) 34 | if err == nil { 35 | e.CID() 36 | e.Contains() 37 | e.Score() 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /api/dnf/expr/assignment.go: -------------------------------------------------------------------------------- 1 | package expr 2 | 3 | import ( 4 | "errors" 5 | "sync" 6 | ) 7 | 8 | // Label is a simple k/v pair: like 9 | type Label struct { 10 | Name string 11 | Value string 12 | Weight int 13 | } 14 | 15 | // Assignment is a slice of Label, equals to 'assignment S' in the paper 16 | type Assignment []Label 17 | 18 | // mapPool is the pool to recycle the map 19 | var mapPool = sync.Pool{ 20 | New: func() interface{} { 21 | return make(map[string]bool) 22 | }, 23 | } 24 | 25 | // ErrorDuplicateLabelName indicates there is duplicated label name in an assignment 26 | var ErrorDuplicateLabelName = errors.New("contains duplicated label name in assignment") 27 | 28 | // ValidateAssignment does sanity check on assignment 29 | func ValidateAssignment(a Assignment) error { 30 | m := mapPool.Get().(map[string]bool) 31 | for k := range m { 32 | delete(m, k) 33 | } 34 | defer mapPool.Put(m) 35 | 36 | for _, l := range a { 37 | if _, exist := m[l.Name]; exist { 38 | return ErrorDuplicateLabelName 39 | } 40 | m[l.Name] = true 41 | } 42 | return nil 43 | } 44 | -------------------------------------------------------------------------------- /api/dnf/indexer/posting/list_test.go: -------------------------------------------------------------------------------- 1 | package posting 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func Test_postingList(t *testing.T) { 10 | 11 | e1, _ := NewEntryInt32(3, true, 0) 12 | e2, _ := NewEntryInt32(1, true, 0) 13 | e3, _ := NewEntryInt32(2, true, 0) 14 | e4, _ := NewEntryInt32(2, false, 0) 15 | 16 | p := List{e1, e2, e3, e4} 17 | 18 | p.Sort() 19 | 20 | assert.Equal(t, 0, p.indexOf(1)) 21 | assert.Equal(t, 0, p.lastIndexOf(1)) 22 | assert.Equal(t, 1, p.indexOf(2)) 23 | assert.Equal(t, 2, p.lastIndexOf(2)) 24 | assert.Equal(t, 3, p.indexOf(3)) 25 | assert.Equal(t, 3, p.lastIndexOf(3)) 26 | assert.Equal(t, -1, p.indexOf(4)) 27 | 28 | assert.Equal(t, uint32(1), p[0].CID()) 29 | assert.Equal(t, uint32(2), p[1].CID()) 30 | assert.Equal(t, uint32(2), p[2].CID()) 31 | assert.Equal(t, uint32(3), p[3].CID()) 32 | 33 | assert.Equal(t, true, p[0].Contains()) 34 | assert.Equal(t, false, p[1].Contains()) 35 | assert.Equal(t, true, p[2].Contains()) 36 | assert.Equal(t, true, p[3].Contains()) 37 | 38 | assert.True(t, p.Remove(2)) 39 | assert.ElementsMatch(t, p, List{e2, e1}) 40 | } 41 | -------------------------------------------------------------------------------- /api/dnf/indexer/record.go: -------------------------------------------------------------------------------- 1 | package indexer 2 | 3 | import "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer/posting" 4 | 5 | // Record represents a key-value entry in indexer shard. 6 | type Record struct { 7 | PostingList posting.List 8 | Key string 9 | Value string 10 | } 11 | 12 | // append appends entry to r. 13 | func (r *Record) append(entry posting.EntryInt32) { 14 | r.PostingList = append(r.PostingList, entry) 15 | } 16 | 17 | // compact shrinks the posting list to avoid empty slot in slice. 18 | func (r *Record) compact() { 19 | if len(r.PostingList) != cap(r.PostingList) { 20 | compacted := make(posting.List, len(r.PostingList)) 21 | for i := 0; i < len(r.PostingList); i++ { 22 | compacted[i] = r.PostingList[i] 23 | } 24 | r.PostingList = compacted 25 | } 26 | } 27 | 28 | // copy deep copys the r to a new Record. 29 | func (r *Record) copy() *Record { 30 | c := &Record{ 31 | PostingList: make(posting.List, len(r.PostingList)), 32 | Key: r.Key, 33 | Value: r.Value, 34 | } 35 | 36 | for i, p := range r.PostingList { 37 | c.PostingList[i] = p 38 | } 39 | 40 | return c 41 | } 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.[56789ao] 3 | *.a[56789o] 4 | *.so 5 | *.pyc 6 | ._* 7 | .nfs.* 8 | [56789a].out 9 | *~ 10 | *.orig 11 | *.rej 12 | *.exe 13 | .*.swp 14 | core 15 | *.cgo*.go 16 | *.cgo*.c 17 | _cgo_* 18 | _obj 19 | _test 20 | _testmain.go 21 | /.vscode/ 22 | 23 | /VERSION.cache 24 | /bin/ 25 | /build.out 26 | /doc/articles/wiki/*.bin 27 | /goinstall.log 28 | /last-change 29 | /misc/cgo/life/run.out 30 | /misc/cgo/stdio/run.out 31 | /misc/cgo/testso/main 32 | /pkg/ 33 | /src/*.*/ 34 | /src/cmd/cgo/zdefaultcc.go 35 | /src/cmd/dist/dist 36 | /src/cmd/go/internal/cfg/zdefaultcc.go 37 | /src/cmd/go/internal/cfg/zosarch.go 38 | /src/cmd/internal/objabi/zbootstrap.go 39 | /src/go/build/zcgo.go 40 | /src/go/doc/headscan 41 | /src/runtime/internal/sys/zversion.go 42 | /src/unicode/maketables 43 | /test.out 44 | /test/garbage/*.out 45 | /test/pass.out 46 | /test/run.out 47 | /test/times.out 48 | 49 | # This file includes artifacts of Go build that should not be checked in. 50 | # For files created by specific development environment (e.g. editor), 51 | # use alternative ways to exclude files from git. 52 | # For example, set up .git/info/exclude or use a global .gitignore. -------------------------------------------------------------------------------- /api/dnf/matcher/pq/pq_test.go: -------------------------------------------------------------------------------- 1 | package pq 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestNew(t *testing.T) { 10 | 11 | pq := New(5) 12 | 13 | num := []int{5, 1, 4, 3, 2} 14 | items := make([]*IntItem, 5) 15 | for i := 0; i < 5; i++ { 16 | items[i] = &IntItem{ 17 | Val: num[i], 18 | Prior: num[i], 19 | } 20 | } 21 | 22 | for _, item := range items { 23 | pq.Push(item) 24 | } 25 | 26 | assert.Equal(t, 1, pq.PeekMin().Value()) 27 | assert.Equal(t, 5, pq.PeekMax().Value()) 28 | 29 | // pop 1 30 | pq.PopMin() 31 | assert.Equal(t, 2, pq.PeekMin().Value()) 32 | 33 | // pop 5 34 | pq.PopMax() 35 | assert.Equal(t, 4, pq.PeekMax().Value()) 36 | 37 | // len = 4 38 | pq.Push(&IntItem{Val: 6, Prior: 6}) 39 | assert.Equal(t, 2, pq.PeekMin().Value()) 40 | assert.Equal(t, 6, pq.PeekMax().Value()) 41 | 42 | pq.Push(&IntItem{Val: 5, Prior: 100}) 43 | assert.Equal(t, 2, pq.PeekMin().Value()) 44 | assert.Equal(t, 5, pq.PeekMax().Value()) 45 | 46 | pq.Push(&IntItem{Val: 7, Prior: 7}) 47 | pq.Push(&IntItem{Val: 8, Prior: 8}) 48 | assert.Equal(t, 5, pq.PeekMax().Value()) 49 | assert.Equal(t, 4, pq.PeekMin().Value()) 50 | 51 | assert.Equal(t, 5, pq.Len()) 52 | } 53 | -------------------------------------------------------------------------------- /api/dnf/indexer/posting/list.go: -------------------------------------------------------------------------------- 1 | package posting 2 | 3 | import "sort" 4 | 5 | // List is a list of Posting Entry 6 | type List []EntryInt32 7 | 8 | // Sort sorts l by CID and Contains flag in asc 9 | func (l List) Sort() { 10 | sort.Slice(l[:], func(i, j int) bool { 11 | 12 | if l[i].CID() != l[j].CID() { 13 | return l[i].CID() < l[j].CID() 14 | } 15 | 16 | return !l[i].Contains() && l[j].Contains() 17 | }) 18 | } 19 | 20 | // Remove removes ID from l, this function is expensive! 21 | func (l *List) Remove(ID int) bool { 22 | first := l.indexOf(uint32(ID)) 23 | if first == -1 { 24 | return false 25 | } 26 | last := l.lastIndexOf(uint32(ID)) 27 | 28 | *l = append((*l)[:first], (*l)[last+1:]...) 29 | return true 30 | } 31 | 32 | func (nums List) indexOf(target uint32) int { 33 | l, r := 0, len(nums) 34 | 35 | for l < r { 36 | m := l + (r-l)/2 37 | if nums[m].CID() >= target { 38 | r = m 39 | } else { 40 | l = m + 1 41 | } 42 | } 43 | 44 | if l < len(nums) && nums[l].CID() == target { 45 | return l 46 | } else { 47 | return -1 48 | } 49 | } 50 | 51 | func (nums List) lastIndexOf(target uint32) int { 52 | l, r := 0, len(nums)-1 53 | 54 | for l < r { 55 | m := (l + r + 1) / 2 56 | 57 | if nums[m].CID() <= target { 58 | l = m 59 | } else { 60 | r = m - 1 61 | } 62 | } 63 | 64 | if l < len(nums) && nums[l].CID() == target { 65 | return l 66 | } else { 67 | return -1 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /api/dnf/indexer/posting/entry.go: -------------------------------------------------------------------------------- 1 | package posting 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | const flagMask uint32 = 1 << 31 8 | const idMask uint32 = 0b111111111111111111111111 9 | const scoreMask uint32 = 0b01111111000000000000000000000000 10 | const maxID uint32 = 16777215 11 | 12 | var EOL EntryInt32 = EntryInt32((1 << 31) | (0 << 24) | maxID) 13 | 14 | // EntryInt32 is 15 | // the 32nd bit is the 'belongsTo' flag: 1 -> belongs, 0 -> not belongs 16 | // the 31st ~ 25th bits are the 'score' field: [0,2^7-1], but only [0,100] is valid 17 | // the 24th to 1st bits are the 'conjunction id' field: ranging from 0 to 16777215 18 | type EntryInt32 uint32 19 | 20 | // NewEntryInt32 creates a uint32 representation of entry. 21 | func NewEntryInt32(ID uint32, contains bool, score uint32) (EntryInt32, error) { 22 | if score > 100 { 23 | return 0, errors.New("score must be [0, 100]") 24 | } 25 | if ID > maxID { 26 | return 0, errors.New("ID must be [0, 16777215]") 27 | } 28 | 29 | var containsBit uint32 = 0 30 | if contains { 31 | containsBit = 1 32 | } 33 | 34 | r := (containsBit << 31) | (score << 24) | ID 35 | return EntryInt32(r), nil 36 | } 37 | 38 | // CID returns the conjunction id 39 | func (e EntryInt32) CID() uint32 { 40 | return uint32(e) & idMask 41 | } 42 | 43 | // Score returns the score 44 | func (e EntryInt32) Score() uint32 { 45 | return uint32(e) & scoreMask >> 24 46 | } 47 | 48 | // Contains returns the belongs-to flag 49 | func (e EntryInt32) Contains() bool { 50 | return uint32(e)&flagMask == flagMask 51 | } 52 | -------------------------------------------------------------------------------- /api/dnf/matcher/ranker.go: -------------------------------------------------------------------------------- 1 | package matcher 2 | 3 | import ( 4 | "sort" 5 | 6 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 7 | ) 8 | 9 | type ranker struct { 10 | assignment expr.Assignment 11 | sWeightLookup map[string]int 12 | } 13 | 14 | func newRanker(assignment expr.Assignment) *ranker { 15 | u := &ranker{ 16 | assignment: assignment, 17 | } 18 | 19 | sWeightLookup := make(map[string]int) 20 | for _, label := range assignment { 21 | sWeightLookup[u.formatKey(label.Name, label.Value)] = label.Weight 22 | } 23 | u.sWeightLookup = sWeightLookup 24 | 25 | return u 26 | } 27 | 28 | func (u *ranker) formatKey(name, value string) string { 29 | return name + ":" + value 30 | } 31 | 32 | // lists must be sorted 33 | func (u *ranker) calculateEntryUB(K int, lists postingLists) int { 34 | 35 | score := 0 36 | for i := 0; i <= K && i < lists.Len(); i++ { 37 | name := lists[i].name 38 | value := lists[i].value 39 | if w, exists := u.sWeightLookup[u.formatKey(name, value)]; exists { 40 | score += w * lists[i].ub 41 | } 42 | } 43 | return score 44 | } 45 | 46 | func (u *ranker) calculateListUB(topN int, lists postingLists) int { 47 | 48 | scores := make([]int, lists.Len()) 49 | for i, list := range lists { 50 | if w, exists := u.sWeightLookup[u.formatKey(list.name, list.value)]; exists { 51 | scores[i] = w * list.ub 52 | } else { 53 | scores[i] = 0 54 | } 55 | } 56 | // get topN 57 | sort.Ints(scores) 58 | totalUB := 0 59 | for i := 0; i < topN && i < len(scores); i++ { 60 | totalUB += scores[i] 61 | } 62 | 63 | return totalUB 64 | } 65 | -------------------------------------------------------------------------------- /api/dnf/matcher/posting_lists_test.go: -------------------------------------------------------------------------------- 1 | package matcher 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer" 7 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer/posting" 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func Test_plistIter(t *testing.T) { 12 | e1, _ := posting.NewEntryInt32(1, true, 0) 13 | e2, _ := posting.NewEntryInt32(2, true, 0) 14 | e3, _ := posting.NewEntryInt32(3, true, 0) 15 | e4, _ := posting.NewEntryInt32(3, false, 0) 16 | 17 | p := posting.List{e1, e2, e3, e4} 18 | 19 | iter := newIterator(p) 20 | assert.Equal(t, e1, iter.current()) 21 | 22 | iter.skipTo(2) 23 | assert.Equal(t, e2, iter.current()) 24 | 25 | iter.skipTo(3) 26 | assert.Equal(t, e3, iter.current()) 27 | 28 | iter.skipTo(3) 29 | assert.Equal(t, e3, iter.current()) 30 | 31 | iter.skipTo(4) 32 | assert.Equal(t, posting.EOL, iter.current()) 33 | } 34 | 35 | func Test_postingLists(t *testing.T) { 36 | 37 | e1, _ := posting.NewEntryInt32(1, true, 0) 38 | e2, _ := posting.NewEntryInt32(2, true, 0) 39 | e3, _ := posting.NewEntryInt32(3, true, 0) 40 | e4, _ := posting.NewEntryInt32(3, false, 0) 41 | 42 | p1 := posting.List{e1} 43 | p2 := posting.List{e2} 44 | p3 := posting.List{e3} 45 | p4 := posting.List{e4} 46 | 47 | plists := newPostingLists([]*indexer.Record{ 48 | {PostingList: p4}, 49 | {PostingList: p3}, 50 | {PostingList: p2}, 51 | {PostingList: p1}, 52 | }, 53 | nil, 54 | ) 55 | plists.sortByCurrent() 56 | 57 | assert.Equal(t, p1, plists[0].ref) 58 | assert.Equal(t, p2, plists[1].ref) 59 | assert.Equal(t, p4, plists[2].ref) 60 | assert.Equal(t, p3, plists[3].ref) 61 | } 62 | -------------------------------------------------------------------------------- /api/dnf/matcher/match_all.go: -------------------------------------------------------------------------------- 1 | package matcher 2 | 3 | import ( 4 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 5 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer" 6 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer/posting" 7 | ) 8 | 9 | type AllMatcher interface { 10 | Match(indexer indexer.Indexer, assignment expr.Assignment) ([]int, error) 11 | } 12 | 13 | func New() AllMatcher { 14 | return &allMatcher{} 15 | } 16 | 17 | type allMatcher struct{} 18 | 19 | func (m *allMatcher) Match(indexer indexer.Indexer, assignment expr.Assignment) ([]int, error) { 20 | if err := expr.ValidateAssignment(assignment); err != nil { 21 | return nil, err 22 | } 23 | 24 | results := make([]int, 0, 1024) 25 | 26 | n := min(len(assignment), indexer.MaxKSize()) 27 | 28 | for i := n; i >= 0; i-- { 29 | pLists := newPostingLists(indexer.Get(i, assignment), nil) 30 | 31 | K := i 32 | if K == 0 { 33 | K = 1 34 | } 35 | if pLists.Len() < K { 36 | continue 37 | } 38 | 39 | pLists.sortByCurrent() 40 | for pLists[K-1].current() != posting.EOL { 41 | var nextID uint32 42 | 43 | if pLists[0].current().CID() == pLists[K-1].current().CID() { 44 | 45 | if pLists[0].current().Contains() == false { 46 | rejectID := pLists[0].current().CID() 47 | for L := K; L <= pLists.Len()-1; L++ { 48 | if pLists[L].current().CID() == rejectID { 49 | pLists[L].skipTo(rejectID + 1) 50 | } else { 51 | break 52 | } 53 | } 54 | 55 | } else { 56 | results = append(results, int(pLists[K-1].current().CID())) 57 | } 58 | 59 | nextID = pLists[K-1].current().CID() + 1 60 | } else { 61 | nextID = pLists[K-1].current().CID() 62 | 63 | } 64 | 65 | for L := 0; L <= K-1; L++ { 66 | pLists[L].skipTo(nextID) 67 | } 68 | pLists.sortByCurrent() 69 | } 70 | 71 | } 72 | 73 | return results, nil 74 | } 75 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | -include .env 2 | 3 | VERSION := $(shell git describe --tags) 4 | BUILD := $(shell git rev-parse --short HEAD) 5 | PROJECTNAME := $(shell basename "$(PWD)") 6 | 7 | # Go related variables. 8 | GOBASE := $(shell pwd) 9 | GOPATH := $(GOBASE)/vendor:$(GOBASE) 10 | GOBIN := $(GOBASE)/bin 11 | GOFILES := $(wildcard *.go) 12 | 13 | # Use linker flags to provide version/build settings 14 | LDFLAGS=-ldflags "-X=main.Version=$(VERSION) -X=main.Build=$(BUILD)" 15 | 16 | # Redirect error output to a file, so we can show it in development mode. 17 | STDERR := /tmp/.$(PROJECTNAME)-stderr.txt 18 | 19 | # PID file will keep the process id of the server 20 | PID := /tmp/.$(PROJECTNAME).pid 21 | 22 | # Make is verbose in Linux. Make it silent. 23 | MAKEFLAGS += --silent 24 | 25 | ## install: Install missing dependencies. Runs `go get` internally. e.g; make install get=github.com/foo/bar 26 | install: go-get 27 | 28 | ## compile: Compile the binary. 29 | compile: 30 | @-touch $(STDERR) 31 | @-rm $(STDERR) 32 | @-$(MAKE) -s go-compile 2> $(STDERR) 33 | @cat $(STDERR) | sed -e '1s/.*/\nError:\n/' | sed 's/make\[.*/ /' | sed "/^/s/^/ /" 1>&2 34 | 35 | ## clean: Clean build files. Runs `go clean` internally. 36 | clean: 37 | @-rm $(GOBIN)/$(PROJECTNAME) 2> /dev/null 38 | @-$(MAKE) go-clean 39 | 40 | go-build: 41 | @echo " > Building binary..." 42 | @GOPATH=$(GOPATH) GOBIN=$(GOBIN) go build $(LDFLAGS) -o $(GOBIN)/$(PROJECTNAME) $(GOFILES) 43 | 44 | go-test: 45 | @echo " > Running tests..." 46 | go test -v ./... -cover 47 | 48 | go-bench: 49 | @echo " > Running benchmarks..." 50 | go test -bench=. ./... -test.timeout=0 51 | 52 | go-generate: 53 | @echo " > Generating dependency files..." 54 | @GOPATH=$(GOPATH) GOBIN=$(GOBIN) go generate $(generate) 55 | 56 | go-get: 57 | @echo " > Checking if there is any missing dependencies..." 58 | @GOPATH=$(GOPATH) GOBIN=$(GOBIN) go get $(get) 59 | 60 | go-install: 61 | @GOPATH=$(GOPATH) GOBIN=$(GOBIN) go install $(GOFILES) 62 | 63 | go-clean: 64 | @echo " > Cleaning build cache" 65 | @GOPATH=$(GOPATH) GOBIN=$(GOBIN) go clean 66 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/cornelk/hashmap v1.0.1 h1:RXGcy29hEdLLV8T6aK4s+BAd4tq4+3Hq50N2GoG0uIg= 2 | github.com/cornelk/hashmap v1.0.1/go.mod h1:8wbysTUDnwJGrPZ1Iwsou3m+An6sldFrJItjRhfegCw= 3 | github.com/csimplestring/deheap v1.0.0 h1:pxoFJwtJCc6pBPAYy1tVB3i7f9IoV79IEvTkkkxyDfg= 4 | github.com/csimplestring/deheap v1.0.0/go.mod h1:S8atrRxHYxqJw3Hbp8abzwphrKJOLEdZXLW+9GHQTK4= 5 | github.com/csimplestring/go-cow-loader v0.0.1 h1:w2H3K43nZczXSk2ok7pL5w6uYFptA+XrdKssgcdzHZo= 6 | github.com/csimplestring/go-cow-loader v0.0.1/go.mod h1:ZEN+naLXi19hMZ+3aQxR+w5Q8dhApYJtwbaeT6RqwVc= 7 | github.com/csimplestring/go-cow-loader v0.0.2 h1:RsifWgvcsdHdK8VbJlZe1OKeOIUouXqVVI8Ip0UrNa0= 8 | github.com/csimplestring/go-cow-loader v0.0.2/go.mod h1:ZEN+naLXi19hMZ+3aQxR+w5Q8dhApYJtwbaeT6RqwVc= 9 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 10 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 11 | github.com/dchest/siphash v1.1.0 h1:1Rs9eTUlZLPBEvV+2sTaM8O0NWn0ppbgqS7p11aWawI= 12 | github.com/dchest/siphash v1.1.0/go.mod h1:q+IRvb2gOSrUnYoPqHiyHXS0FOBBOdl6tONBlVnOnt4= 13 | github.com/dchest/uniuri v0.0.0-20200228104902-7aecb25e1fe5 h1:RAV05c0xOkJ3dZGS0JFybxFKZ2WMLabgx3uXnd7rpGs= 14 | github.com/dchest/uniuri v0.0.0-20200228104902-7aecb25e1fe5/go.mod h1:GgB8SF9nRG+GqaDtLcwJZsQFhcogVCJ79j4EdT0c2V4= 15 | github.com/orcaman/concurrent-map v0.0.0-20210501183033-44dafcb38ecc h1:Ak86L+yDSOzKFa7WM5bf5itSOo1e3Xh8bm5YCMUXIjQ= 16 | github.com/orcaman/concurrent-map v0.0.0-20210501183033-44dafcb38ecc/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI= 17 | github.com/pkg/profile v1.5.0 h1:042Buzk+NhDI+DeSAA62RwJL8VAuZUMQZUjCsRz1Mug= 18 | github.com/pkg/profile v1.5.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18= 19 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 20 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 21 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 22 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 23 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 24 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 25 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 26 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 27 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 28 | -------------------------------------------------------------------------------- /api/dnf/matcher/posting_lists.go: -------------------------------------------------------------------------------- 1 | package matcher 2 | 3 | import ( 4 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer" 5 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer/posting" 6 | "github.com/csimplestring/bool-expr-indexer/api/dnf/scorer" 7 | ) 8 | 9 | type plistIter struct { 10 | name string 11 | value string 12 | ub int 13 | ref posting.List 14 | cur int 15 | } 16 | 17 | func newIterator(ref posting.List) *plistIter { 18 | return &plistIter{ 19 | ref: ref, 20 | cur: 0, 21 | } 22 | } 23 | 24 | func newScoredIterator(name, value string, ub int, ref posting.List) *plistIter { 25 | return &plistIter{ 26 | name: name, 27 | value: value, 28 | ub: ub, 29 | ref: ref, 30 | cur: 0, 31 | } 32 | } 33 | 34 | func (p *plistIter) current() posting.EntryInt32 { 35 | if p.cur >= len(p.ref) { 36 | return posting.EOL 37 | } 38 | 39 | return p.ref[p.cur] 40 | } 41 | 42 | func (p *plistIter) skipTo(ID uint32) { 43 | n := len(p.ref) 44 | // since p.ref.Items is already sorted in asc order, we do search: find the smallest-ID >= ID 45 | // the binary search is not used 46 | i := p.cur 47 | for i < n && p.ref[i].CID() < ID { 48 | i++ 49 | } 50 | p.cur = i 51 | } 52 | 53 | // postingLists is a slice of list iterator 54 | type postingLists []*plistIter 55 | 56 | func newPostingLists( 57 | records []*indexer.Record, 58 | scorer scorer.Scorer, 59 | ) postingLists { 60 | 61 | c := make([]*plistIter, len(records)) 62 | 63 | for i, v := range records { 64 | if scorer != nil { 65 | ub := scorer.GetUB(v.Key, v.Value) 66 | c[i] = newScoredIterator(v.Key, v.Value, ub, v.PostingList) 67 | } else { 68 | c[i] = newIterator(v.PostingList) 69 | } 70 | } 71 | return c 72 | } 73 | 74 | func (p postingLists) Len() int { 75 | return len(p) 76 | } 77 | 78 | func (p postingLists) sortByCurrent() { 79 | // we implement the insertion sort by own because: 80 | // 1. the size of postingLists is usually small and the changes of position happens not frequently 81 | // 2. the built-in sort.Sort function takes much time and extra allocation happens, benchmark shows 5x times slower 82 | p.insertionSort() 83 | } 84 | 85 | func (p postingLists) insertionSort() { 86 | var n = len(p) 87 | for i := 1; i < n; i++ { 88 | j := i 89 | for j > 0 { 90 | a := p[j-1].current() 91 | b := p[j].current() 92 | 93 | if a.CID() > b.CID() || (a.CID() == b.CID()) && a.Contains() && !b.Contains() { 94 | p[j-1], p[j] = p[j], p[j-1] 95 | } 96 | j = j - 1 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /api/dnf/indexer/immutable_indexer.go: -------------------------------------------------------------------------------- 1 | package indexer 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 7 | cmap "github.com/orcaman/concurrent-map" 8 | ) 9 | 10 | var _ Indexer = (*MemReadOnlyIndexer)(nil) 11 | 12 | // MemReadOnlyIndexer implements the Indexer interface and stores all the entries in memory. 13 | type MemReadOnlyIndexer struct { 14 | meta *metadata 15 | maxKSize int 16 | sizedIndexes map[int]shard 17 | } 18 | 19 | // NewMemReadOnlyIndexer create a memory stored indexer. This kind of indexer is thread-safe. 20 | func NewMemReadOnlyIndexer(items []*expr.Conjunction) (*MemReadOnlyIndexer, error) { 21 | 22 | m := &MemReadOnlyIndexer{ 23 | meta: &metadata{ 24 | forwardIdx: &forwardIndex{ 25 | cmap.New(), 26 | }, 27 | }, 28 | maxKSize: 0, 29 | sizedIndexes: make(map[int]shard), 30 | } 31 | 32 | for _, item := range items { 33 | if err := m.add(item); err != nil { 34 | return nil, err 35 | } 36 | } 37 | 38 | return m, nil 39 | } 40 | 41 | // Add conjunction into indexer. 42 | func (k *MemReadOnlyIndexer) add(c *expr.Conjunction) error { 43 | if _, exist := k.meta.forwardIdx.Get(c.ID); exist { 44 | return fmt.Errorf("duplicate conjunction with ID: %d", c.ID) 45 | } 46 | 47 | ksize := c.GetKSize() 48 | 49 | if k.maxKSize < ksize { 50 | k.maxKSize = ksize 51 | } 52 | 53 | kidx, exist := k.sizedIndexes[ksize] 54 | if !exist { 55 | kidx = newMapShard(ksize) 56 | k.sizedIndexes[ksize] = kidx 57 | } 58 | 59 | if err := kidx.Add(c); err != nil { 60 | return err 61 | } 62 | k.meta.forwardIdx.Set(c.ID, c) 63 | return nil 64 | } 65 | 66 | // Build finalise the build-up of indexer by calling the Build on each shards. 67 | func (k *MemReadOnlyIndexer) Build() error { 68 | for _, v := range k.sizedIndexes { 69 | if err := v.Build(); err != nil { 70 | return err 71 | } 72 | } 73 | return nil 74 | } 75 | 76 | // MaxKSize returns the max K-size of the conjunctions stored in indexer. 77 | func (k *MemReadOnlyIndexer) MaxKSize() int { 78 | return k.maxKSize 79 | } 80 | 81 | // Get returns the list of Record, based on size and labels. 82 | func (k *MemReadOnlyIndexer) Get(size int, labels expr.Assignment) []*Record { 83 | idx := k.sizedIndexes[size] 84 | if idx == nil { 85 | return nil 86 | } 87 | 88 | candidates := make([]*Record, 0, len(labels)+1) 89 | for _, label := range labels { 90 | 91 | p := idx.Get(label.Name, label.Value) 92 | if p == nil { 93 | continue 94 | } 95 | candidates = append(candidates, p) 96 | } 97 | if size == 0 { 98 | candidates = append(candidates, idx.Get("", "")) 99 | } 100 | return candidates 101 | } 102 | -------------------------------------------------------------------------------- /api/dnf/matcher/match_top.go: -------------------------------------------------------------------------------- 1 | package matcher 2 | 3 | import ( 4 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 5 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer" 6 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer/posting" 7 | "github.com/csimplestring/bool-expr-indexer/api/dnf/matcher/pq" 8 | "github.com/csimplestring/bool-expr-indexer/api/dnf/scorer" 9 | ) 10 | 11 | type TopNMatcher interface { 12 | MatchTopN(topN int, indexer indexer.Indexer, assignment expr.Assignment) []int 13 | } 14 | 15 | func NewTopN(s scorer.Scorer) TopNMatcher { 16 | return &topNMatcher{ 17 | scorer: s, 18 | } 19 | } 20 | 21 | type topNMatcher struct { 22 | scorer scorer.Scorer 23 | } 24 | 25 | func (m *topNMatcher) MatchTopN(topN int, indexer indexer.Indexer, assignment expr.Assignment) []int { 26 | ubCalculator := newRanker(assignment) 27 | q := pq.New(topN) 28 | 29 | n := min(len(assignment), indexer.MaxKSize()) 30 | 31 | for i := n; i >= 0; i-- { 32 | pLists := newPostingLists(indexer.Get(i, assignment), m.scorer) 33 | 34 | K := i 35 | if K == 0 { 36 | K = 1 37 | } 38 | if pLists.Len() < K { 39 | continue 40 | } 41 | 42 | listUB := ubCalculator.calculateListUB(K, pLists) 43 | if q.Len() == topN && q.PeekMin().Priority() > listUB { 44 | continue 45 | } 46 | 47 | pLists.sortByCurrent() 48 | for pLists[K-1].current() != posting.EOL { 49 | conjunctionUB := ubCalculator.calculateEntryUB(K-1, pLists) 50 | 51 | if q.Len() == topN && q.PeekMin().Priority() > conjunctionUB { 52 | nextID := pLists[K-1].current().CID() + 1 53 | for L := 0; L <= K-1; L++ { 54 | pLists[L].skipTo(nextID) 55 | } 56 | pLists.sortByCurrent() 57 | continue 58 | } 59 | 60 | var nextID uint32 61 | 62 | if pLists[0].current().CID() == pLists[K-1].current().CID() { 63 | 64 | if pLists[0].current().Contains() == false { 65 | rejectID := pLists[0].current().CID() 66 | for L := K; L <= pLists.Len()-1; L++ { 67 | if pLists[L].current().CID() == rejectID { 68 | pLists[L].skipTo(rejectID + 1) 69 | } else { 70 | break 71 | } 72 | } 73 | 74 | } else { 75 | q.Push(&pq.IntItem{Val: int(pLists[K-1].current().CID()), Prior: conjunctionUB}) 76 | } 77 | 78 | nextID = pLists[K-1].current().CID() + 1 79 | } else { 80 | nextID = pLists[K-1].current().CID() 81 | 82 | } 83 | 84 | for L := 0; L <= K-1; L++ { 85 | pLists[L].skipTo(nextID) 86 | } 87 | pLists.sortByCurrent() 88 | } 89 | 90 | } 91 | 92 | return extractIDs(q) 93 | } 94 | 95 | func extractIDs(q pq.MinMaxPriorityQueue) []int { 96 | ids := make([]int, q.Len()) 97 | i := 0 98 | for q.Len() != 0 { 99 | ids[i] = q.PopMin().(*pq.IntItem).Value().(int) 100 | i++ 101 | } 102 | return ids 103 | } 104 | -------------------------------------------------------------------------------- /api/dnf/tools/bench.go: -------------------------------------------------------------------------------- 1 | package tools 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "runtime" 7 | "time" 8 | 9 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 10 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer" 11 | "github.com/dchest/uniuri" 12 | ) 13 | 14 | func randBool() bool { 15 | rand.Seed(time.Now().UnixNano()) 16 | n := rand.Intn(100) 17 | // it will return false in 1% possibility 18 | if n <= 1 { 19 | return false 20 | } 21 | return true 22 | } 23 | 24 | func PrintMemUsage() { 25 | bToMb := func(b uint64) uint64 { 26 | return b / 1024 / 1024 27 | } 28 | var m runtime.MemStats 29 | runtime.ReadMemStats(&m) 30 | fmt.Printf("Alloc = %v MiB", bToMb(m.Alloc)) 31 | fmt.Printf("\tTotalAlloc = %v MiB", bToMb(m.TotalAlloc)) 32 | fmt.Printf("\tSys = %v MiB", bToMb(m.Sys)) 33 | fmt.Printf("\tNumGC = %v\n", m.NumGC) 34 | } 35 | 36 | func getTestAttributes(num int) (map[string][]string, []string) { 37 | 38 | m := make(map[string][]string) 39 | 40 | names := make([]string, num) 41 | for i := 0; i < num; i++ { 42 | nameLen := rand.Intn(8) + 1 43 | name := uniuri.NewLen(nameLen) 44 | 45 | valuesLen := rand.Intn(20) + 1 46 | values := make([]string, valuesLen) 47 | for j := 0; j < valuesLen; j++ { 48 | values[j] = uniuri.NewLen(valuesLen) 49 | } 50 | 51 | m[name] = values 52 | names[i] = name 53 | } 54 | 55 | return m, names 56 | } 57 | 58 | func getTestAssignment(n int, attrs map[string][]string, names []string) expr.Assignment { 59 | labels := make([]expr.Label, n) 60 | for i := 0; i < n; i++ { 61 | name := names[rand.Intn(len(names))] 62 | values := attrs[name] 63 | 64 | value := values[0] 65 | flag := randBool() 66 | // we simulate a mis-match case here. 67 | if flag { 68 | value = "" 69 | } 70 | 71 | labels[i] = expr.Label{ 72 | Name: name, 73 | Value: value, 74 | } 75 | } 76 | return labels 77 | } 78 | 79 | func GetPrefilledIndex(attributeNum, conjunctionNum, assignmentNum, assignmentAvgSize int) (indexer.Indexer, []expr.Assignment) { 80 | testAttrs, testAttrNames := getTestAttributes(attributeNum) 81 | 82 | conjunctions := make([]*expr.Conjunction, conjunctionNum) 83 | for n := 0; n < conjunctionNum; n++ { 84 | id := n + 1 85 | 86 | n1 := rand.Intn(5) + 1 87 | attrs := make([]*expr.Attribute, n1) 88 | for i := 0; i < n1; i++ { 89 | 90 | name := testAttrNames[rand.Intn(len(testAttrNames))] 91 | attrs[i] = &expr.Attribute{ 92 | Name: name, 93 | Values: testAttrs[name], 94 | Contains: randBool(), 95 | } 96 | } 97 | 98 | conjunctions[n] = expr.NewConjunction(id, attrs) 99 | } 100 | 101 | k, _ := indexer.NewMemReadOnlyIndexer(conjunctions) 102 | k.Build() 103 | 104 | assignments := make([]expr.Assignment, assignmentNum) 105 | for i := 0; i < assignmentNum; i++ { 106 | assignments[i] = getTestAssignment(assignmentAvgSize, testAttrs, testAttrNames) 107 | } 108 | 109 | return k, assignments 110 | } 111 | -------------------------------------------------------------------------------- /api/dnf/indexer/shard.go: -------------------------------------------------------------------------------- 1 | package indexer 2 | 3 | import ( 4 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 5 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer/posting" 6 | ) 7 | 8 | const zeroKey string = ":" 9 | 10 | // shard is a sub-map of indexer, which only stores the conjunctions with same size. 11 | type shard interface { 12 | Get(name string, value string) *Record 13 | Build() error 14 | Add(c *expr.Conjunction) error 15 | Copy() shard 16 | } 17 | 18 | // mapShard implements shard, stores the posting indexes for all the conjunctions with the same size. 19 | type mapShard struct { 20 | conjunctionSize int 21 | zeroKey string 22 | invertedMap map[string]*Record 23 | } 24 | 25 | // newMapShard creates a new mapShard. 26 | func newMapShard(ksize int) *mapShard { 27 | 28 | return &mapShard{ 29 | zeroKey: zeroKey, 30 | conjunctionSize: ksize, 31 | invertedMap: make(map[string]*Record), 32 | } 33 | } 34 | 35 | // hashKey concats the name:value as hash key. 36 | func (m *mapShard) hashKey(name string, value string) string { 37 | return name + ":" + value 38 | } 39 | 40 | // Build finalise the posting lists in shard, sort and compact each post list. 41 | func (m *mapShard) Build() error { 42 | 43 | for _, r := range m.invertedMap { 44 | r.PostingList.Sort() 45 | r.compact() 46 | } 47 | return nil 48 | } 49 | 50 | // Get returns Record based on name:value 51 | func (m *mapShard) Get(name string, value string) *Record { 52 | v, ok := m.invertedMap[m.hashKey(name, value)] 53 | if !ok { 54 | return nil 55 | } 56 | 57 | return v 58 | } 59 | 60 | // createIfAbsent 61 | func (m *mapShard) createIfAbsent(hash string, name, value string) *Record { 62 | 63 | if v, found := m.invertedMap[hash]; found { 64 | return v 65 | } 66 | 67 | m.invertedMap[hash] = &Record{ 68 | PostingList: make(posting.List, 0, 64), 69 | Key: name, 70 | Value: value, 71 | } 72 | 73 | return m.invertedMap[hash] 74 | } 75 | 76 | // Add conjunction into a shard. 77 | func (m *mapShard) Add(c *expr.Conjunction) error { 78 | 79 | for _, attr := range c.Attributes { 80 | for i, value := range attr.Values { 81 | 82 | hash := m.hashKey(attr.Name, value) 83 | 84 | r := m.createIfAbsent(hash, attr.Name, value) 85 | 86 | score := uint32(0) 87 | if len(attr.Weights) != 0 { 88 | score = attr.Weights[i] 89 | } 90 | 91 | entry, err := posting.NewEntryInt32(uint32(c.ID), attr.Contains, score) 92 | if err != nil { 93 | return err 94 | } 95 | 96 | r.append(entry) 97 | 98 | m.invertedMap[hash] = r 99 | } 100 | } 101 | 102 | if c.GetKSize() == 0 { 103 | r := m.createIfAbsent(m.zeroKey, "", "") 104 | 105 | entry, err := posting.NewEntryInt32(uint32(c.ID), true, 0) 106 | if err != nil { 107 | return err 108 | } 109 | r.append(entry) 110 | m.invertedMap[m.zeroKey] = r 111 | } 112 | 113 | return nil 114 | } 115 | 116 | // Copy deep-copys the mapShard 117 | func (m *mapShard) Copy() shard { 118 | c := &mapShard{ 119 | conjunctionSize: m.conjunctionSize, 120 | zeroKey: m.zeroKey, 121 | invertedMap: make(map[string]*Record, len(m.invertedMap)), 122 | } 123 | for k, v := range m.invertedMap { 124 | c.invertedMap[k] = v.copy() 125 | } 126 | 127 | return c 128 | } 129 | -------------------------------------------------------------------------------- /api/dnf/matcher/pq/pq.go: -------------------------------------------------------------------------------- 1 | package pq 2 | 3 | import "github.com/csimplestring/deheap" 4 | 5 | type Item interface { 6 | Value() interface{} 7 | Priority() int 8 | UUID() uint64 9 | } 10 | 11 | type IntItem struct { 12 | Val int 13 | Prior int 14 | } 15 | 16 | func (i *IntItem) Value() interface{} { 17 | return i.Val 18 | } 19 | 20 | func (i *IntItem) Priority() int { 21 | return i.Prior 22 | } 23 | 24 | func (i *IntItem) UUID() uint64 { 25 | return uint64(i.Val) 26 | } 27 | 28 | type MinMaxPriorityQueue interface { 29 | Push(Item) 30 | PeekMin() Item 31 | PeekMax() Item 32 | PopMin() Item 33 | PopMax() Item 34 | Update(Item) 35 | Len() int 36 | } 37 | 38 | type indexedItem struct { 39 | value Item 40 | index int 41 | } 42 | 43 | type itemDeheap []*indexedItem 44 | 45 | func (h itemDeheap) Len() int { return len(h) } 46 | 47 | func (h itemDeheap) Less(i, j int) bool { 48 | return h[i].value.Priority() < h[j].value.Priority() 49 | } 50 | 51 | func (h itemDeheap) Swap(i, j int) { 52 | h[i], h[j] = h[j], h[i] 53 | h[i].index = i 54 | h[j].index = j 55 | } 56 | 57 | func (h *itemDeheap) Push(x interface{}) { 58 | // Push and Pop use pointer receivers because they modify the slice's length, 59 | // not just its contents. 60 | n := len(*h) 61 | item := x.(*indexedItem) 62 | item.index = n 63 | *h = append(*h, item) 64 | } 65 | 66 | func (h *itemDeheap) Pop() interface{} { 67 | old := *h 68 | n := len(old) 69 | x := old[n-1] 70 | old[n-1] = nil 71 | x.index = -1 72 | *h = old[0 : n-1] 73 | return x 74 | } 75 | 76 | type bpq struct { 77 | heap itemDeheap 78 | idx map[uint64]int 79 | bound int 80 | } 81 | 82 | func New(bound int) MinMaxPriorityQueue { 83 | return &bpq{ 84 | heap: make(itemDeheap, 0, bound), 85 | idx: make(map[uint64]int), 86 | bound: bound, 87 | } 88 | } 89 | 90 | func (b *bpq) Len() int { 91 | return b.heap.Len() 92 | } 93 | 94 | func (b *bpq) add(item Item) { 95 | it := &indexedItem{ 96 | value: item, 97 | } 98 | deheap.Push(&b.heap, it) 99 | b.idx[item.UUID()] = it.index 100 | 101 | // check bound 102 | for b.heap.Len() > b.bound { 103 | ele := deheap.Pop(&b.heap).(*indexedItem) 104 | delete(b.idx, ele.value.UUID()) 105 | } 106 | } 107 | 108 | func (b *bpq) Push(item Item) { 109 | 110 | _, ok := b.idx[item.UUID()] 111 | if ok { 112 | b.Update(item) 113 | return 114 | } 115 | 116 | b.add(item) 117 | } 118 | 119 | func (b *bpq) PeekMin() Item { 120 | if b.heap.Len() == 0 { 121 | return nil 122 | } 123 | 124 | return b.heap[0].value 125 | } 126 | 127 | func (b *bpq) PeekMax() Item { 128 | if b.heap.Len() == 0 { 129 | return nil 130 | } 131 | 132 | if b.heap.Len() == 1 { 133 | return b.heap[0].value 134 | } 135 | if b.heap.Len() == 2 { 136 | return b.heap[1].value 137 | } 138 | 139 | return max(b.heap[1].value, b.heap[2].value) 140 | } 141 | 142 | func (b *bpq) PopMin() Item { 143 | if b.heap.Len() == 0 { 144 | return nil 145 | } 146 | 147 | v := deheap.Pop(&b.heap).(*indexedItem) 148 | delete(b.idx, v.value.UUID()) 149 | return v.value 150 | } 151 | 152 | func (b *bpq) PopMax() Item { 153 | if b.heap.Len() == 0 { 154 | return nil 155 | } 156 | 157 | v := deheap.PopMax(&b.heap).(*indexedItem) 158 | delete(b.idx, v.value.UUID()) 159 | return v.value 160 | } 161 | 162 | func (b *bpq) Update(item Item) { 163 | if item == nil { 164 | return 165 | } 166 | 167 | i, ok := b.idx[item.UUID()] 168 | if !ok { 169 | return 170 | } 171 | 172 | v := deheap.Remove(&b.heap, i).(*indexedItem) 173 | delete(b.idx, v.value.UUID()) 174 | 175 | b.add(item) 176 | } 177 | 178 | func max(a Item, b Item) Item { 179 | if a.Priority() > b.Priority() { 180 | return a 181 | } 182 | return b 183 | } 184 | -------------------------------------------------------------------------------- /api/dnf/indexer/mutable_indexer.go: -------------------------------------------------------------------------------- 1 | package indexer 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 7 | cow "github.com/csimplestring/go-cow-loader" 8 | ) 9 | 10 | // MutableIndexer top level interface 11 | type MutableIndexer interface { 12 | MaxKSize() int 13 | Add(c *expr.Conjunction) error 14 | Delete(ID int) error 15 | Get(conjunctionSize int, labels expr.Assignment) []*Record 16 | } 17 | 18 | var _ MutableIndexer = (*CopyOnWriteIndexer)(nil) 19 | var _ Indexer = (*CopyOnWriteIndexer)(nil) 20 | 21 | // internalCopyOnWriteIndexer inherits the MemReadOnlyIndexer, plus Apply and Copy functions/ 22 | type internalCopyOnWriteIndexer struct { 23 | *MemReadOnlyIndexer 24 | } 25 | 26 | // Apply applies the ops on itself in the order. 27 | func (i *internalCopyOnWriteIndexer) Apply(ops []cow.Op) error { 28 | for _, op := range ops { 29 | opType := op.Type() 30 | 31 | switch opType { 32 | case "add": 33 | i.add(op.Context().(*expr.Conjunction)) 34 | case "delete": 35 | i.delette(op.Context().(int)) 36 | default: 37 | return fmt.Errorf("unsupported type: %s", opType) 38 | } 39 | } 40 | return nil 41 | } 42 | 43 | // add adds a new conjunction into i. 44 | func (i *internalCopyOnWriteIndexer) add(c *expr.Conjunction) error { 45 | if _, exist := i.meta.forwardIdx.Get(c.ID); exist { 46 | return fmt.Errorf("Try to add duplicate conjunction with ID %d", c.ID) 47 | } 48 | 49 | return i.add(c) 50 | } 51 | 52 | // delette delettes an existing conjunction. 53 | func (i *internalCopyOnWriteIndexer) delette(ID int) error { 54 | c, exist := i.meta.forwardIdx.Get(ID) 55 | if !exist { 56 | return fmt.Errorf("Try to delete non-existing conjunction with ID %d", ID) 57 | } 58 | 59 | shard := i.sizedIndexes[c.GetKSize()] 60 | for _, attr := range c.Attributes { 61 | for _, val := range attr.Values { 62 | name := attr.Name 63 | record := shard.Get(name, val) 64 | record.PostingList.Remove(ID) 65 | } 66 | } 67 | 68 | return nil 69 | } 70 | 71 | // Copy deep copy a new internalCopyOnWriteIndexer. 72 | func (c *internalCopyOnWriteIndexer) Copy() cow.Value { 73 | copiedShard := make(map[int]shard, len(c.sizedIndexes)) 74 | for k, v := range c.sizedIndexes { 75 | copiedShard[k] = v.Copy() 76 | } 77 | 78 | meta := c.meta 79 | c.meta = nil 80 | 81 | copiedIndex := &internalCopyOnWriteIndexer{ 82 | MemReadOnlyIndexer: &MemReadOnlyIndexer{ 83 | meta: meta, 84 | maxKSize: c.maxKSize, 85 | sizedIndexes: copiedShard, 86 | }, 87 | } 88 | 89 | return copiedIndex 90 | } 91 | 92 | // NewCopyOnWriteIndexer creats a new CopyOnWriteIndexer with given items. 93 | // It internally uses a loader to periodically reload index. 94 | func NewCopyOnWriteIndexer(items []*expr.Conjunction, refreshInterval int) (*CopyOnWriteIndexer, error) { 95 | base, err := NewMemReadOnlyIndexer(items) 96 | if err != nil { 97 | return nil, err 98 | } 99 | 100 | if err := base.Build(); err != nil { 101 | return nil, err 102 | } 103 | 104 | idx := &internalCopyOnWriteIndexer{ 105 | base, 106 | } 107 | 108 | u := &CopyOnWriteIndexer{} 109 | u.loader = cow.New(idx, refreshInterval) 110 | errChan := u.loader.Err() 111 | 112 | go func() { 113 | for err := range errChan { 114 | fmt.Println(err) 115 | } 116 | }() 117 | 118 | return u, nil 119 | } 120 | 121 | // CopyOnWriteIndexer allows user to update the index. Internally it uses a loader to periodically 122 | // reload index by applying the ADD/DEL/UPD operations. 123 | type CopyOnWriteIndexer struct { 124 | loader *cow.Reloader 125 | } 126 | 127 | func (u *CopyOnWriteIndexer) MaxKSize() int { 128 | return u.loader.Reload().(Indexer).MaxKSize() 129 | } 130 | 131 | // Add adds a new conjunction into index, this operation will be first buffered in a queue 132 | // and be applied in a batcch way once the ticker is triggered. So the new item won't be updated immediately but with a 133 | // lag. 134 | func (u *CopyOnWriteIndexer) Add(c *expr.Conjunction) error { 135 | 136 | return u.loader.Accept(&IndexOp{ 137 | OpType: "add", 138 | Data: c, 139 | }) 140 | } 141 | 142 | // Delete deletes a conjunction by ID. 143 | func (u *CopyOnWriteIndexer) Delete(ID int) error { 144 | 145 | return u.loader.Accept(&IndexOp{ 146 | OpType: "delete", 147 | Data: ID, 148 | }) 149 | } 150 | 151 | // Get gets the matched records. 152 | func (u *CopyOnWriteIndexer) Get(conjunctionSize int, labels expr.Assignment) []*Record { 153 | idx := u.loader.Reload().(Indexer) 154 | return idx.Get(conjunctionSize, labels) 155 | } 156 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Boolean Expression Indexer Go library 2 | 3 | ![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/csimplestring/bool-expr-indexer/Go/master?style=for-the-badge) 4 | [![GitHub issues](https://img.shields.io/github/issues/csimplestring/bool-expr-indexer?style=for-the-badge)](https://github.com/csimplestring/bool-expr-indexer/issues) 5 | [![GitHub stars](https://img.shields.io/github/stars/csimplestring/bool-expr-indexer?style=for-the-badge)](https://github.com/csimplestring/bool-expr-indexer/stargazers) 6 | [![GitHub license](https://img.shields.io/github/license/csimplestring/bool-expr-indexer?style=for-the-badge)](https://github.com/csimplestring/bool-expr-indexer/blob/master/LICENSE) 7 | [![Go Report Card](https://goreportcard.com/badge/github.com/csimplestring/bool-expr-indexer?style=for-the-badge)](https://goreportcard.com/report/github.com/csimplestring/bool-expr-indexer) 8 | 9 | 10 | 11 | A Go implementation of the core algorithm in Standford and Yahoo's paper <[Indexing Boolean Expression](https://theory.stanford.edu/~sergei/papers/vldb09-indexing.pdf)>, which already supports the following features mentioned in paper: 12 | 13 | - DNF algorithm 14 | - Simple match 15 | - TopN match (ranking based) 16 | - Online update (Copy-On-Write) 17 | 18 | 19 | ## usage 20 | 21 | ``` Go 22 | 23 | import 24 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 25 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer" 26 | "github.com/stretchr/testify/assert" 27 | ) 28 | 29 | var conjunctions []*expr.Conjunction 30 | 31 | conjunctions = append(conjunctions, expr.NewConjunction( 32 | 1, 33 | []*expr.Attribute{ 34 | {Name: "age", Values: []string{"3"}, Contains: true, Weights: []uint32{1}}, 35 | {Name: "state", Values: []string{"NY"}, Contains: true, Weights: []uint32{40}}, 36 | }, 37 | )) 38 | 39 | conjunctions = append(conjunctions, expr.NewConjunction( 40 | 2, 41 | []*expr.Attribute{ 42 | {Name: "age", Values: []string{"3"}, Contains: true, Weights: []uint32{1}}, 43 | {Name: "gender", Values: []string{"F"}, Contains: true, Weights: []uint32{3}}, 44 | }, 45 | )) 46 | 47 | conjunctions = append(conjunctions, expr.NewConjunction( 48 | 3, 49 | []*expr.Attribute{ 50 | {Name: "age", Values: []string{"3"}, Contains: true, Weights: []uint32{2}}, 51 | {Name: "gender", Values: []string{"M"}, Contains: true, Weights: []uint32{5}}, 52 | {Name: "state", Values: []string{"CA"}, Contains: false, Weights: []uint32{0}}, 53 | }, 54 | )) 55 | 56 | conjunctions = append(conjunctions, expr.NewConjunction( 57 | 4, 58 | []*expr.Attribute{ 59 | {Name: "state", Values: []string{"CA"}, Contains: true, Weights: []uint32{15}}, 60 | {Name: "gender", Values: []string{"M"}, Contains: true, Weights: []uint32{9}}, 61 | }, 62 | )) 63 | 64 | conjunctions = append(conjunctions, expr.NewConjunction( 65 | 5, 66 | []*expr.Attribute{ 67 | {Name: "age", Values: []string{"3", "4"}, Contains: true, Weights: []uint32{1, 5}}, 68 | }, 69 | )) 70 | 71 | conjunctions = append(conjunctions, expr.NewConjunction( 72 | 6, 73 | []*expr.Attribute{ 74 | {Name: "state", Values: []string{"CA", "NY"}, Contains: false, Weights: []uint32{0, 0}}, 75 | }, 76 | )) 77 | 78 | // read only indexer, best performance 79 | k, err := indexer.NewMemReadOnlyIndexer(conjunctions) 80 | assert.NoError(t, err) 81 | k.Build() 82 | 83 | matcher := &allMatcher{} 84 | 85 | matched := matcher.Match(k, expr.Assignment{ 86 | expr.Label{Name: "age", Value: "3"}, 87 | expr.Label{Name: "state", Value: "CA"}, 88 | expr.Label{Name: "gender", Value: "M"}, 89 | }) 90 | 91 | assert.ElementsMatch(t, []int{4, 5}, matched) 92 | 93 | matched = matcher.Match(k, expr.Assignment{ 94 | expr.Label{Name: "age", Value: "3"}, 95 | expr.Label{Name: "state", Value: "NY"}, 96 | expr.Label{Name: "gender", Value: "F"}, 97 | }) 98 | 99 | assert.ElementsMatch(t, []int{1, 2, 5}, matched) 100 | 101 | // copy on write indexer, you can ADD or DELETE new conjunctions 102 | // the refresh interval in second, to control how often to swap the old and new index 103 | // usually set it up to 15 minutes, which is ok in most cases. 104 | freshInterval := 5 105 | k, err := indexer.NewCopyOnWriteIndexer(conjunctions, freshInterval) 106 | assert.NoError(t, err) 107 | 108 | k.Delete(4) 109 | 110 | matched = matcher.Match(k, expr.Assignment{ 111 | expr.Label{Name: "age", Value: "3"}, 112 | expr.Label{Name: "state", Value: "CA"}, 113 | expr.Label{Name: "gender", Value: "M"}, 114 | }) 115 | assert.ElementsMatch(t, []int{4, 5}, matched) 116 | 117 | // after 5 seconds, the modifications will be applied. 118 | time.Sleep(5 * time.Second) 119 | matched = matcher.Match(k, expr.Assignment{ 120 | expr.Label{Name: "age", Value: "3"}, 121 | expr.Label{Name: "state", Value: "CA"}, 122 | expr.Label{Name: "gender", Value: "M"}, 123 | }) 124 | assert.ElementsMatch(t, []int{5}, matched) 125 | ``` 126 | 127 | see matcher_test.go 128 | 129 | ## Use Scenario 130 | 131 | It is an important component in online computational advertising system. As mentioned in the paper, the original motivation of this library is to provide an efficient way to select ads based on pre-defined targeting condition. Given a user with some labels, it finds the best-matched ads. 132 | 133 | In a typical advertising management system, the following hierarchy models are used: 134 | 135 | Advertisers 136 | |__ LineItem 137 | |__ InsertionOrder 138 | |__ Campaign 139 | |__ Creative Banners With Targeting Condition 140 | 141 | ### Ad selector in RTB 142 | 143 | In the RTB or similar environment, when a bidding request comes, usually it comes with some user-profile context(in the paper, it is called ***assignment***). The Ad server then needs to quickly find the matched creative banners that match the targeting condition(in the paper, it is expressed as ***conjunctions***). A naive way is to iterate all the banners and compare the user-profile with targeting condition one-by-one, which is very slow when there are millions of banners in the system, however the whole RTB workflow must be done with 100 ms. 144 | 145 | ### User segmentation in DMP 146 | 147 | In a DMP environment, all the collected user data shall be processed, enriched and aggregated in nearly real-time. One key problem is to quickly identify a user belongs to which group, based on pre-defined group condition. 148 | 149 | This library is developed for the above scenarios. The following features are supported 150 | 151 | - DNF algorithm 152 | 153 | For example: a targeting condition can be expressed as: (age = 30 AND city = A) OR (gender = male AND age = 20 AND region = B) etc 154 | 155 | - Simple match 156 | 157 | It returns all the matched expression ids 158 | 159 | - TopN match (ranking based) 160 | 161 | It returns the TopN matched expression ids, based on an adopted WAND algorithm. Note that the caller has to provide the upper bound and score of each conjunction, usually can be calculated in a Spark job. 162 | 163 | ## Benchmark 164 | 165 | Total number of expressions - size of key | operations within 1s | op per ns | 166 | |---:|---:|---:| 167 | | Benchmark_Match_10000_20-12 | 106482 | 10142 ns/op | 168 | | Benchmark_Match_100000_20-12 | 70419 | 14749 ns/op| 169 | |Benchmark_Match_1000000_20-12 | 14438 | 87884 ns/op | 170 | | Benchmark_Match_10000_30-12 | 80452 | 15832 ns/op| 171 | | Benchmark_Match_100000_30-12 | 61867 | 20770 ns/op | 172 | | Benchmark_Match_1000000_30-12 | 10000 | 103594 ns/op | 173 | |Benchmark_Match_10000_40-12 | 61221 | 20778 ns/op | 174 | | Benchmark_Match_100000_40-12 | 49161 | 25129 ns/op | 175 | | Benchmark_Match_1000000_40-12 | 10000 | 110132 ns/op | 176 | 177 | Memory usage: 1 million of expressions are indexed and it takes 100 MB on average. 178 | 179 | 180 | ## Roadmap 181 | 182 | This library only implements the core DNF algorithm in that paper. However, it is more useful to use it to build up a production-ready Ad Server. Currently, the indexer does not support online update(all the expressions shall be indexed once in the beginning). Also, the speed will be slow if the expressions number increases. Therefore I plan to support more advanced features soon 183 | 184 | - metrics monitoring 185 | - index partitioning 186 | - canary rollout deployment 187 | - HA support 188 | - http/gRPC transport 189 | - web UI 190 | 191 | PR issues are welcome 192 | -------------------------------------------------------------------------------- /api/dnf/matcher/matcher_test.go: -------------------------------------------------------------------------------- 1 | package matcher 2 | 3 | import ( 4 | "math/rand" 5 | "sync" 6 | "testing" 7 | "time" 8 | 9 | "github.com/csimplestring/bool-expr-indexer/api/dnf/expr" 10 | "github.com/csimplestring/bool-expr-indexer/api/dnf/indexer" 11 | "github.com/csimplestring/bool-expr-indexer/api/dnf/scorer" 12 | "github.com/csimplestring/bool-expr-indexer/api/dnf/tools" 13 | "github.com/stretchr/testify/assert" 14 | ) 15 | 16 | var benchmarkResults []int 17 | 18 | func Benchmark_Match_10000_20(b *testing.B) { 19 | 20 | k, assignments := tools.GetPrefilledIndex(1000, 10000, 10000, 20) 21 | 22 | b.ResetTimer() 23 | matcher := &allMatcher{} 24 | var result []int 25 | for i := 0; i < b.N; i++ { 26 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 27 | } 28 | benchmarkResults = result 29 | } 30 | 31 | func Benchmark_Match_100000_20(b *testing.B) { 32 | 33 | k, assignments := tools.GetPrefilledIndex(1000, 100000, 10000, 20) 34 | 35 | b.ResetTimer() 36 | matcher := &allMatcher{} 37 | var result []int 38 | for i := 0; i < b.N; i++ { 39 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 40 | } 41 | benchmarkResults = result 42 | } 43 | 44 | func Benchmark_Match_1000000_20(b *testing.B) { 45 | 46 | k, assignments := tools.GetPrefilledIndex(1000, 1000000, 10000, 20) 47 | 48 | b.ResetTimer() 49 | matcher := &allMatcher{} 50 | var result []int 51 | for i := 0; i < b.N; i++ { 52 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 53 | } 54 | benchmarkResults = result 55 | } 56 | 57 | func Benchmark_Match_10000_30(b *testing.B) { 58 | 59 | k, assignments := tools.GetPrefilledIndex(1000, 10000, 10000, 30) 60 | 61 | b.ResetTimer() 62 | matcher := &allMatcher{} 63 | var result []int 64 | for i := 0; i < b.N; i++ { 65 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 66 | } 67 | benchmarkResults = result 68 | } 69 | 70 | func Benchmark_Match_100000_30(b *testing.B) { 71 | 72 | k, assignments := tools.GetPrefilledIndex(1000, 100000, 10000, 30) 73 | 74 | b.ResetTimer() 75 | matcher := &allMatcher{} 76 | var result []int 77 | for i := 0; i < b.N; i++ { 78 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 79 | } 80 | benchmarkResults = result 81 | } 82 | 83 | func Benchmark_Match_1000000_30(b *testing.B) { 84 | 85 | k, assignments := tools.GetPrefilledIndex(1000, 1000000, 10000, 30) 86 | 87 | b.ResetTimer() 88 | matcher := &allMatcher{} 89 | var result []int 90 | for i := 0; i < b.N; i++ { 91 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 92 | } 93 | benchmarkResults = result 94 | } 95 | 96 | func Benchmark_Match_10000_40(b *testing.B) { 97 | 98 | k, assignments := tools.GetPrefilledIndex(1000, 10000, 10000, 40) 99 | 100 | b.ResetTimer() 101 | matcher := &allMatcher{} 102 | var result []int 103 | for i := 0; i < b.N; i++ { 104 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 105 | } 106 | benchmarkResults = result 107 | } 108 | 109 | func Benchmark_Match_100000_40(b *testing.B) { 110 | 111 | k, assignments := tools.GetPrefilledIndex(1000, 100000, 10000, 40) 112 | 113 | b.ResetTimer() 114 | matcher := &allMatcher{} 115 | var result []int 116 | for i := 0; i < b.N; i++ { 117 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 118 | } 119 | benchmarkResults = result 120 | } 121 | 122 | func Benchmark_Match_1000000_40(b *testing.B) { 123 | 124 | k, assignments := tools.GetPrefilledIndex(1000, 1000000, 10000, 40) 125 | 126 | b.ResetTimer() 127 | matcher := &allMatcher{} 128 | var result []int 129 | for i := 0; i < b.N; i++ { 130 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 131 | } 132 | benchmarkResults = result 133 | } 134 | 135 | func Benchmark_Concurrent_Match_1000000_40(b *testing.B) { 136 | 137 | k, assignments := tools.GetPrefilledIndex(1000, 1000000, 10000, 40) 138 | 139 | b.ResetTimer() 140 | matcher := &allMatcher{} 141 | var result []int 142 | wg := sync.WaitGroup{} 143 | for i := 0; i < b.N; i++ { 144 | wg.Add(1) 145 | go func() { 146 | result, _ = matcher.Match(k, assignments[rand.Intn(10000)]) 147 | wg.Done() 148 | }() 149 | } 150 | benchmarkResults = result 151 | wg.Wait() 152 | } 153 | 154 | func Test_MemReadOnlyIndex_Match(t *testing.T) { 155 | 156 | var conjunctions []*expr.Conjunction 157 | 158 | conjunctions = append(conjunctions, expr.NewConjunction( 159 | 1, 160 | []*expr.Attribute{ 161 | {Name: "age", Values: []string{"3"}, Contains: true, Weights: []uint32{1}}, 162 | {Name: "state", Values: []string{"NY"}, Contains: true, Weights: []uint32{40}}, 163 | }, 164 | )) 165 | 166 | conjunctions = append(conjunctions, expr.NewConjunction( 167 | 2, 168 | []*expr.Attribute{ 169 | {Name: "age", Values: []string{"3"}, Contains: true, Weights: []uint32{1}}, 170 | {Name: "gender", Values: []string{"F"}, Contains: true, Weights: []uint32{3}}, 171 | }, 172 | )) 173 | 174 | conjunctions = append(conjunctions, expr.NewConjunction( 175 | 3, 176 | []*expr.Attribute{ 177 | {Name: "age", Values: []string{"3"}, Contains: true, Weights: []uint32{2}}, 178 | {Name: "gender", Values: []string{"M"}, Contains: true, Weights: []uint32{5}}, 179 | {Name: "state", Values: []string{"CA"}, Contains: false, Weights: []uint32{0}}, 180 | }, 181 | )) 182 | 183 | conjunctions = append(conjunctions, expr.NewConjunction( 184 | 4, 185 | []*expr.Attribute{ 186 | {Name: "state", Values: []string{"CA"}, Contains: true, Weights: []uint32{15}}, 187 | {Name: "gender", Values: []string{"M"}, Contains: true, Weights: []uint32{9}}, 188 | }, 189 | )) 190 | 191 | conjunctions = append(conjunctions, expr.NewConjunction( 192 | 5, 193 | []*expr.Attribute{ 194 | {Name: "age", Values: []string{"3", "4"}, Contains: true, Weights: []uint32{1, 5}}, 195 | }, 196 | )) 197 | 198 | conjunctions = append(conjunctions, expr.NewConjunction( 199 | 6, 200 | []*expr.Attribute{ 201 | {Name: "state", Values: []string{"CA", "NY"}, Contains: false, Weights: []uint32{0, 0}}, 202 | }, 203 | )) 204 | 205 | k, err := indexer.NewMemReadOnlyIndexer(conjunctions) 206 | assert.NoError(t, err) 207 | k.Build() 208 | 209 | scoreMap := scorer.NewMapScorer() 210 | scoreMap.SetUB("state", "CA", 2) 211 | scoreMap.SetUB("state", "NY", 5) 212 | scoreMap.SetUB("age", "3", 1) 213 | scoreMap.SetUB("age", "4", 3) 214 | scoreMap.SetUB("gender", "F", 2) 215 | scoreMap.SetUB("gender", "M", 1) 216 | 217 | assert.Equal(t, 2, k.MaxKSize()) 218 | matcher := &allMatcher{} 219 | 220 | matched, err := matcher.Match(k, expr.Assignment{ 221 | expr.Label{Name: "age", Value: "3"}, 222 | expr.Label{Name: "state", Value: "CA"}, 223 | expr.Label{Name: "gender", Value: "M"}, 224 | }) 225 | 226 | assert.ElementsMatch(t, []int{4, 5}, matched) 227 | 228 | matched, err = matcher.Match(k, expr.Assignment{ 229 | expr.Label{Name: "age", Value: "3"}, 230 | expr.Label{Name: "state", Value: "NY"}, 231 | expr.Label{Name: "gender", Value: "F"}, 232 | }) 233 | 234 | assert.ElementsMatch(t, []int{1, 2, 5}, matched) 235 | 236 | topNMatcher := NewTopN(scoreMap) 237 | matched = topNMatcher.MatchTopN(1, k, expr.Assignment{ 238 | expr.Label{Name: "age", Value: "3", Weight: 8}, 239 | expr.Label{Name: "state", Value: "NY", Weight: 10}, 240 | expr.Label{Name: "gender", Value: "F", Weight: 9}, 241 | }) 242 | assert.ElementsMatch(t, []int{1}, matched) 243 | } 244 | 245 | func Test_COWIndex_Match(t *testing.T) { 246 | 247 | var conjunctions []*expr.Conjunction 248 | 249 | conjunctions = append(conjunctions, expr.NewConjunction( 250 | 1, 251 | []*expr.Attribute{ 252 | {Name: "age", Values: []string{"3"}, Contains: true, Weights: []uint32{1}}, 253 | {Name: "state", Values: []string{"NY"}, Contains: true, Weights: []uint32{40}}, 254 | }, 255 | )) 256 | 257 | conjunctions = append(conjunctions, expr.NewConjunction( 258 | 2, 259 | []*expr.Attribute{ 260 | {Name: "age", Values: []string{"3"}, Contains: true, Weights: []uint32{1}}, 261 | {Name: "gender", Values: []string{"F"}, Contains: true, Weights: []uint32{3}}, 262 | }, 263 | )) 264 | 265 | conjunctions = append(conjunctions, expr.NewConjunction( 266 | 3, 267 | []*expr.Attribute{ 268 | {Name: "age", Values: []string{"3"}, Contains: true, Weights: []uint32{2}}, 269 | {Name: "gender", Values: []string{"M"}, Contains: true, Weights: []uint32{5}}, 270 | {Name: "state", Values: []string{"CA"}, Contains: false, Weights: []uint32{0}}, 271 | }, 272 | )) 273 | 274 | conjunctions = append(conjunctions, expr.NewConjunction( 275 | 4, 276 | []*expr.Attribute{ 277 | {Name: "state", Values: []string{"CA"}, Contains: true, Weights: []uint32{15}}, 278 | {Name: "gender", Values: []string{"M"}, Contains: true, Weights: []uint32{9}}, 279 | }, 280 | )) 281 | 282 | conjunctions = append(conjunctions, expr.NewConjunction( 283 | 5, 284 | []*expr.Attribute{ 285 | {Name: "age", Values: []string{"3", "4"}, Contains: true, Weights: []uint32{1, 5}}, 286 | }, 287 | )) 288 | 289 | conjunctions = append(conjunctions, expr.NewConjunction( 290 | 6, 291 | []*expr.Attribute{ 292 | {Name: "state", Values: []string{"CA", "NY"}, Contains: false, Weights: []uint32{0, 0}}, 293 | }, 294 | )) 295 | 296 | k, err := indexer.NewCopyOnWriteIndexer(conjunctions, 1) 297 | assert.NoError(t, err) 298 | 299 | scoreMap := scorer.NewMapScorer() 300 | scoreMap.SetUB("state", "CA", 2) 301 | scoreMap.SetUB("state", "NY", 5) 302 | scoreMap.SetUB("age", "3", 1) 303 | scoreMap.SetUB("age", "4", 3) 304 | scoreMap.SetUB("gender", "F", 2) 305 | scoreMap.SetUB("gender", "M", 1) 306 | 307 | assert.Equal(t, 2, k.MaxKSize()) 308 | matcher := &allMatcher{} 309 | 310 | time.Sleep(1 * time.Second) 311 | 312 | matched, err := matcher.Match(k, expr.Assignment{ 313 | expr.Label{Name: "age", Value: "3"}, 314 | expr.Label{Name: "state", Value: "CA"}, 315 | expr.Label{Name: "gender", Value: "M"}, 316 | }) 317 | assert.NoError(t, err) 318 | assert.ElementsMatch(t, []int{4, 5}, matched) 319 | 320 | k.Delete(4) 321 | 322 | time.Sleep(2 * time.Second) 323 | 324 | matched, err = matcher.Match(k, expr.Assignment{ 325 | expr.Label{Name: "age", Value: "3"}, 326 | expr.Label{Name: "state", Value: "CA"}, 327 | expr.Label{Name: "gender", Value: "M"}, 328 | }) 329 | assert.NoError(t, err) 330 | assert.ElementsMatch(t, []int{5}, matched) 331 | 332 | matched, err = matcher.Match(k, expr.Assignment{ 333 | expr.Label{Name: "age", Value: "3"}, 334 | expr.Label{Name: "state", Value: "NY"}, 335 | expr.Label{Name: "gender", Value: "F"}, 336 | }) 337 | assert.NoError(t, err) 338 | assert.ElementsMatch(t, []int{1, 2, 5}, matched) 339 | time.Sleep(1 * time.Second) 340 | 341 | topNMatcher := NewTopN(scoreMap) 342 | matched = topNMatcher.MatchTopN(1, k, expr.Assignment{ 343 | expr.Label{Name: "age", Value: "3", Weight: 8}, 344 | expr.Label{Name: "state", Value: "NY", Weight: 10}, 345 | expr.Label{Name: "gender", Value: "F", Weight: 9}, 346 | }) 347 | assert.ElementsMatch(t, []int{1}, matched) 348 | } 349 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------