Search code examples
pythonhighlightingwhoosh

How to get highlighted searches on whoosh


I used an example code from pythonhosted.org but nothing seems to happen. This is code I used:

results = mysearcher.search(myquery)
for hit in results:
    print(hit["title"])

I entered this code into python but it gives an error saying mysearcher is not defined. So I'm really not sure if I'm missing something out as I'm just trying to get the basics to get me up and running.


Solution

  • You are missing to define the searcher mysearcher, copy the whole code. Here is a complete example:

    >>> import 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"}
    

    Than you can highlight like this:

    for hit in results:
        print(hit["title"])
        # Assume "content" field is stored
        print(hit.highlights("content"))