我想让用户能够在user模型中的多个列中搜索其他用户。即first_name、last_name和email字段。我现在正在做MySQL全文搜索,但我不相信这是我继续的正确方式。有没有人知道MySQL全文搜索与Solr和其他第三方提供商相比有多大优势?
我把searchify和websolr看作是潜在的。但是对于1个表跨3列执行全文搜索,这样做值得吗?
发布于 2012-07-24 12:08:30
根据数据库本身进行搜索相当慢。推荐的方法是使用搜索引擎,如Solr、Whoosh等来生成索引。Haystack是一个非常有用的django应用程序,它可以让你抽象搜索引擎,并在索引时使用模板。
所以有了这个模板,你就可以拥有一个这样的模板:
{{user.first_name}}
{{user. last_name}}
{{user.email}}它会生成你想要的搜索结果。
发布于 2012-07-24 12:42:02
我就是这么做的
#search.py
import re
from django.db.models import Q
def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r'\s{2,}').sub):
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]
def get_query(query_string, search_fields):
query = None
terms = normalize_query(query_string)
for term in terms:
or_query = None
for field_name in search_fields:
q = Q(**{"%s__icontains" % field_name: term})
if or_query is None:
or_query = q
else:
or_query = or_query | q
if query is None:
query = or_query
else:
query = query & or_query
return query视图:
# views.py
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
def search(request):
query = request.GET.get('q', '')
if query:
entry_query = get_query(query, ['first_name', 'last_name', 'email'])
users = User.objects.filter(entry_query).order_by('-pub_date')
else:
entries_list = []
return render_response(request, 'blog/list.html', {'entries': entries_list})https://stackoverflow.com/questions/11623409
复制相似问题