学习python Whoosh全文索引的笔记翻译,有错请多指教
快速开始
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"}
The
开始用Whoosh, 你需要一个index object,第一次创建索引,你必须定义索引的schema.schema列出索引的字段. 一个字段是每个建立索引文档的一块信息,例如它的标题和文本内容. 一个字段能够被索引(意味着它能被搜索)并且 /或 存储(意味着获取索引时能得到对应的值), 像标题等这些字段是很有用的. schema 有两个字段,title和contentIndex
andSchema
objectsfrom whoosh.fields import Schema, TEXT schema = Schema(title=TEXT, content=TEXT)当你创建索引时,你只需要创建schema一次.schema 是能被pickled和存储的.
当你创建Schema对象时,你用关键参数去映射字段名到字段类型. 一系列的字段和它们的类型定义了你正定义什么索引和什么是可被搜索的.
Whoosh 带有一些很有用的预定义字段类型,同时你也可以很容易的创建你自己的.
如果你不需要传递任何参数给字段类型,你可以只给类名然后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)
一当你有了schema,你可以用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)
你创建一个索引后,你可以用open_dir方法
from whoosh.index import open_dir ix = open_dir("index")
The IndexWriter
object
到现在我们有一个 Index
对象,现在可以开始添加文档.Index对象里的writer()
有个IndexWriter对象,
这能让你添加文档到索引里.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()两个需要注意的:
*你不一定需要为每个字段填值,
*索引一个text字段必须传一个unicode值
如果你有一个text字段需要indexed和stored,你可以index一个unicode值,
但如果必要(通常不是必要的,但有是很有用)用下面存储不同对象
writer.add_document(title=u"Title to be indexed", _stored_title=u"Stored title")调用commit方法去添加的文件到索引里:
writer.commit()