搜索¶
搜索 QuerySet¶
Wagtail 的搜索建立在 Django 的 QuerySet API 之上。只要模型以及被过滤的字段已加入搜索索引,你就应当能够搜索任何 Django QuerySet。
搜索页面¶
Wagtail 为搜索页面提供了一个快捷方式:.search() 这个 QuerySet 方法。你可以在任何 PageQuerySet 上调用它。例如:
# Search future EventPages
>>> from wagtail.models import EventPage
>>> EventPage.objects.filter(date__gt=timezone.now()).search("Hello world!")
PageQuerySet 的其它所有方法都可以与 search() 配合使用。例如:
# Search all live EventPages that are under the events index
>>> EventPage.objects.live().descendant_of(events_index).search("Event")
[<EventPage: Event 1>, <EventPage: Event 2>]
备注
search() 方法会把你的 QuerySet 转换成 Wagtail 某个 SearchResults 类的实例(具体取决于后端)。这意味着你必须在调用 search() 之前完成过滤。
search 方法的标准行为是只返回完整词匹配的结果;例如搜索 "hel" 不会返回包含 "hello" 这个词的结果。例外情况是回退的数据库搜索后端 —— 当数据库没有可用的全文搜索扩展、且未指定其它后端时会使用它。它执行基本的子串匹配,会返回包含搜索词的结果,忽略所有词边界。
自动补全搜索¶
Wagtail 提供了一个单独的方法,用于对特定的自动补全字段做部分匹配。这主要用于在用户输入查询时实时向他们提示页面 —— 不建议用于普通搜索,因为自动补全会倾向于加入超出所搜索具体词的多余结果。
>>> EventPage.objects.live().autocomplete("Eve")
[<EventPage: Event 1>, <EventPage: Event 2>]
搜索图片、文档和自定义模型¶
Wagtail 的文档和图片模型与页面一样,在其 QuerySet 上提供了 search 方法:
>>> from wagtail.images.models import Image
>>> Image.objects.filter(uploaded_by_user=user).search("Hello")
[<Image: Hello>, <Image: Hello world!>]
自定义模型可以通过直接使用搜索后端上的 search 方法来搜索:
>>> from myapp.models import Book
>>> from wagtail.search.backends import get_search_backend
# Search books
>>> s = get_search_backend()
>>> s.search("Great", Book)
[<Book: Great Expectations>, <Book: The Great Gatsby>]
你也可以把一个 QuerySet 传入 search 方法,这样就能给搜索结果加上过滤条件:
>>> from myapp.models import Book
>>> from wagtail.search.backends import get_search_backend
# Search books
>>> s = get_search_backend()
>>> s.search("Great", Book.objects.filter(published_date__year__lt=1900))
[<Book: Great Expectations>]
指定要搜索的字段¶
默认情况下,Wagtail 会搜索所有用 index.SearchField 建立过索引的字段。
可以通过 fields 关键字参数把它限制为某一组字段:
# Search just the title field
>>> EventPage.objects.search("Event", fields=["title"])
[<EventPage: Event 1>, <EventPage: Event 2>]
分面搜索¶
Wagtail 支持分面搜索,也就是基于某个分类 字段(例如分类或页面类型)进行过滤。
.facet(field_name) 方法返回一个 OrderedDict。键是指定字段
所引用的关联对象的 ID,值则是每个 ID 被引用
的次数。结果按引用次数
降序排列。
例如,要找出搜索结果中最常见的页面类型:
>>> Page.objects.search("Test").facet("content_type_id")
# Note: The keys correspond to the ID of a ContentType object; the values are the
# number of pages returned for that type
OrderedDict([
('2', 4), # 4 pages have content_type_id == 2
('1', 2), # 2 pages have content_type_id == 1
])
改变搜索行为¶
搜索运算符¶
搜索运算符决定当用户输入多个搜索词时搜索应如何表现。有两个可选值:
"or" —— 结果必须至少匹配一个词(Elasticsearch 的默认值)
"and" —— 结果必须匹配所有词(数据库搜索的默认值)
两种运算符各有优劣。"or" 运算符会返回多得多的结果,但很可能包含大量不相关的结果。"and" 运算符只返回包含所有搜索词的结果,但要求用户的查询更精确。
我们建议在按相关度排序时使用 "or" 运算符,在按其它条件排序时使用 "and" 运算符。
下面是一个使用 operator 关键字参数的示例:
# The database contains a "Thing" model with the following items:
# - Hello world
# - Hello
# - World
# Search with the "or" operator
>>> s = get_search_backend()
>>> s.search("Hello world", Things, operator="or")
# All records returned as they all contain either "hello" or "world"
[<Thing: Hello World>, <Thing: Hello>, <Thing: World>]
# Search with the "and" operator
>>> s = get_search_backend()
>>> s.search("Hello world", Things, operator="and")
# Only "hello world" returned as that's the only item that contains both terms
[<Thing: Hello world>]
对页面、图片和文档模型,QuerySet 的 search 方法也支持 operator 关键字参数:
>>> Page.objects.search("Hello world", operator="or")
# All pages containing either "hello" or "world" are returned
[<Page: Hello World>, <Page: Hello>, <Page: World>]
短语搜索¶
短语搜索用于查找整句或整个短语,而不是单个词。 这些词必须一起出现且顺序相同。
例如:
>>> from wagtail.search.query import Phrase
>>> Page.objects.search(Phrase("Hello world"))
[<Page: Hello World>]
>>> Page.objects.search(Phrase("World hello"))
[<Page: World Hello day>]
如果你想用双引号语法实现短语查询,见 查询字符串解析。
模糊匹配¶
模糊匹配会返回包含与搜索词相似的词条(term)的文档,相似程度以Levenshtein 编辑距离衡量。
对三到五个字母的词条,最多允许一次编辑(换位、插入或删除一个字符);更长的词条允许两次编辑;更短的词条必须完全匹配。
例如:
>>> from wagtail.search.query import Fuzzy
>>> Page.objects.search(Fuzzy("Hallo"))
[<Page: Hello World>, <Page: Hello>]
模糊匹配仅由 Elasticsearch 搜索后端支持。
Fuzzy 对象同样支持 operator 关键字参数,默认为 "or":
>>> Page.objects.search(Fuzzy("Hallo wurld", operator="and"))
[<Page: Hello World>]
复杂搜索查询¶
借助搜索查询类,Wagtail 也支持把搜索查询构建成 Python 对象,这些对象可以被其它搜索查询包裹并与之组合。可用的类 如下:
PlainText(query_string, operator=None, boost=1.0)
该类包裹一个由若干独立词组成的字符串。这与不带查询类进行搜索相同。
它接收查询字符串、运算符和 boost。
例如:
>>> from wagtail.search.query import PlainText
>>> Page.objects.search(PlainText("Hello world"))
# Multiple plain text queries can be combined. This example will match both "hello world" and "Hello earth"
>>> Page.objects.search(PlainText("Hello") & (PlainText("world") | PlainText("earth")))
Phrase(query_string)
该类包裹一个包含短语的字符串。其工作方式见上一节。
例如:
# This example will match both the phrases "hello world" and "Hello earth"
>>> Page.objects.search(Phrase("Hello world") | Phrase("Hello earth"))
Boost(query, boost)
该类提升另一个查询的得分。
例如:
>>> from wagtail.search.query import PlainText, Boost
# This example will match both the phrases "hello world" and "Hello earth" but matches for "hello world" will be ranked higher
>>> Page.objects.search(Boost(Phrase("Hello world"), 10.0) | Phrase("Hello earth"))
注意,PostgreSQL 或数据库搜索后端不支持这一功能。
查询字符串解析¶
前面几节展示了如何手动构造短语搜索查询,但很多搜索引擎(包括 Wagtail 管理后台,可以试试!)
都支持用双引号包裹短语来写短语查询。除了短语,你可能还希望允许用户
用冒号语法给查询添加过滤条件(hello world published:yes)。
这两个功能可以用 parse_query_string 工具函数实现。该函数接收用户
输入的查询字符串,返回一个查询对象和一个 QueryDict 形式的过滤条件:
例如:
>>> from wagtail.search.utils import parse_query_string
>>> filters, query = parse_query_string('my query string "this is a phrase" this_is_a:filter key:value1 key:value2', operator='and')
# Alternatively..
# filters, query = parse_query_string("my query string 'this is a phrase' this_is_a:filter key:test1 key:test2", operator='and')
>>> filters
<QueryDict: {'this_is_a': ['filter'], 'key': ['value1', 'value2']}>>
# Get a list of values associated with a particular key using the getlist method
>>> filters.getlist('key')
['value1', 'value2']
# Get a dict representation using the dict method
# NOTE: The dict method will reduce multiple values for a particular key to the last assigned value
>>> filters.dict()
{
'this_is_a': 'filter',
'key': 'value2'
}
>>> query
And([
PlainText("my query string", operator='and'),
Phrase("this is a phrase"),
])
下面是一个在搜索视图中使用该函数的示例:
from wagtail.search.utils import parse_query_string
def search(request):
query_string = request.GET["query"]
# Parse query
filters, query = parse_query_string(query_string, operator="and")
# Published filter
# An example filter that accepts either `published:yes` or `published:no` and filters the pages accordingly
published_filter = filters.get("published")
published_filter = published_filter and published_filter.lower()
if published_filter in ["yes", "true"]:
pages = pages.filter(live=True)
elif published_filter in ["no", "false"]:
pages = pages.filter(live=False)
# Search
pages = pages.search(query)
return render(request, "search_results.html", {"pages": pages})
自定义排序¶
默认情况下,如果后端支持,搜索结果会按相关度排序。要保留 QuerySet 原有的排序,需要把 search() 方法上的 order_by_relevance 关键字参数设为 False。
例如:
# Get a list of events ordered by date
>>> EventPage.objects.order_by('date').search("Event", order_by_relevance=False)
# Events ordered by date
[<EventPage: Easter>, <EventPage: Halloween>, <EventPage: Christmas>]
给结果标注得分¶
对每个匹配到的结果,Elasticsearch 都会计算一个「得分」,它是一个数字, 表示该结果相对于用户查询的相关程度。 结果通常按得分排序。
有些情况下能访问得分是有用的(例如
以编程方式合并针对不同模型的两个查询)。你可以通过在
SearchQuerySet 上调用 .annotate_score(field) 方法,
给每个结果加上得分。
例如:
>>> events = EventPage.objects.search("Event").annotate_score("_score")
>>> for event in events:
... print(event.title, event._score)
...
("Easter", 2.5),
("Halloween", 1.7),
("Christmas", 1.5),
注意得分本身是任意的,它只对比较 同一查询下的结果有用。
一个页面搜索视图示例¶
下面是一个可用于给你的站点添加「搜索」页面的 Django 视图示例:
# views.py
from django.shortcuts import render
from wagtail.models import Page
from wagtail.contrib.search_promotions.models import Query
def search(request):
# Search
search_query = request.GET.get("query", None)
if search_query:
search_results = Page.objects.live().search(search_query)
# Log the query so Wagtail can suggest promoted results
Query.get(search_query).add_hit()
else:
search_results = Page.objects.none()
# Render template
return render(
request,
"search_results.html",
{
"search_query": search_query,
"search_results": search_results,
},
)
以及配套的模板:
{% extends "base.html" %}
{% load wagtailcore_tags %}
{% block title %}Search{% endblock %}
{% block content %}
<form action="{% url 'search' %}" method="get">
<input type="text" name="query" value="{{ search_query }}">
<input type="submit" value="Search">
</form>
{% if search_results %}
<ul>
{% for result in search_results %}
<li>
<h4><a href="{% pageurl result %}">{{ result }}</a></h4>
{% if result.search_description %}
{{ result.search_description|safe }}
{% endif %}
</li>
{% endfor %}
</ul>
{% elif search_query %}
No results found
{% else %}
Please type something into the search box
{% endif %}
{% endblock %}
推广的搜索结果¶
「推广的搜索结果」让编辑者可以把相关内容显式关联到搜索词,这样结果页面除搜索引擎返回的结果之外,还能包含经过策划的内容。
该功能由 search_promotions contrib 模块提供。