Skip to content

Instantly share code, notes, and snippets.

@svankie
Created April 30, 2011 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svankie/949703 to your computer and use it in GitHub Desktop.
Save svankie/949703 to your computer and use it in GitHub Desktop.
whoosh code
# index.py
import os
from whoosh.fields import Schema, TEXT as text, ID as id
from whoosh.index import create_in, open_dir
schema = Schema(
title=text(stored=True),
description=text(stored=True),
date=id)
if not os.path.exists("index"):
os.mkdir("index")
idx = create_in("index", schema)
index = open_dir("index")
# index_builder.py
from clew.search.index import index
class IndexBuilder(object):
"""
Hoping this would be easy enough.
"""
def __init__(self):
self.writer = index.writer()
def build(self, events):
for event in events:
date = unicode(event.date.strftime('%Y-%m-%d'))
self.writer.add_document(title=event.name,
description=event.description,
date=date)
self.writer.commit()
# run_builder.py
from clew.core.model import Event
from clew.search.index_builder import IndexBuilder
if __name__ == '__main__':
print "Building object index..."
idx_builder = IndexBuilder()
events = Event.query.all()
if events:
idx_builder.build(events)
print "Done."
else:
print "No events to be added."
# searcher.py
from whoosh.qparser.default import QueryParser
from clew.search.index import index
class EventSearcher(object):
def __init__(self):
self.searcher = index.searcher()
self.parser = QueryParser("description", index.schema)
def search(self, query):
try:
query = self.parser.parse(query)
res = self.searcher.search(query)
return res
finally:
self.searcher.close()
# es llamado desde un 'controlador'
@app.route("/search", methods=['GET'])
def search():
es = EventSearcher()
terms = unicode(" ".join(request.query_string.split("=")[1].split("+"))) # ya sé
results = es.search(terms)
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment