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 def initialize dir=BASE_DIR
16 @index_mutex = Monitor.new
18 @entries = MarshalledGDBM.new File.join(dir, "entries.db")
19 @docids = MarshalledGDBM.new File.join(dir, "docids.db")
20 @thread_members = MarshalledGDBM.new File.join(dir, "thread_members.db")
21 @thread_ids = MarshalledGDBM.new File.join(dir, "thread_ids.db")
22 @assigned_docids = GDBM.new File.join(dir, "assigned_docids.db")
24 @xapian = Xapian::WritableDatabase.new(File.join(dir, "xapian"), Xapian::DB_CREATE_OR_OPEN)
25 @term_generator = Xapian::TermGenerator.new()
26 @term_generator.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
27 @enquire = Xapian::Enquire.new @xapian
28 @enquire.weighting_scheme = Xapian::BoolWeight.new
29 @enquire.docid_order = Xapian::Enquire::ASCENDING
42 synchronize { @xapian.doccount }
46 synchronize { @entries.member? id }
50 synchronize { @entries[id][:source_id] }
54 synchronize { @xapian.delete_document @docids[id] }
58 entry = synchronize { @entries[id] }
61 source = SourceManager[entry[:source_id]]
62 raise "invalid source #{entry[:source_id]}" unless source
64 mk_addrs = lambda { |l| l.map { |e,n| "#{n} <#{e}>" } * ', ' }
65 mk_refs = lambda { |l| l.map { |r| "<#{r}>" } * ' ' }
67 'message-id' => entry[:message_id],
68 'date' => Time.at(entry[:date]),
69 'subject' => entry[:subject],
70 'from' => mk_addrs[[entry[:from]]],
71 'to' => mk_addrs[[entry[:to]]],
72 'cc' => mk_addrs[[entry[:cc]]],
73 'bcc' => mk_addrs[[entry[:bcc]]],
74 'reply-tos' => mk_refs[entry[:replytos]],
75 'references' => mk_refs[entry[:refs]],
78 m = Message.new :source => source, :source_info => entry[:source_info],
79 :labels => entry[:labels],
80 :snippet => entry[:snippet]
81 m.parse_header fake_header
85 def sync_message m, opts={}
86 entry = synchronize { @entries[m.id] }
90 entry = {} if opts[:force_overwrite]
94 :source_id => m.source.id,
95 :source_info => m.source_info,
96 :date => (entry[:date] || m.date),
98 :labels => labels.uniq,
99 :from => (entry[:from] || [m.from.email, m.from.name]),
100 :to => (entry[:to] || m.to.map { |p| [p.email, p.name] }),
101 :cc => (entry[:cc] || m.cc.map { |p| [p.email, p.name] }),
102 :bcc => (entry[:bcc] || m.bcc.map { |p| [p.email, p.name] }),
104 :refs => (entry[:refs] || m.refs),
105 :replytos => (entry[:replytos] || m.replytos),
108 m.labels.each { |l| LabelManager << l }
111 index_message m, opts
112 union_threads([m.id] + m.refs + m.replytos)
118 def num_results_for query={}
119 xapian_query = build_xapian_query query
120 matchset = run_query xapian_query, 0, 0, 100
121 matchset.matches_estimated
129 xapian_query = build_xapian_query query
131 ids = run_query_ids xapian_query, offset, (offset+page)
132 ids.each { |id| yield id }
133 break if ids.size < page
138 def each_id_by_date query={}
139 each_id(query) { |id| yield id, lambda { build_message id } }
142 def each_message_in_thread_for m, opts={}
143 # TODO thread by subject
144 # TODO handle killed threads
145 ids = synchronize { @thread_members[@thread_ids[m.id]] } || []
146 ids.select { |id| contains_id? id }.each { |id| yield id, lambda { build_message id } }
150 def load_contacts emails, opts={}
152 num = opts[:num] || 20
153 each_id_by_date :participants => emails do |id,b|
154 break if contacts.size >= num
156 ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
158 contacts.to_a.compact.map { |n,e| Person.new n, e }[0...num]
161 # TODO share code with the Ferret index
165 subs = s.gsub(/\b(to|from):(\S+)\b/) do
167 if(p = ContactManager.contact_for(name))
170 [field, "(" + AccountManager.user_emails.join("||") + ")"]
176 ## if we see a label:deleted or a label:spam term anywhere in the query
177 ## string, we set the extra load_spam or load_deleted options to true.
178 ## bizarre? well, because the query allows arbitrary parenthesized boolean
179 ## expressions, without fully parsing the query, we can't tell whether
180 ## the user is explicitly directing us to search spam messages or not.
181 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
182 ## search spam messages or not?
184 ## so, we rely on the fact that turning these extra options ON turns OFF
185 ## the adding of "-label:deleted" or "-label:spam" terms at the very
186 ## final stage of query processing. if the user wants to search spam
187 ## messages, not adding that is the right thing; if he doesn't want to
188 ## search spam messages, then not adding it won't have any effect.
189 query[:load_spam] = true if subs =~ /\blabel:spam\b/
190 query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
192 ## gmail style "is" operator
193 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
194 field, label = $1, $2
199 query[:load_spam] = true
202 query[:load_deleted] = true
209 ## gmail style attachments "filename" and "filetype" searches
210 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
211 field, name = $1, ($3 || $4)
214 Redwood::log "filename - translated #{field}:#{name} to attachment:\"#{name.downcase}\""
215 "attachment:\"#{name.downcase}\""
217 Redwood::log "filetype - translated #{field}:#{name} to attachment_extension:#{name.downcase}"
218 "attachment_extension:#{name.downcase}"
225 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
226 field, datestr = $1, ($3 || $4)
227 realdate = Chronic.parse datestr, :guess => false, :context => :past
231 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
232 "date:#{realdate.end.to_i}..#{lastdate}"
234 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
235 "date:#{firstdate}..#{realdate.end.to_i}"
237 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
238 "date:#{realdate.begin.to_i}..#{realdate.end.to_i}"
241 raise ParseError, "can't understand date #{datestr.inspect}"
246 ## limit:42 restrict the search to 42 results
247 subs = subs.gsub(/\blimit:(\S+)\b/) do
250 query[:limit] = lim.to_i
253 raise ParseError, "non-numeric limit #{lim.inspect}"
257 qp = Xapian::QueryParser.new
258 qp.database = @xapian
259 qp.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
260 qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
261 qp.default_op = Xapian::Query::OP_AND
262 qp.add_valuerangeprocessor(Xapian::NumberValueRangeProcessor.new(DATE_VALUENO, 'date:', true))
263 NORMAL_PREFIX.each { |k,v| qp.add_prefix k, v }
264 BOOLEAN_PREFIX.each { |k,v| qp.add_boolean_prefix k, v }
265 xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE|Xapian::QueryParser::FLAG_BOOLEAN|Xapian::QueryParser::FLAG_LOVEHATE|Xapian::QueryParser::FLAG_WILDCARD, PREFIX['body'])
267 raise ParseError if xapian_query.nil? or xapian_query.empty?
268 query[:qobj] = xapian_query
288 'from_email' => 'FE',
294 'attachment_extension' => 'O',
297 PREFIX = NORMAL_PREFIX.merge BOOLEAN_PREFIX
301 # Xapian can very efficiently sort in ascending docid order. Sup always wants
302 # to sort by descending date, so this method maps between them. In order to
303 # handle multiple messages per second, we use a logistic curve centered
304 # around MIDDLE_DATE so that the slope (docid/s) is greatest in this time
305 # period. A docid collision is not an error - the code will pick the next
306 # smallest unused one.
307 DOCID_SCALE = 2.0**32
309 MIDDLE_DATE = Time.gm(2011)
311 t = (m.date.to_i - MIDDLE_DATE.to_i).to_f
312 docid = (DOCID_SCALE - DOCID_SCALE/(Math::E**(-(t/TIME_SCALE)) + 1)).to_i
314 while @assigned_docids.member? [docid].pack("N")
319 @assigned_docids[[docid].pack("N")] = ''
324 @index_mutex.synchronize &b
327 def run_query xapian_query, offset, limit, checkatleast=0
329 @enquire.query = xapian_query
330 @enquire.mset(offset, limit-offset, checkatleast)
334 def run_query_ids xapian_query, offset, limit
335 matchset = run_query xapian_query, offset, limit
336 matchset.matches.map { |r| r.document.data }
340 def build_xapian_query opts
341 labels = ([opts[:label]] + (opts[:labels] || [])).compact
342 neglabels = [:spam, :deleted, :killed].reject { |l| (labels.include? l) || opts.member?("load_#{l}".intern) }
343 pos_terms, neg_terms = [], []
345 pos_terms << mkterm(:type, 'mail')
346 pos_terms.concat(labels.map { |l| mkterm(:label,l) })
347 pos_terms << opts[:qobj] if opts[:qobj]
348 pos_terms << mkterm(:source_id, opts[:source_id]) if opts[:source_id]
350 if opts[:participants]
351 participant_terms = opts[:participants].map { |p| mkterm(:email,:any, (Redwood::Person === p) ? p.email : p) }
352 pos_terms << Q.new(Q::OP_OR, participant_terms)
355 neg_terms.concat(neglabels.map { |l| mkterm(:label,l) })
357 pos_query = Q.new(Q::OP_AND, pos_terms)
358 neg_query = Q.new(Q::OP_OR, neg_terms)
363 Q.new(Q::OP_AND_NOT, [pos_query, neg_query])
367 def index_message m, opts
371 subject_text = m.indexable_subject
372 body_text = m.indexable_body
374 # Person names are indexed with several prefixes
375 person_termer = lambda do |d|
377 ["#{d}_name", "name", "body"].each do |x|
378 text << [p.name, PREFIX[x]]
380 [d, :any].each { |x| terms << mkterm(:email, x, p.email) }
384 person_termer[:from][m.from] if m.from
385 (m.to+m.cc+m.bcc).each(&(person_termer[:to]))
387 terms << mkterm(:date,m.date) if m.date
388 m.labels.each { |t| terms << mkterm(:label,t) }
389 terms << mkterm(:type, 'mail')
390 terms << mkterm(:source_id, m.source.id)
391 m.attachments.each do |a|
392 a =~ /\.(\w+)$/ or next
393 t = mkterm(:attachment_extension, $1)
397 # Full text search content
398 text << [subject_text, PREFIX['subject']]
399 text << [subject_text, PREFIX['body']]
400 text << [body_text, PREFIX['body']]
401 m.attachments.each { |a| text << [a, PREFIX['attachment']] }
403 # Date value for range queries
404 date_value = Xapian.sortable_serialise(m.date.to_i)
406 doc = Xapian::Document.new
407 docid = @docids[m.id] || assign_docid(m)
409 @term_generator.document = doc
410 text.each { |text,prefix| @term_generator.index_text text, 1, prefix }
411 terms.each { |term| doc.add_term term }
412 doc.add_value DATE_VALUENO, date_value
415 @xapian.replace_document docid, doc
416 @docids[m.id] = docid
419 # Construct a Xapian term
420 def mkterm type, *args
423 PREFIX['label'] + args[0].to_s.downcase
425 PREFIX['type'] + args[0].to_s.downcase
427 PREFIX['date'] + args[0].getutc.strftime("%Y%m%d%H%M%S")
430 when :from then PREFIX['from_email']
431 when :to then PREFIX['to_email']
432 when :any then PREFIX['email']
433 else raise "Invalid email term type #{args[0]}"
434 end + args[1].to_s.downcase
436 PREFIX['source_id'] + args[0].to_s.downcase
437 when :attachment_extension
438 PREFIX['attachment_extension'] + args[0].to_s.downcase
440 raise "Invalid term type #{type}"
444 # Join all the given message-ids into a single thread
445 def union_threads ids
446 seen_threads = Set.new
449 # Get all the ids that will be in the new thread
452 thread_id = @thread_ids[id]
453 if thread_id && !seen_threads.member?(thread_id)
454 thread_members = @thread_members[thread_id]
455 related.merge thread_members
456 seen_threads << thread_id
460 # Pick a leader and move all the others to its thread
462 best, *rest = a.sort_by { |x| x.hash }
463 @thread_members[best] = a
464 @thread_ids[best] = best
466 @thread_members.delete x
467 @thread_ids[x] = best
474 class MarshalledGDBM < GDBM
476 super k, Marshal.dump(v)
481 v ? Marshal.load(v) : nil