Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Numeric Range Query with Term Query in Lucene

Tags:

java

lucene

I would like to combine a numeric range query with a term query in Lucene. For example, I want to search for documents that I have indexed that contain between 10 and 20 pages and have the title "Hello World".

It does not seem possibly to use the QueryParser to generate this query for me; the range query that the QueryParser generates appears to be a text one.

I definitely would appreciate an example of how to combine a numeric range query with a term query. I would also be open taking an alternative to searching my index.

Thanks

like image 285
Chris J Avatar asked Jul 14 '10 23:07

Chris J


2 Answers

Well it looks like I figured this one out on my own. You can use Query.combine() to OR queries together. I have included an example below.

String termQueryString = "title:\"hello world\"";
Query termQuery = parser.parse(termQueryString);

Query pageQueryRange = NumericRangeQuery.newIntRange("page_count", 10, 20, true, true);

Query query = termQuery.combine(new Query[]{termQuery, pageQueryRange});
like image 67
Chris J Avatar answered Nov 18 '22 12:11

Chris J


You can also create a custom QueryParser overriding protected Query getRangeQuery(...) method, which should return NumericRangeQuery instance when "page_count" field is encountered.

Like so...

public class CustomQueryParser extends QueryParser {

    public CustomQueryParser(Version matchVersion, String f, Analyzer a) {
        super(matchVersion, f, a);
    }

    @Override
    protected Query getRangeQuery(final String field, final String part1, final String part2, final boolean inclusive) throws ParseException {

        if ("page_count".equals(field)) {
            return NumericRangeQuery.newIntRange(field, Integer.parseInt(part1), Integer.parseInt(part2), inclusive, inclusive);
        }

        // return default
        return super.getRangeQuery(field, part1, part2, inclusive);    
    }
}

Then use CustomQueryParser when parsing textual queries..

Like so...

...
final QueryParser parser = new CustomQueryParser(Version.LUCENE_35, "some_default_field", new StandardAnalyzer(Version.LUCENE_35));
final Query q = parser.parse("title:\"hello world\" AND page_count:[10 TO 20]");
...

This all, of course, assumes that NumericField(...).setIntValue(...) was used when page_count values were added to documents

like image 5
Dr. Benedict Porkins Avatar answered Nov 18 '22 12:11

Dr. Benedict Porkins