Commits

Yuuki Ito  committed 3484206

検索ロジック組み込み

  • Participants
  • Parent commits 6b6ad76
  • Branches feature/whoosh-search

Comments (0)

Files changed (2)

File src/memocurial/__init__.py

 # -*- coding: utf-8 -*-
 import os
 import re
+import sys
 from datetime import datetime
 from flask import Flask, request, session, g, redirect, url_for, \
      abort, render_template, flash, send_file
 from memocurial.app import app
 from memocurial.models import *
 
-
 def init_db():
     """Create the database tables."""
     db.init_app(app)
         return reduce(lambda x, y: x & y,
                       [m.error is None for m in self.manifests])
 
+## whoosh --------------------------------------------------
+
+class Searcher:
+
+    ix_path = ''
+
+    def __init__(self, ix_path):
+        self.ix_path = ix_path
+
+    def search(self, query_str):
+
+        from whoosh import index
+        from whoosh.fields import Schema, NGRAM, NGRAMWORDS
+        from whoosh.qparser import DisMaxParser
+        ix = index.open_dir(self.ix_path)
+        schema = Schema(body1=NGRAM(stored=True), body2=NGRAMWORDS(stored=True))
+        searcher = ix.searcher()
+        print query_str
+        parser = DisMaxParser({"body1": 0.5, "body2": 0.5}, schema)
+        query = parser.parse(query_str)
+
+        results = searcher.search(query)
+
+        ix.close()
+        return results
+
+    def index_list(self, query_str):
+        list = []
+        results = self.search(query_str)
+        for result in results:
+            list.append(result['id'])
+
+        return list
+
 
 @app.route('/', methods=['GET', 'POST'])
 def index():
 @app.route('/list')
 @app.route('/list/<int:page>')
 def list(page=1):
+    q = request.args.get('q')
     items_per_page = int(app.config['ITEMS_PER_PAGE'])
-    pagination = Paste.query.order_by('id desc').paginate(page, items_per_page)
-    return render_template('list.html', pagination=pagination)
+    if not q:
+        pagination = Paste.query.order_by('id desc').paginate(page, items_per_page)
+    else:
+        searcher = Searcher(app.config['WHOOSH_ROOT'])
+        pagination = Paste.query.order_by('id desc').filter(Paste.id.in_(searcher.index_list(q))).paginate(page, items_per_page)
+
+    return render_template('list.html', pagination=pagination, q=q)
 
 
 @app.route('/about')

File src/memocurial/templates/list.html

 <div class="row">
   <div class="span12">
     <form method="GET" action="{{ action}}">
-        <div class="clearfix">
-          <input type="text" placeholder="" name="" id="" class="span7" /><input type="submit" value="Search" class="btn primary pull-center" />
-        </div>
+      <div class="clearfix">
+        <input type="text" placeholder="" name="q" id="" class="span7" value="{{ q }}"/><input type="submit" value="Search" class="btn primary pull-center" />
+      </div>
     </form>
   </div>
 </div>