1

使用 Whoosh 我无法搜索包含多字查询的文档。我使用了http://packages.python.org/Whoosh/quickstart.html#the-searcher-object中描述的 And 运算符, 但它显示错误。单字搜索有效。

from whoosh.index import create_in
from whoosh.fields import *
from whoosh.qparser import QueryParser
from whoosh.fields import Schema, TEXT, KEYWORD, ID, STORED
from whoosh.analysis import StemmingAnalyzer
from whoosh.query import *
import os.path

##Schema

schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)

##Indexing

if not os.path.exists("index"):
    os.mkdir("index")

ix = create_in("index", schema)

writer = ix.writer()
writer.add_document(title=u"First document", path=u"/a", content=u"Michael Jackson")
writer.add_document(title=u"Second document", path=u"/b", content=u"Roger Federer")
writer.add_document(title=u"Third document", path=u"/c", content=u"Michael Jordan")
writer.add_document(title=u"Fifth document", path=u"/d", content=u"Michael Phelps")
writer.add_document(title=u"Sixth document", path=u"/e", content=u"Michael Schumacher")
writer.add_document(title=u"Seventh document", path=u"/f", content=u"Michael Dell")
writer.add_document(title=u"Eigth document", path=u"/g", content=u"Michael Akerfeldt")
writer.commit()


##Searching

searcher = ix.searcher()

#Single Word Search:
#myquery = u'Michael'

#Multiword Search:
myquery = And([Term("content", u'Roger'), Term("content", u'Michael')])

#query = QueryParser("content", schema=ix.schema).parse(myquery)

parser = QueryParser("content", ix.schema)
query = parser.parse(myquery)

#with ix.searcher() as searcher:

results = searcher.search(query, limit=None)

print "Length of Results :", len(results)
print "\nResults : "
for i in range (0,len(results)):
    print results[i]
4

1 回答 1

0

我认为您对查询解析器的功能感到困惑。查询解析器将创建And您通过调用显式构造的查询:

query = parser.parse("Roger and Michael")

或者,如果您真的想自己创建查询结构,则直接传递myquerysearcher.search而不是query.

更多信息在这里:http ://packages.python.org/Whoosh/parsing.html

于 2012-09-09T12:13:56.297 回答