Search code examples
pythonwhoosh

In PY whoosh full text search engineer, how to create a query to find a value in a range?


I am trying to find document by value in a specific range. The official document doesn't give example for different types of fields and search methods. Any smart guy can give me a link with more example and application? Any hint?

Thank you!

Here's my codes,

from whoosh.index import create_in
from whoosh.fields import *
from whoosh.qparser import QueryParser

schema = Schema(temperature=NUMERIC(float, stored=True))
ix = create_in("indexdir", schema)

writer = ix.writer()
writer.add_document(temperature = 32.3)
writer.commit()

with ix.searcher() as searcher:
    query = QueryParser("temperature", ix.schema).parse("temperature:>20.0") ## should be something like this
    print(searcher.search(query)[0])

Solution

  • Range query syntax is [START to END] such as START and END are numbers representing the range bounds. [ START to] if no end is defined. [to END] if no start is defined.

    In your case, for temperature greater than 20.0 use temperature:[20.0 to]. Becarful no space between to and ].

     query = QueryParser("temperature", ix.schema).parse("temperature:[ 20 to 1000 ]")
    

    You can also use whoosh.query.NumericRange:

    class whoosh.query.NumericRange (fieldname, start, end, startexcl=False, endexcl=False, boost=1.0, constantscore=True)

    query = NumericRange(u'temperature', 20.0, None)
    

    Ref: Query lang - Ranges