+class SearchResult(object):
+ def __init__(self, searcher, scoreDocs, score=None):
+ if score:
+ self.score = score
+ else:
+ self.score = scoreDocs.score
+
+ self.fragments = []
+ self.scores = {}
+ self.sections = []
+
+ stored = searcher.doc(scoreDocs.doc)
+ self.book_id = int(stored.get("book_id"))
+
+ fragment = stored.get("fragment_anchor")
+ if fragment:
+ self.fragments.append(fragment)
+ self.scores[fragment] = scoreDocs.score
+
+ header_type = stored.get("header_type")
+ if header_type:
+ sec = (header_type, int(stored.get("header_index")))
+ self.sections.append(sec)
+ self.scores[sec] = scoreDocs.score
+
+ def get_book(self):
+ return catalogue.models.Book.objects.get(id=self.book_id)
+
+ book = property(get_book)
+
+ def get_parts(self):
+ book = self.book
+ parts = [{"header": s[0], "position": s[1], '_score_key': s} for s in self.sections] \
+ + [{"fragment": book.fragments.get(anchor=f), '_score_key':f} for f in self.fragments]
+
+ parts.sort(lambda a, b: cmp(self.scores[a['_score_key']], self.scores[b['_score_key']]))
+ print("bookid: %d parts: %s" % (self.book_id, parts))
+ return parts
+
+ parts = property(get_parts)
+
+ def merge(self, other):
+ if self.book_id != other.book_id:
+ raise ValueError("this search result is or book %d; tried to merge with %d" % (self.book_id, other.book_id))
+ self.fragments += other.fragments
+ self.sections += other.sections
+ self.scores.update(other.scores)
+ if other.score > self.score:
+ self.score = other.score
+ return self
+
+ def __unicode__(self):
+ return u'SearchResult(book_id=%d, score=%d)' % (self.book_id, self.score)
+
+ @staticmethod
+ def aggregate(*result_lists):
+ books = {}
+ for rl in result_lists:
+ for r in rl:
+ if r.book_id in books:
+ books[r.book_id].merge(r)
+ #print(u"already have one with score %f, and this one has score %f" % (books[book.id][0], found.score))
+ else:
+ books[r.book_id] = r
+ return books.values()
+
+ def __cmp__(self, other):
+ return cmp(self.score, other.score)
+
+