Reputation: 855
I have a numeric field in Lucene 3.0.3 and it works perfectly fine with the range queries. If we switch to the TermQuery it doesnt produce any result. For example:
Document doc = new Document();
String name = "geolongitude";
NumericField numericField = new NumericField(name);
double value = 29.0753505;
String valueAsString = "29.0753505";
numericField.setDoubleValue(value);
doc.add(numericField);
indexWriter.addDocument(doc);
indexWriter.commit();
indexWriter.close();
IndexSearcher indexSearcher = new IndexSearcher(open);
Query termQ = new TermQuery(new Term(name, valueAsString));
TopDocs search = indexSearcher.search(termQ, 10);
In this case I dont get any result. I tried to figure out whether exist any "NumericTermQuery" but couldnt find that. I could do something tricky (make a range query for the term that I am searching) but I dont like the solution.
Thank you!
Upvotes: 2
Views: 2172
Reputation: 820
When you built index with NumericField, the value in index is 29.0753505 (a double data). The TermQuery will use the value "29.0753505"(a String) to search.
I think if you don't like use the range query, you can imply a numeric query by yourself, and you can see the code of NumericRangeTermEnum
in NumericRangeQuery
, and imply one that make the termEnum contains all terms that exactly matched.
Upvotes: 0
Reputation: 855
Ok, I have figure out a different solution,
String doubleToPrefixCoded = NumericUtils.doubleToPrefixCoded(value);
Query termQ = new TermQuery(new Term(name, doubleToPrefixCoded));
I found it out from : http://www.gossamer-threads.com/lists/lucene/java-user/88516 and it works correctly
Upvotes: 1
Reputation: 33351
Numeric fields are not indexed as plain text terms, so searching for their string representation as a term won't work.
Like it or not, constructing a NumericRangeQuery
where min = max is indeed the correct approach:
Query query = NumericRangeQuery.newDoubleRange(name, value, value, true, true);
The implementation of NumericRangeQuery
recognizes this case specifically, actually, and is designed to handle it well.
Upvotes: 6