Convert all warnings to strings
[0mirror.git] / search.py
blobc1486a642f27ffd797f10e56498d432d97c3fcc4
1 # Tool for querying the search index that 0mirror builds when mirroring feeds.
3 # Copyright (C) 2011, Anders F Bjorklund
4 # Copyright (C) 2013, Thomas Leonard
5 # See the COPYING file for details, or visit http://0install.net.
7 # This version for 0mirror is based on original code for 0install:
8 # http://thread.gmane.org/gmane.comp.file-systems.zero-install.devel/3847
10 from whoosh.index import open_dir
11 from whoosh.qparser import MultifieldParser
13 from xml.sax.saxutils import escape, quoteattr
15 import os, sys
17 class Searcher:
18 def __init__(self, index_dir):
19 index = open_dir(index_dir)
20 self.searcher = index.searcher()
22 fields = ["name", "summary", "description"]
23 self.parser = MultifieldParser(fields, schema=index.schema)
25 def query(self, query_string, out):
26 """out should take unicode and encode it as necessary"""
27 query = self.parser.parse(unicode(query_string))
28 results = self.searcher.search(query)
29 max_score = results and max([result.score for result in results]) or 0.0
31 out.write('<?xml version="1.0" ?>')
32 out.write("<results>")
33 for result in results:
34 uri = result["uri"]
35 name = result["name"]
36 summary = result.get("summary", "")
37 category = result.get("category", None)
39 s = 100.0 * result.score / max_score
41 out.write("<result uri=%s name=%s score='%d'>" % (quoteattr(uri), quoteattr(name), s))
42 out.write("<summary>%s</summary>" % escape(summary))
43 if category:
44 out.write("<category>%s</category>" % escape(category))
45 out.write("</result>")
46 out.write("</results>")