【发布时间】:2014-05-08 04:47:51
【问题描述】:
我正在制作一个必须支持嵌套数据层次结构的搜索索引。 出于测试目的,我正在制作一个非常简单的架构:
test_schema = Schema(
name_ngrams=NGRAMWORDS(minsize=4, field_boost=1.2),
name=TEXT(stored=True),
id=ID(unique=True, stored=True),
type=TEXT
)
对于测试数据,我使用这些:
test_data = [
dict(
name=u'The Dark Knight Returns',
id=u'chapter_1',
type=u'chapter'),
dict(
name=u'The Dark Knight Triumphant',
id=u'chapter_2',
type=u'chapter'),
dict(
name=u'Hunt The Dark Knight',
id=u'chapter_3',
type=u'chapter'),
dict(
name=u'The Dark Knight Falls',
id=u'chapter_4',
type=u'chapter')
]
parent = dict(
name=u'The Dark Knight Returns',
id=u'book_1',
type=u'book')
我已将所有 (5) 个文档添加到索引中,如下所示
with index_writer.group():
index_writer.add_document(
name_ngrams=parent['name'],
name=parent['name'],
id=parent['id'],
type=parent['type']
)
for data in test_data:
index_writer.add_document(
name_ngrams=data['name'],
name=data['name'],
id=data['id'],
type=data['type']
)
所以,为了获取一本书的所有章节,我创建了一个使用 NestedChildren 搜索的函数:
def search_childs(query_string):
os.chdir(settings.SEARCH_INDEX_PATH)
# Initialize index
index = open_dir(settings.SEARCH_INDEX_NAME, indexname='test')
parser = qparser.MultifieldParser(
['name',
'type'],
schema=index.schema)
parser.add_plugin(qparser.FuzzyTermPlugin())
parser.add_plugin(DateParserPlugin())
myquery = parser.parse(query_string)
# First, we need a query that matches all the documents in the "parent"
# level we want of the hierarchy
all_parents = And([parser.parse(query_string), Term('type', 'book')])
# Then, we need a query that matches the children we want to find
wanted_kids = And([parser.parse(query_string),
Term('type', 'chapter')])
q = NestedChildren(all_parents, wanted_kids)
print q
with index.searcher() as searcher:
#these results are the parents
results = searcher.search(q)
print "number of results:", len(results)
if len(results):
for result in results:
print(result.highlights('name'))
print(result)
return results
但是对于我的测试数据,如果我搜索“dark knigth”,当它必须是 4 个搜索结果时,我只会得到 3 个结果。
我不知道丢失的结果是否因为与书名相同而被排除在外,但它根本没有显示在搜索结果中
我知道所有项目都在索引中,但我不知道我在这里缺少什么。
有什么想法吗?
【问题讨论】:
标签: python full-text-search whoosh