-
-
Save yxlwfds/5064120 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import whoosh,os | |
from whoosh import index | |
import whoosh.index | |
import whoosh.qparser | |
import tornado.ioloop | |
import tornado.web | |
class Search(object): | |
def __init__(self, indexdir, searchstr): | |
self.indexdir = indexdir | |
self.searchstr = searchstr | |
def searcher(self): | |
schema = whoosh.fields.Schema( | |
path = whoosh.fields.ID(unique=True, stored=True), | |
title = whoosh.fields.TEXT(stored=True, phrase=False), | |
content = whoosh.fields.TEXT(), | |
tag = whoosh.fields.TEXT(stored=True), | |
category = whoosh.fields.TEXT(stored=True)) | |
if not os.path.exists(self.indexdir): | |
os.mkdir(self.indexdir) | |
ix = index.create_in(self.indexdir, schema) | |
writer = ix.writer() | |
writer.add_document(title=u"Welcome", content=u"This is welcome blog!", | |
path=u"/welcome", tag=u"Welcome", category=u"Welcome") | |
writer.add_document(title=u"Python Whoosh", content=u"Whoosh search library in pure Python", | |
path=u"/whoosh", tag=u"whoosh", category=u"Search") | |
writer.add_document(title=u"Python Tornado", content=u"Tornado Web Server for real-time web apps", | |
path=u"/tornado", tag=u"tornado", category=u"Web Server") | |
writer.commit() | |
_queryparser = whoosh.qparser.QueryParser('content', schema=schema) | |
s = ix.searcher() | |
return s.search(_queryparser.parse( | |
unicode(self.searchstr)), limit=50) | |
class Home(tornado.web.RequestHandler): | |
def get(self): | |
self.render('searchform.html') | |
class Srch(tornado.web.RequestHandler): | |
def get(self): | |
q = self.get_argument("q") | |
srch = Search('./indexdir', q) | |
results = srch.searcher() | |
self.write(str(results)) | |
application = tornado.web.Application([ | |
(r"/",Home ), | |
(r"/search",Srch ), | |
]) | |
if __name__ == "__main__": | |
application.listen(8888) | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment