PCv5/app/routes/search.py

32 lines
1.7 KiB
Python
Raw Normal View History

from app import app, db
from app.forms.search import AdvancedSearchForm, SearchForm
from app.models.post import Post
2019-02-03 16:20:05 +01:00
from app.utils.render import render
from sqlalchemy import text
from flask import request
2019-02-03 16:20:05 +01:00
2019-12-16 23:57:50 +01:00
@app.route('/rechercher')
2019-02-03 16:20:05 +01:00
def search():
form = AdvancedSearchForm(request.args)
results = list()
if form.validate():
# Topics are sorted first in results
topics = text("""SELECT topic.id, ts_headline(topic.title, query, 'StartSel=<<, StopSel=>>') AS headline, ts_rank_cd(textsearch, query) AS rank, MAX(topic.title)
FROM topic, websearch_to_tsquery_multilang(:keywords) query, to_tsvector_multilang(topic.title) textsearch
WHERE query @@ textsearch
GROUP BY topic.id,query,textsearch
ORDER BY rank DESC;""")
results = list(db.session.execute(topics, {'keywords': '%' + form.q.data + '%'}))
# Comments are less important than topics and programs
forums = text("""SELECT comment.id, ts_headline(comment.text, query, 'StartSel=<<, StopSel=>>') AS headline, ts_rank_cd(textsearch, query) AS rank, MAX(topic.title) as title
FROM comment, websearch_to_tsquery_multilang(:keywords) query, to_tsvector_multilang(comment.text) textsearch, topic, program
WHERE query @@ textsearch
AND comment.thread_id = topic.thread_id
GROUP BY comment.id,query,textsearch
ORDER BY rank DESC;""")
results.extend(list(db.session.execute(forums, {'keywords': '%' + form.q.data + '%'})))
print(results)
return render('search.html', form=form, results=results)