7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flaskを用いたwebサイトでのサイト内検索の実装

Last updated at Posted at 2017-11-15

Flaskを使ってWebページを構築していると、サイト内検索を実装したくなった。
Googleカスタム検索で実装してもよかったが、折角なのでMongoDBとflask-mongoengineを使って構築した。

構築環境

  • python
  • flask
  • mongoDB
  • flask-mongoengine

データベースのコレクションはsampleだとする。
フィールドは performer,Genre,title があるとする。

コードは以下の通り

search.py
import flask
from flask import *
from flask_mongoengine import MongoEngine
from mongoengine.queryset.visitor import Q

@app.route('/search', methods=['GET'])
def search():
    #GETメソッドで取得した値があれば、スペースで区切った配列にする
    if request.args.get('message') != None:
        search_list = request.args.get('message').split()
    page_num = int(flask.request.args.get('page') or 1)
    result = sample.objects()
    for i in search_list:
        #繰り返しクエリを投げることでAnd検索を表現。
        #Like検索は /'検索したい文字'/。しかし、ここでは変数を使っているので、'/' + i + '/' と書くと'/検索したい文字/'となってしまうので'$regex'ノーテーションを使う
        #Q() | Q() で or 条件にできる。
        result = result(Q(__raw__ ={'performer':{'$regex': i }}) | Q(__raw__ = {'title': {'$regex': i }}) | Q(__raw__ = {'Genre': {'$regex': i }}))
    result = result.paginate(page=page_num, per_page=30)
    return flask.render_template("search.html", result=result)

flask-mongoengine のpaginateメソッドを用いて検索結果のコンテンツを1ページに30個表示するように設定している。
見たとおり、or検索は実装していないが、あまり使わないので必要ないかと感じた。

あまり日本語でflaskとmongodbを組み合わせてwebサイトを作るといった趣旨の情報が少ないので、少しでも同胞の助けになれば。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?