6 # This index implementation uses Xapian for searching and GDBM for storage. It
7 # tends to be slightly faster than Ferret for indexing and significantly faster
8 # for searching due to precomputing thread membership.
9 class XapianIndex < BaseIndex
10 STEM_LANGUAGE = "english"
12 ## dates are converted to integers for xapian, and are used for document ids,
13 ## so we must ensure they're reasonably valid. this typically only affect
16 MAX_DATE = Time.at(2**31-1)
18 def initialize dir=BASE_DIR
21 @index_mutex = Monitor.new
25 @xapian = Xapian::WritableDatabase.new(File.join(@dir, "xapian"), Xapian::DB_CREATE_OR_OPEN)
26 @term_generator = Xapian::TermGenerator.new()
27 @term_generator.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
28 @enquire = Xapian::Enquire.new @xapian
29 @enquire.weighting_scheme = Xapian::BoolWeight.new
30 @enquire.docid_order = Xapian::Enquire::ASCENDING
40 synchronize { @xapian.doccount }
44 synchronize { find_docid(id) && true }
48 synchronize { get_entry(id)[:source_id] }
52 synchronize { @xapian.delete_document mkterm(:msgid, id) }
56 entry = synchronize { get_entry id }
59 source = SourceManager[entry[:source_id]]
60 raise "invalid source #{entry[:source_id]}" unless source
62 mk_addrs = lambda { |l| l.map { |e,n| "#{n} <#{e}>" } * ', ' }
63 mk_refs = lambda { |l| l.map { |r| "<#{r}>" } * ' ' }
65 'message-id' => entry[:message_id],
66 'date' => Time.at(entry[:date]),
67 'subject' => entry[:subject],
68 'from' => mk_addrs[[entry[:from]]],
69 'to' => mk_addrs[entry[:to]],
70 'cc' => mk_addrs[entry[:cc]],
71 'bcc' => mk_addrs[entry[:bcc]],
72 'reply-tos' => mk_refs[entry[:replytos]],
73 'references' => mk_refs[entry[:refs]],
76 m = Message.new :source => source, :source_info => entry[:source_info],
77 :labels => entry[:labels],
78 :snippet => entry[:snippet]
79 m.parse_header fake_header
83 def sync_message m, opts={}
84 entry = synchronize { get_entry m.id }
88 entry = {} if opts[:force_overwrite]
92 :source_id => m.source.id,
93 :source_info => m.source_info,
94 :date => (entry[:date] || m.date),
96 :labels => labels.uniq,
97 :from => (entry[:from] || [m.from.email, m.from.name]),
98 :to => (entry[:to] || m.to.map { |p| [p.email, p.name] }),
99 :cc => (entry[:cc] || m.cc.map { |p| [p.email, p.name] }),
100 :bcc => (entry[:bcc] || m.bcc.map { |p| [p.email, p.name] }),
102 :refs => (entry[:refs] || m.refs),
103 :replytos => (entry[:replytos] || m.replytos),
106 m.labels.each { |l| LabelManager << l }
109 index_message m, d, opts
114 def num_results_for query={}
115 xapian_query = build_xapian_query query
116 matchset = run_query xapian_query, 0, 0, 100
117 matchset.matches_estimated
125 xapian_query = build_xapian_query query
127 ids = run_query_ids xapian_query, offset, (offset+page)
128 ids.each { |id| yield id }
129 break if ids.size < page
134 def each_id_by_date query={}
135 each_id(query) { |id| yield id, lambda { build_message id } }
138 def each_message_in_thread_for m, opts={}
139 # TODO thread by subject
140 # TODO handle killed threads
141 return unless doc = find_doc(m.id)
142 queue = doc.value(THREAD_VALUENO).split(',')
144 seen_threads = Set.new
145 seen_messages = Set.new [m.id]
146 while not queue.empty?
147 thread_id = queue.pop
148 next if seen_threads.member? thread_id
149 return false if thread_killed? thread_id
150 seen_threads << thread_id
151 docs = term_docids(mkterm(:thread, thread_id)).map { |x| @xapian.document x }
153 msgid = doc.value MSGID_VALUENO
154 next if seen_messages.member? msgid
156 seen_messages << msgid
157 queue.concat doc.value(THREAD_VALUENO).split(',')
160 msgids.each { |id| yield id, lambda { build_message id } }
164 def load_contacts emails, opts={}
166 num = opts[:num] || 20
167 each_id_by_date :participants => emails do |id,b|
168 break if contacts.size >= num
170 ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
172 contacts.to_a.compact.map { |n,e| Person.new n, e }[0...num]
175 # TODO share code with the Ferret index
179 subs = s.gsub(/\b(to|from):(\S+)\b/) do
181 if(p = ContactManager.contact_for(name))
184 [field, "(" + AccountManager.user_emails.join("||") + ")"]
190 ## if we see a label:deleted or a label:spam term anywhere in the query
191 ## string, we set the extra load_spam or load_deleted options to true.
192 ## bizarre? well, because the query allows arbitrary parenthesized boolean
193 ## expressions, without fully parsing the query, we can't tell whether
194 ## the user is explicitly directing us to search spam messages or not.
195 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
196 ## search spam messages or not?
198 ## so, we rely on the fact that turning these extra options ON turns OFF
199 ## the adding of "-label:deleted" or "-label:spam" terms at the very
200 ## final stage of query processing. if the user wants to search spam
201 ## messages, not adding that is the right thing; if he doesn't want to
202 ## search spam messages, then not adding it won't have any effect.
203 query[:load_spam] = true if subs =~ /\blabel:spam\b/
204 query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
206 ## gmail style "is" operator
207 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
208 field, label = $1, $2
213 query[:load_spam] = true
216 query[:load_deleted] = true
223 ## gmail style attachments "filename" and "filetype" searches
224 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
225 field, name = $1, ($3 || $4)
228 Redwood::log "filename - translated #{field}:#{name} to attachment:\"#{name.downcase}\""
229 "attachment:\"#{name.downcase}\""
231 Redwood::log "filetype - translated #{field}:#{name} to attachment_extension:#{name.downcase}"
232 "attachment_extension:#{name.downcase}"
239 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
240 field, datestr = $1, ($3 || $4)
241 realdate = Chronic.parse datestr, :guess => false, :context => :past
245 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
246 "date:#{realdate.end.to_i}..#{lastdate}"
248 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
249 "date:#{firstdate}..#{realdate.end.to_i}"
251 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
252 "date:#{realdate.begin.to_i}..#{realdate.end.to_i}"
255 raise ParseError, "can't understand date #{datestr.inspect}"
260 ## limit:42 restrict the search to 42 results
261 subs = subs.gsub(/\blimit:(\S+)\b/) do
264 query[:limit] = lim.to_i
267 raise ParseError, "non-numeric limit #{lim.inspect}"
271 qp = Xapian::QueryParser.new
272 qp.database = @xapian
273 qp.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
274 qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
275 qp.default_op = Xapian::Query::OP_AND
276 qp.add_valuerangeprocessor(Xapian::NumberValueRangeProcessor.new(DATE_VALUENO, 'date:', true))
277 NORMAL_PREFIX.each { |k,v| qp.add_prefix k, v }
278 BOOLEAN_PREFIX.each { |k,v| qp.add_boolean_prefix k, v }
279 xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE|Xapian::QueryParser::FLAG_BOOLEAN|Xapian::QueryParser::FLAG_LOVEHATE|Xapian::QueryParser::FLAG_WILDCARD, PREFIX['body'])
281 raise ParseError if xapian_query.nil? or xapian_query.empty?
282 query[:qobj] = xapian_query
302 'from_email' => 'FE',
308 'attachment_extension' => 'O',
314 PREFIX = NORMAL_PREFIX.merge BOOLEAN_PREFIX
320 MAX_TERM_LENGTH = 245
322 # Xapian can very efficiently sort in ascending docid order. Sup always wants
323 # to sort by descending date, so this method maps between them. In order to
324 # handle multiple messages per second, we use a logistic curve centered
325 # around MIDDLE_DATE so that the slope (docid/s) is greatest in this time
326 # period. A docid collision is not an error - the code will pick the next
327 # smallest unused one.
328 DOCID_SCALE = 2.0**32
330 MIDDLE_DATE = Time.gm(2011)
331 def assign_docid m, truncated_date
332 t = (truncated_date.to_i - MIDDLE_DATE.to_i).to_f
333 docid = (DOCID_SCALE - DOCID_SCALE/(Math::E**(-(t/TIME_SCALE)) + 1)).to_i
334 while docid > 0 and docid_exists? docid
337 docid > 0 ? docid : nil
340 # XXX is there a better way?
341 def docid_exists? docid
343 @xapian.doclength docid
345 rescue RuntimeError #Xapian::DocNotFoundError
346 raise unless $!.message =~ /DocNotFoundError/
352 @xapian.postlist(term).map { |x| x.docid }
356 term_docids(mkterm(:msgid,id)).tap { |x| fail unless x.size <= 1 }.first
360 return unless docid = find_docid(id)
361 @xapian.document docid
365 return unless doc = @xapian.document(docid)
366 doc.value MSGID_VALUENO
370 return unless doc = find_doc(id)
371 Marshal.load doc.data
374 def thread_killed? thread_id
375 not run_query(Q.new(Q::OP_AND, mkterm(:thread, thread_id), mkterm(:label, :Killed)), 0, 1).empty?
379 @index_mutex.synchronize &b
382 def run_query xapian_query, offset, limit, checkatleast=0
384 @enquire.query = xapian_query
385 @enquire.mset(offset, limit-offset, checkatleast)
389 def run_query_ids xapian_query, offset, limit
390 matchset = run_query xapian_query, offset, limit
391 matchset.matches.map { |r| r.document.value MSGID_VALUENO }
395 def build_xapian_query opts
396 labels = ([opts[:label]] + (opts[:labels] || [])).compact
397 neglabels = [:spam, :deleted, :killed].reject { |l| (labels.include? l) || opts.member?("load_#{l}".intern) }
398 pos_terms, neg_terms = [], []
400 pos_terms << mkterm(:type, 'mail')
401 pos_terms.concat(labels.map { |l| mkterm(:label,l) })
402 pos_terms << opts[:qobj] if opts[:qobj]
403 pos_terms << mkterm(:source_id, opts[:source_id]) if opts[:source_id]
405 if opts[:participants]
406 participant_terms = opts[:participants].map { |p| mkterm(:email,:any, (Redwood::Person === p) ? p.email : p) }
407 pos_terms << Q.new(Q::OP_OR, participant_terms)
410 neg_terms.concat(neglabels.map { |l| mkterm(:label,l) })
412 pos_query = Q.new(Q::OP_AND, pos_terms)
413 neg_query = Q.new(Q::OP_OR, neg_terms)
418 Q.new(Q::OP_AND_NOT, [pos_query, neg_query])
422 def index_message m, entry, opts
426 subject_text = m.indexable_subject
427 body_text = m.indexable_body
429 # Person names are indexed with several prefixes
430 person_termer = lambda do |d|
432 ["#{d}_name", "name", "body"].each do |x|
433 text << [p.name, PREFIX[x]]
435 [d, :any].each { |x| terms << mkterm(:email, x, p.email) }
439 person_termer[:from][m.from] if m.from
440 (m.to+m.cc+m.bcc).each(&(person_termer[:to]))
442 terms << mkterm(:date,m.date) if m.date
443 m.labels.each { |t| terms << mkterm(:label,t) }
444 terms << mkterm(:type, 'mail')
445 terms << mkterm(:msgid, m.id)
446 terms << mkterm(:source_id, m.source.id)
447 m.attachments.each do |a|
448 a =~ /\.(\w+)$/ or next
449 t = mkterm(:attachment_extension, $1)
454 children = term_docids(mkterm(:ref, m.id)).map { |docid| @xapian.document docid }
455 parent_ids = m.refs + m.replytos
456 parents = parent_ids.map { |id| find_doc id }.compact
457 thread_members = SavingHash.new { [] }
458 (children + parents).each do |doc2|
459 thread_ids = doc2.value(THREAD_VALUENO).split ','
460 thread_ids.each { |thread_id| thread_members[thread_id] << doc2 }
463 thread_ids = thread_members.empty? ? [m.id] : thread_members.keys
465 thread_ids.each { |thread_id| terms << mkterm(:thread, thread_id) }
466 parent_ids.each do |ref|
467 terms << mkterm(:ref, ref)
470 # Full text search content
471 text << [subject_text, PREFIX['subject']]
472 text << [subject_text, PREFIX['body']]
473 text << [body_text, PREFIX['body']]
474 m.attachments.each { |a| text << [a, PREFIX['attachment']] }
476 truncated_date = if m.date < MIN_DATE
477 Redwood::log "warning: adjusting too-low date #{m.date} for indexing"
479 elsif m.date > MAX_DATE
480 Redwood::log "warning: adjusting too-high date #{m.date} for indexing"
486 # Date value for range queries
488 Xapian.sortable_serialise truncated_date.to_i
490 Xapian.sortable_serialise 0
494 unless doc = find_doc(m.id)
495 doc = Xapian::Document.new
496 if not docid = assign_docid(m, truncated_date)
497 # Could be triggered by spam
498 Redwood::log "warning: docid underflow, dropping #{m.id.inspect}"
507 @term_generator.document = doc
508 text.each { |text,prefix| @term_generator.index_text text, 1, prefix }
509 terms.each { |term| doc.add_term term if term.length <= MAX_TERM_LENGTH }
510 doc.add_value MSGID_VALUENO, m.id
511 doc.add_value THREAD_VALUENO, (thread_ids * ',')
512 doc.add_value DATE_VALUENO, date_value
513 doc.data = Marshal.dump entry
515 @xapian.replace_document docid, doc
518 # Construct a Xapian term
519 def mkterm type, *args
522 PREFIX['label'] + args[0].to_s.downcase
524 PREFIX['type'] + args[0].to_s.downcase
526 PREFIX['date'] + args[0].getutc.strftime("%Y%m%d%H%M%S")
529 when :from then PREFIX['from_email']
530 when :to then PREFIX['to_email']
531 when :any then PREFIX['email']
532 else raise "Invalid email term type #{args[0]}"
533 end + args[1].to_s.downcase
535 PREFIX['source_id'] + args[0].to_s.downcase
536 when :attachment_extension
537 PREFIX['attachment_extension'] + args[0].to_s.downcase
538 when :msgid, :ref, :thread
539 PREFIX[type.to_s] + args[0][0...(MAX_TERM_LENGTH-1)]
541 raise "Invalid term type #{type}"