我通过创建两个单独的字段解决了这个问题。一项用于实际搜索,一项用于建议。 NGRAM 或 NGRAMWORDS 字段类型可用于“模糊搜索”功能。在你的情况下,它会是这样的:
# not sure how your schema looks like exactly
schema = Schema(
title=NGRAMWORDS(minsize=2, maxsize=10, stored=True, field_boost=1.0, tokenizer=None, at='start', queryor=False, sortable=False)
content=TEXT(stored=True),
url=title=ID(stored=True),
spelling=TEXT(stored=True, spelling=True)) # typeahead field
if not os.path.exists("index"):
os.mkdir("index")
ix = create_in("index", schema)
ix = open_dir("index")
writer = ix.writer()
q = MyTable.select()
for item in q:
print 'adding %s' % item.Title
writer.add_document(title=item.Title, content=item.content, url = item.URL)
writer.add_document(spelling=item.Title) # adding item title to typeahead field
self.addContentToSpelling(writer, item.content) # some method that adds some content words to typeheadfield if needed. The same way as above.
writer.commit()
那么什么时候进行搜索:
origQueryString = 'my search string'
words = self.splitQuery(origQueryString) # use tokenizers / analyzers or self implemented
queryString = origQueryString # would be better to actually create a query
corrector = ix.searcher().corrector("spelling")
for word in words:
suggestionList = corrector.suggest(word, limit=self.limit)
for suggestion in suggestionList:
queryString = queryString + " " + suggestion # would be better to actually create a query
parser = QueryParser("title", ix.schema)
myquery = parser.parse(querystring)
with ix.searcher() as searcher:
results = searcher.search(myquery)
print len(results)
for r in results:
print r
希望你能明白。