快速启动

whoosh是一个类和函数库,用于索引文本,然后搜索索引。它允许你为你的内容开发定制的搜索引擎。例如,如果您正在创建博客软件,您可以使用whoosh添加搜索功能,允许用户搜索博客条目。

简单介绍

>>> from whoosh.index import create_in
>>> from whoosh.fields import *
>>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
>>> ix = create_in("indexdir", schema)
>>> writer = ix.writer()
>>> writer.add_document(title=u"First document", path=u"/a",
...                     content=u"This is the first document we've added!")
>>> writer.add_document(title=u"Second document", path=u"/b",
...                     content=u"The second one is even more interesting!")
>>> writer.commit()
>>> from whoosh.qparser import QueryParser
>>> with ix.searcher() as searcher:
...     query = QueryParser("content", ix.schema).parse("first")
...     results = searcher.search(query)
...     results[0]
...
{"title": u"First document", "path": u"/a"}

这个 IndexSchema 物体

要开始使用whoosh,您需要 索引对象. 第一次创建索引时,必须定义索引的 图式. 模式列出了 fields 在索引中。字段是索引中每个文档的一条信息,例如其标题或文本内容。一个字段可以是 indexed (表示可以搜索)和/或 stored (意味着索引的值将随结果一起返回;这对于标题等字段很有用)。

此架构有两个字段:“标题”和“内容”::

from whoosh.fields import Schema, TEXT

schema = Schema(title=TEXT, content=TEXT)

创建索引时,只需要创建一次架构。模式被pickle化,并与索引一起存储。

当你创建 Schema 对象,使用关键字参数将字段名映射到字段类型。字段列表及其类型定义了要索引的内容和可搜索的内容。whoosh附带了一些非常有用的预定义字段类型,您可以轻松地创建自己的字段类型。

whoosh.fields.ID

此类型只将字段的整个值作为单个单元进行索引(并可选地存储)(也就是说,它不会将字段分解为单个单词)。这对于文件路径、URL、日期、类别等字段很有用。

whoosh.fields.STORED

此字段与文档一起存储,但未编入索引。此字段类型没有索引且不可搜索。这对于要在搜索结果中显示给用户的文档信息很有用。

whoosh.fields.KEYWORD

此类型是为空格或逗号分隔的关键字设计的。此类型是可索引和搜索的(并且可以选择存储)。为了节省空间,它不支持短语搜索。

whoosh.fields.TEXT

此类型用于正文文本。它索引(并可选地存储)文本并存储术语位置,以允许短语搜索。

whoosh.fields.NUMERIC

此类型用于数字。您可以存储整数或浮点数。

whoosh.fields.BOOLEAN

此类型用于布尔值(真/假)。

whoosh.fields.DATETIME

此类型用于 datetime 物体。见 Indexing and parsing dates/times 更多信息。

whoosh.fields.NGRAM and whoosh.fields.NGRAMWORDS

这些类型将字段文本或单个术语分解为n个语法。见 索引和搜索N图 更多信息。

(作为一个快捷方式,如果不需要向字段类型传递任何参数,您只需给出类名,whoosh将为您实例化对象。)::

from whoosh.fields import Schema, STORED, ID, KEYWORD, TEXT

schema = Schema(title=TEXT(stored=True), content=TEXT,
                path=ID(stored=True), tags=KEYWORD, icon=STORED)

设计模式 更多信息。

Once you have the schema, you can create an index using the create_in 功能:

import os.path
from whoosh.index import create_in

if not os.path.exists("index"):
    os.mkdir("index")
ix = create_in("index", schema)

(在较低的水平上,这将创建一个 Storage 对象以包含索引。一 Storage 对象表示将在其中存储索引的媒体。通常是这样 FileStorage ,它将索引存储为目录中的一组文件。)

创建索引后,可以使用 open_dir 方便功能:

from whoosh.index import open_dir

ix = open_dir("index")

IndexWriter 对象

好吧,我们有一个 Index 对象,现在我们可以开始添加文档。这个 writer() 方法 Index 对象返回 IndexWriter 对象,用于将文档添加到索引中。索引编写器的 add_document(**kwargs) 方法接受字段名映射到值的关键字参数:

writer = ix.writer()
writer.add_document(title=u"My document", content=u"This is my document!",
                    path=u"/a", tags=u"first short", icon=u"/icons/star.png")
writer.add_document(title=u"Second try", content=u"This is the second example.",
                    path=u"/b", tags=u"second short", icon=u"/icons/sheep.png")
writer.add_document(title=u"Third time's the charm", content=u"Examples are many.",
                    path=u"/c", tags=u"short", icon=u"/icons/book.png")
writer.commit()

两个重要注意事项:

  • 您不必为每个字段填写值。whoosh不在乎你是否在文档中遗漏了一个字段。

  • 索引文本字段必须传递一个Unicode值。存储但未编入索引的字段( STORED 字段类型)可以传递任何可pickle的对象。

如果您有一个同时被索引和存储的文本字段,您可以索引一个Unicode值,但在必要时存储一个不同的对象(它通常不是,但有时确实有用),使用以下技巧:

writer.add_document(title=u"Title to be indexed", _stored_title=u"Stored title")

在上调用commit()。 IndexWriter 将添加的文档保存到索引::

writer.commit()

如何索引文档 更多信息。

一旦您的文档被提交到索引中,您就可以搜索它们。

Searcher 对象

要开始搜索索引,我们需要 Searcher 对象:

searcher = ix.searcher()

您通常希望使用 with 语句,这样当您完成搜索时,搜索者将自动关闭(搜索者对象表示许多打开的文件,因此如果您没有显式关闭它们,并且系统收集它们的速度很慢,则可能会耗尽文件句柄)::

with ix.searcher() as searcher:
    ...

这当然等同于:

try:
    searcher = ix.searcher()
    ...
finally:
    searcher.close()

搜索者的 search() 方法采用 查询对象. 可以直接构造查询对象,也可以使用查询分析器来分析查询字符串。

例如,此查询将匹配“content”字段中同时包含“apple”和“bear”的文档:

# Construct query objects directly

from whoosh.query import *
myquery = And([Term("content", u"apple"), Term("content", "bear")])

要分析查询字符串,可以使用 qparser 模块。第一个论点 QueryParser constructor is the default field to search. This is usually the "body text" field. 第二个可选参数是用于理解如何解析字段的架构:

# Parse a query string

from whoosh.qparser import QueryParser
parser = QueryParser("content", ix.schema)
myquery = parser.parse(querystring)

一旦你拥有了 Searcher 以及一个查询对象,您可以使用 Searchersearch() 方法运行查询并获取 Results 对象:

>>> results = searcher.search(myquery)
>>> print(len(results))
1
>>> print(results[0])
{"title": "Second try", "path": "/b", "icon": "/icons/sheep.png"}

默认值 QueryParser 实现与Lucene非常相似的查询语言。它允许您将术语与 ANDOR ,删除术语 NOT ,将术语分组为带括号的子句,执行范围、前缀和wilcard查询,并指定要搜索的不同字段。默认情况下,它将子句与 AND (因此,默认情况下,您指定的所有术语都必须在文档中,文档才能匹配)::

>>> print(parser.parse(u"render shade animate"))
And([Term("content", "render"), Term("content", "shade"), Term("content", "animate")])

>>> print(parser.parse(u"render OR (title:shade keyword:animate)"))
Or([Term("content", "render"), And([Term("title", "shade"), Term("keyword", "animate")])])

>>> print(parser.parse(u"rend*"))
Prefix("content", "rend")

whoosh包含处理搜索结果的额外功能,例如

  • 按索引字段的值排序结果,而不是按相关性排序。

  • 突出显示原始文档摘录中的搜索词。

  • 根据找到的前几个文档展开查询词。

  • 分页结果(例如“显示结果1-20,第1页,共4页”)。

如何搜索 更多信息。