mainstringargs
mainstringargs

Reputation: 13923

Is there a way to use MultiFieldQuery combined with NumericRanges in Lucene?

I'm currently creating and searching using this using a MultiFieldQueryParser. I've got about 20 different fields all of varying data types, and I'd like the search to take into account all of them. Here is where I'm building the parser and getting the query object:

MultiFieldQueryParser mfqp = new MultiFieldQueryParser(
                keyHashSet.toArray(new String[] {}), analyzer);

mfqp.setAllowLeadingWildcard(true);

Query q = mfqp.parse(search);

System.out.println(q.getClass());

Where keyHashSet has all of my data keys.

Whenever I pass in a range query, for instance:

Heading:[0 to 360]

The class returned from the printout is

class org.apache.lucene.search.TermRangeQuery

Even though I am setting up the Heading field like this:

doc.add(new FloatField("Heading", value, Field.Store.YES));

Is there a way to perform a NumericRangeQuery using the MultiFieldQueryParser?

Upvotes: 4

Views: 253

Answers (1)

sameer yadav
sameer yadav

Reputation: 36

I've been facing the same problem, the thing is whenever you pass range query using MultiFieldQueryParser, it interprets it as TermRangeQuery, So we need to customize the class MultiFieldQueryParser according to our need,I'm using lucene 4.7.2; here is what I did, since during indexing I had parsed the number as long, I only had one field for which numeric range query is to be applied ie "price",

public class CustomMultiFieldQueryParser extends MultiFieldQueryParser {

    public CustomMultiFieldQueryParser(Version matchVersion, String[] fields, Analyzer analyzer) {
        super(matchVersion, fields, analyzer);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected org.apache.lucene.search.Query getRangeQuery(String fieldName, String min, String max, boolean minInclusive,
            boolean maxInclusive) throws ParseException {
        // TODO Auto-generated method stub
        if(fieldName.equals("price")) {
            return NumericRangeQuery.newLongRange(fieldName, Long.parseLong(min), Long.parseLong(max), minInclusive, maxInclusive);
        }
        return super.getRangeQuery(fieldName, min, max, minInclusive, maxInclusive);
    }
}

Upvotes: 2

Related Questions