Class: Factbase::IndexedAnd

Inherits:
Object
  • Object
show all
Defined in:
lib/factbase/indexed/indexed_and.rb

Overview

Indexed term ‘and’.

Instance Method Summary collapse

Constructor Details

#initialize(term, idx) ⇒ IndexedAnd

Returns a new instance of IndexedAnd.



8
9
10
11
# File 'lib/factbase/indexed/indexed_and.rb', line 8

def initialize(term, idx)
  @term = term
  @idx = idx
end

Instance Method Details

#predict(maps, fb, params) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/factbase/indexed/indexed_and.rb', line 13

def predict(maps, fb, params)
  return nil if @idx.nil?
  key = [maps.object_id, @term.operands.first, @term.op]
  r = nil
  if @term.operands.all? { |o| o.op == :eq } && @term.operands.size > 1 \
    && @term.operands.all? { |o| o.operands.first.is_a?(Symbol) && _scalar?(o.operands[1]) }
    props = @term.operands.map { |o| o.operands.first }.sort
    key = [maps.object_id, props, :multi_and_eq]
    if @idx[key].nil?
      @idx[key] = {}
      maps.to_a.each do |m|
        _all_tuples(m, props).each do |t|
          @idx[key][t] = [] if @idx[key][t].nil?
          @idx[key][t].append(m)
        end
      end
    end
    tuples = Enumerator.product(
      *@term.operands.sort_by { |o| o.operands.first }.map do |o|
        if o.operands[1].is_a?(Symbol)
          params[o.operands[1].to_s] || []
        else
          [o.operands[1]]
        end
      end
    )
    j = tuples.map { |t| @idx[key][t] || [] }.reduce(&:|)
    r = (maps & []) | j
  else
    @term.operands.each do |o|
      n = o.predict(maps, fb, params)
      break if n.nil?
      if r.nil?
        r = n
      elsif n.size < r.size * 8 # to skip some obvious matchings
        r &= n.to_a
      end
      break if r.size < maps.size / 32 # it's already small enough
      break if r.size < 128 # it's obviously already small enough
    end
  end
  r
end