Lucene 3.0.3 Numeric term query

2019-04-12 21:57发布

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!

标签: java lucene
3条回答
神经病院院长
2楼-- · 2019-04-12 22:30

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.

查看更多
太酷不给撩
3楼-- · 2019-04-12 22:33

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.

查看更多
仙女界的扛把子
4楼-- · 2019-04-12 22:39

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

查看更多
登录 后发表回答