如何使用whoosh搜索关键字

时间:2016-01-13 07:22:57

标签: python python-2.7 search whoosh

文章架构:

以下是我创建的文章架构。

class ArticleSchema(SchemaClass):
    title = TEXT(
        phrase=True, sortable=True, stored=True,
        field_boost=2.0, spelling=True, analyzer=StemmingAnalyzer())
    keywords = KEYWORD(
        commas=True, field_boost=1.5, lowercase=True)
    authors = KEYWORD(stored=True, commas=True, lowercase=True)
    content = TEXT(spelling=True, analyzer=StemmingAnalyzer())
    summary = TEXT(spelling=True, analyzer=StemmingAnalyzer())
    published_time = DATETIME(stored=True, sortable=True)
    permalink = STORED
    thumbnail = STORED
    article_id = ID(unique=True, stored=True)
    topic = TEXT(spelling=True, stored=True)
    series_id = STORED
    tags = KEYWORD(commas=True, lowercase=True)

搜索查询

FIELD_TIME = 'published_time'
FIELD_TITLE = 'title'
FIELD_PUBLISHER = 'authors'
FIELD_KEYWORDS = 'keywords'
FIELD_CONTENT = 'content'
FIELD_TOPIC = 'topic'

def search_query(search_term=None, page=1, result_len=10):
    '''Search the provided query.'''
    if not search_term or search_term == '':
        return None, 0
    if not index.exists_in(INDEX_DIR, indexname=INDEX_NAME):
        return None, 0
    ix = get_index()
    parser = qparser.MultifieldParser(
            [FIELD_TITLE, FIELD_PUBLISHER, FIELD_KEYWORDS, FIELD_TOPIC],
            ix.schema)
    query = parser.parse(search_term)
    query.normalize()
    search_results = []
    with ix.searcher() as searcher:
        results = searcher.search_page(
            query,
            pagenum=page,
            pagelen=result_len,
            sortedby=[sorting_timestamp, scores],
            reverse=True,
            terms=True
        )
        if results.scored_length() > 0:
            for hit in results:
                search_results.append(append_to(hit))
            return (search_results, results.pagecount)

    parser = qparser.MultifieldParser(
            [FIELD_TITLE, FIELD_PUBLISHER, FIELD_TOPIC],
            ix.schema, termclass=FuzzyTerm)
    parser.add_plugin(qparser.FuzzyTermPlugin())
    query = parser.parse(search_term)
    query.normalize()
    search_results = []
    with ix.searcher() as searcher:
        results = searcher.search_page(
            query,
            pagenum=page,
            pagelen=result_len,
            sortedby=[sorting_timestamp, scores],
            reverse=True,
            terms=True
        )
        if results.scored_length() > 0:
            for hit in results:
                search_results.append(append_to(hit))
            return (search_results, results.pagecount)
    return None, 0

当我尝试标题搜索工作时,但对于作者和关键字,搜索无法正常工作。我无法理解我在这里做错了什么。我从api获取数据然后运行索引。一切正常。但是,当我搜索authorskeywords等关键字时,它无效。

1 个答案:

答案 0 :(得分:0)

authorskeywords都属于KEYWORD类型,它不支持词组搜索,这意味着您应该使用完全关键字或其衍生产品进行搜索,因为您使用的是词干分析器。

对于authors,我认为您应该使用TEXT

来自whoosh的文档

  

<强> whoosh.fields.KEYWORD

     

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