7 # This index implementation uses Xapian for searching and GDBM for storage. It
8 # tends to be slightly faster than Ferret for indexing and significantly faster
9 # for searching due to precomputing thread membership.
10 class XapianIndex < BaseIndex
11 STEM_LANGUAGE = "english"
13 ## dates are converted to integers for xapian, and are used for document ids,
14 ## so we must ensure they're reasonably valid. this typically only affect
17 MAX_DATE = Time.at(2**31-1)
19 def initialize dir=BASE_DIR
22 @index_mutex = Monitor.new
26 @entries = MarshalledGDBM.new File.join(@dir, "entries.db")
27 @docids = MarshalledGDBM.new File.join(@dir, "docids.db")
28 @thread_members = MarshalledGDBM.new File.join(@dir, "thread_members.db")
29 @thread_ids = MarshalledGDBM.new File.join(@dir, "thread_ids.db")
30 @assigned_docids = GDBM.new File.join(@dir, "assigned_docids.db")
32 @xapian = Xapian::WritableDatabase.new(File.join(@dir, "xapian"), Xapian::DB_CREATE_OR_OPEN)
33 @term_generator = Xapian::TermGenerator.new()
34 @term_generator.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
35 @enquire = Xapian::Enquire.new @xapian
36 @enquire.weighting_scheme = Xapian::BoolWeight.new
37 @enquire.docid_order = Xapian::Enquire::ASCENDING
47 synchronize { @xapian.doccount }
51 synchronize { @entries.member? id }
55 synchronize { @entries[id][:source_id] }
59 synchronize { @xapian.delete_document @docids[id] }
63 entry = synchronize { @entries[id] }
66 source = SourceManager[entry[:source_id]]
67 raise "invalid source #{entry[:source_id]}" unless source
69 mk_addrs = lambda { |l| l.map { |e,n| "#{n} <#{e}>" } * ', ' }
70 mk_refs = lambda { |l| l.map { |r| "<#{r}>" } * ' ' }
72 'message-id' => entry[:message_id],
73 'date' => Time.at(entry[:date]),
74 'subject' => entry[:subject],
75 'from' => mk_addrs[[entry[:from]]],
76 'to' => mk_addrs[entry[:to]],
77 'cc' => mk_addrs[entry[:cc]],
78 'bcc' => mk_addrs[entry[:bcc]],
79 'reply-tos' => mk_refs[entry[:replytos]],
80 'references' => mk_refs[entry[:refs]],
83 m = Message.new :source => source, :source_info => entry[:source_info],
84 :labels => entry[:labels],
85 :snippet => entry[:snippet]
86 m.parse_header fake_header
90 def add_message m; sync_message m end
91 def update_message m; sync_message m end
92 def update_message_state m; sync_message m end
94 def sync_message m, opts={}
95 entry = synchronize { @entries[m.id] }
99 entry = {} if opts[:force_overwrite]
103 :source_id => m.source.id,
104 :source_info => m.source_info,
105 :date => (entry[:date] || m.date),
108 :from => (entry[:from] || [m.from.email, m.from.name]),
109 :to => (entry[:to] || m.to.map { |p| [p.email, p.name] }),
110 :cc => (entry[:cc] || m.cc.map { |p| [p.email, p.name] }),
111 :bcc => (entry[:bcc] || m.bcc.map { |p| [p.email, p.name] }),
113 :refs => (entry[:refs] || m.refs),
114 :replytos => (entry[:replytos] || m.replytos),
117 labels.each { |l| LabelManager << l }
120 index_message m, opts
121 union_threads([m.id] + m.refs + m.replytos)
126 private :sync_message
128 def num_results_for query={}
129 xapian_query = build_xapian_query query
130 matchset = run_query xapian_query, 0, 0, 100
131 matchset.matches_estimated
139 xapian_query = build_xapian_query query
141 ids = run_query_ids xapian_query, offset, (offset+page)
142 ids.each { |id| yield id }
143 break if ids.size < page
148 def each_id_by_date query={}
149 each_id(query) { |id| yield id, lambda { build_message id } }
152 def each_message_in_thread_for m, opts={}
153 # TODO thread by subject
154 # TODO handle killed threads
155 ids = synchronize { @thread_members[@thread_ids[m.id]] } || []
156 ids.select { |id| contains_id? id }.each { |id| yield id, lambda { build_message id } }
160 def load_contacts emails, opts={}
162 num = opts[:num] || 20
163 each_id_by_date :participants => emails do |id,b|
164 break if contacts.size >= num
166 ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
168 contacts.to_a.compact.map { |n,e| Person.new n, e }[0...num]
171 # TODO share code with the Ferret index
175 subs = s.gsub(/\b(to|from):(\S+)\b/) do
177 if(p = ContactManager.contact_for(name))
180 [field, "(" + AccountManager.user_emails.join("||") + ")"]
186 ## if we see a label:deleted or a label:spam term anywhere in the query
187 ## string, we set the extra load_spam or load_deleted options to true.
188 ## bizarre? well, because the query allows arbitrary parenthesized boolean
189 ## expressions, without fully parsing the query, we can't tell whether
190 ## the user is explicitly directing us to search spam messages or not.
191 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
192 ## search spam messages or not?
194 ## so, we rely on the fact that turning these extra options ON turns OFF
195 ## the adding of "-label:deleted" or "-label:spam" terms at the very
196 ## final stage of query processing. if the user wants to search spam
197 ## messages, not adding that is the right thing; if he doesn't want to
198 ## search spam messages, then not adding it won't have any effect.
199 query[:load_spam] = true if subs =~ /\blabel:spam\b/
200 query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
202 ## gmail style "is" operator
203 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
204 field, label = $1, $2
209 query[:load_spam] = true
212 query[:load_deleted] = true
219 ## gmail style attachments "filename" and "filetype" searches
220 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
221 field, name = $1, ($3 || $4)
224 debug "filename: translated #{field}:#{name} to attachment:\"#{name.downcase}\""
225 "attachment:\"#{name.downcase}\""
227 debug "filetype: translated #{field}:#{name} to attachment_extension:#{name.downcase}"
228 "attachment_extension:#{name.downcase}"
235 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
236 field, datestr = $1, ($3 || $4)
237 realdate = Chronic.parse datestr, :guess => false, :context => :past
241 debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
242 "date:#{realdate.end.to_i}..#{lastdate}"
244 debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
245 "date:#{firstdate}..#{realdate.end.to_i}"
247 debug "chronic: translated #{field}:#{datestr} to #{realdate}"
248 "date:#{realdate.begin.to_i}..#{realdate.end.to_i}"
251 raise ParseError, "can't understand date #{datestr.inspect}"
256 ## limit:42 restrict the search to 42 results
257 subs = subs.gsub(/\blimit:(\S+)\b/) do
260 query[:limit] = lim.to_i
263 raise ParseError, "non-numeric limit #{lim.inspect}"
267 qp = Xapian::QueryParser.new
268 qp.database = @xapian
269 qp.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
270 qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
271 qp.default_op = Xapian::Query::OP_AND
272 qp.add_valuerangeprocessor(Xapian::NumberValueRangeProcessor.new(DATE_VALUENO, 'date:', true))
273 NORMAL_PREFIX.each { |k,v| qp.add_prefix k, v }
274 BOOLEAN_PREFIX.each { |k,v| qp.add_boolean_prefix k, v }
275 xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE|Xapian::QueryParser::FLAG_BOOLEAN|Xapian::QueryParser::FLAG_LOVEHATE|Xapian::QueryParser::FLAG_WILDCARD, PREFIX['body'])
277 raise ParseError if xapian_query.nil? or xapian_query.empty?
278 query[:qobj] = xapian_query
298 'from_email' => 'FE',
304 'attachment_extension' => 'O',
307 PREFIX = NORMAL_PREFIX.merge BOOLEAN_PREFIX
311 MAX_TERM_LENGTH = 245
313 # Xapian can very efficiently sort in ascending docid order. Sup always wants
314 # to sort by descending date, so this method maps between them. In order to
315 # handle multiple messages per second, we use a logistic curve centered
316 # around MIDDLE_DATE so that the slope (docid/s) is greatest in this time
317 # period. A docid collision is not an error - the code will pick the next
318 # smallest unused one.
319 DOCID_SCALE = 2.0**32
321 MIDDLE_DATE = Time.gm(2011)
322 def assign_docid m, truncated_date
323 t = (truncated_date.to_i - MIDDLE_DATE.to_i).to_f
324 docid = (DOCID_SCALE - DOCID_SCALE/(Math::E**(-(t/TIME_SCALE)) + 1)).to_i
326 while @assigned_docids.member? [docid].pack("N")
331 @assigned_docids[[docid].pack("N")] = ''
336 @index_mutex.synchronize &b
339 def run_query xapian_query, offset, limit, checkatleast=0
341 @enquire.query = xapian_query
342 @enquire.mset(offset, limit-offset, checkatleast)
346 def run_query_ids xapian_query, offset, limit
347 matchset = run_query xapian_query, offset, limit
348 matchset.matches.map { |r| r.document.data }
352 def build_xapian_query opts
353 labels = ([opts[:label]] + (opts[:labels] || [])).compact
354 neglabels = [:spam, :deleted, :killed].reject { |l| (labels.include? l) || opts.member?("load_#{l}".intern) }
355 pos_terms, neg_terms = [], []
357 pos_terms << mkterm(:type, 'mail')
358 pos_terms.concat(labels.map { |l| mkterm(:label,l) })
359 pos_terms << opts[:qobj] if opts[:qobj]
360 pos_terms << mkterm(:source_id, opts[:source_id]) if opts[:source_id]
362 if opts[:participants]
363 participant_terms = opts[:participants].map { |p| mkterm(:email,:any, (Redwood::Person === p) ? p.email : p) }
364 pos_terms << Q.new(Q::OP_OR, participant_terms)
367 neg_terms.concat(neglabels.map { |l| mkterm(:label,l) })
369 pos_query = Q.new(Q::OP_AND, pos_terms)
370 neg_query = Q.new(Q::OP_OR, neg_terms)
375 Q.new(Q::OP_AND_NOT, [pos_query, neg_query])
379 def index_message m, opts
383 subject_text = m.indexable_subject
384 body_text = m.indexable_body
386 # Person names are indexed with several prefixes
387 person_termer = lambda do |d|
389 ["#{d}_name", "name", "body"].each do |x|
390 text << [p.name, PREFIX[x]]
392 [d, :any].each { |x| terms << mkterm(:email, x, p.email) }
396 person_termer[:from][m.from] if m.from
397 (m.to+m.cc+m.bcc).each(&(person_termer[:to]))
399 terms << mkterm(:date,m.date) if m.date
400 m.labels.each { |t| terms << mkterm(:label,t) }
401 terms << mkterm(:type, 'mail')
402 terms << mkterm(:source_id, m.source.id)
403 m.attachments.each do |a|
404 a =~ /\.(\w+)$/ or next
405 t = mkterm(:attachment_extension, $1)
409 # Full text search content
410 text << [subject_text, PREFIX['subject']]
411 text << [subject_text, PREFIX['body']]
412 text << [body_text, PREFIX['body']]
413 m.attachments.each { |a| text << [a, PREFIX['attachment']] }
415 truncated_date = if m.date < MIN_DATE
416 debug "warning: adjusting too-low date #{m.date} for indexing"
418 elsif m.date > MAX_DATE
419 debug "warning: adjusting too-high date #{m.date} for indexing"
425 # Date value for range queries
427 Xapian.sortable_serialise truncated_date.to_i
429 Xapian.sortable_serialise 0
432 doc = Xapian::Document.new
433 docid = @docids[m.id] || assign_docid(m, truncated_date)
435 @term_generator.document = doc
436 text.each { |text,prefix| @term_generator.index_text text, 1, prefix }
437 terms.each { |term| doc.add_term term if term.length <= MAX_TERM_LENGTH }
438 doc.add_value DATE_VALUENO, date_value
441 @xapian.replace_document docid, doc
442 @docids[m.id] = docid
445 # Construct a Xapian term
446 def mkterm type, *args
449 PREFIX['label'] + args[0].to_s.downcase
451 PREFIX['type'] + args[0].to_s.downcase
453 PREFIX['date'] + args[0].getutc.strftime("%Y%m%d%H%M%S")
456 when :from then PREFIX['from_email']
457 when :to then PREFIX['to_email']
458 when :any then PREFIX['email']
459 else raise "Invalid email term type #{args[0]}"
460 end + args[1].to_s.downcase
462 PREFIX['source_id'] + args[0].to_s.downcase
463 when :attachment_extension
464 PREFIX['attachment_extension'] + args[0].to_s.downcase
466 raise "Invalid term type #{type}"
470 # Join all the given message-ids into a single thread
471 def union_threads ids
472 seen_threads = Set.new
475 # Get all the ids that will be in the new thread
478 thread_id = @thread_ids[id]
479 if thread_id && !seen_threads.member?(thread_id)
480 thread_members = @thread_members[thread_id]
481 related.merge thread_members
482 seen_threads << thread_id
486 # Pick a leader and move all the others to its thread
488 best, *rest = a.sort_by { |x| x.hash }
489 @thread_members[best] = a
490 @thread_ids[best] = best
492 @thread_members.delete x
493 @thread_ids[x] = best
500 class MarshalledGDBM < GDBM
502 super k, Marshal.dump(v)
507 v ? Marshal.load(v) : nil