0

I have a folder called pads in which there are six notepad documents with some text in each of them. Am trying to build a whoosh code that will return the appropriate document for the query string but am getting output as runtime, help appreciated

import os
from whoosh.index import create_in
from whoosh.fields import Schema, TEXT, ID
import sys
from whoosh.qparser import QueryParser
from whoosh import scoring
from whoosh.index import open_dir

def createSearchableData(root):   

'''
Schema definition: title(name of file), path(as ID), content(indexed
but not stored),textdata (stored text content)
'''
    schema = Schema(title=TEXT(stored=True),path=ID(stored=True),\
          content=TEXT,textdata=TEXT(stored=True))
    if not os.path.exists("indexdir"):
        os.mkdir("indexdir")

# Creating a index writer to add document as per schema
    ix = create_in("indexdir",schema)
    writer = ix.writer()

    filepaths = [os.path.join(root,i) for i in os.listdir(root)]
    for path in filepaths:
        fp = open(path,'r')
        print(path)
        text = fp.read()
        writer.add_document(title=path.split("\\")[0], path=path,\
          content=text,textdata=text)
        fp.close()
    writer.commit()

root = "pads"
createSearchableData(root)

---OUTPUT--- pads/5.txt pads/4.txt pads/6.txt pads/3.txt pads/2.txt pads/1.txt

ix = open_dir("indexdir")
query_str = 'barzini'
# Top 'n' documents as result
topN = 3

qp = QueryParser("content", ix.schema)
q = qp.parse(query_str)

with ix.searcher() as searcher:
    results = searcher.search(q,limit=topN)
print(results)   

---OUTPUT--- Top 1 Results for Term('content', 'barzini') runtime=0.00048629400043864734>

I wanted the output to return 4.txt from Pad folder as it has the string "barzini" . Could you please help me with the output

ravijprs
  • 39
  • 1
  • 4
  • As the [docs](https://whoosh.readthedocs.io/en/latest/searching.html) state, search() returns a Results object which can be used similar to a list. – Michael Butscher Sep 08 '19 at 05:42
  • I found an answer to this. [This](https://stackoverflow.com/questions/19477319/whoosh-accessing-search-page-result-items-throws-readerclosed-exception/19477988) might help you. – Tanay Sojwal Apr 20 '20 at 04:11

1 Answers1

0

Actually, you need to place print(results) inside the "with" code block as shown below.

with ix.searcher() as searcher:
    results = searcher.search(q, limit=None)
    print(results)