You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@lucene.apache.org by lu...@jakarta.apache.org on 2004/04/04 22:30:10 UTC

[Jakarta Lucene Wiki] New: SearchNumericalFields

   Date: 2004-04-04T13:30:06
   Editor: StephaneVaucher <va...@cirano.qc.ca>
   Wiki: Jakarta Lucene Wiki
   Page: SearchNumericalFields
   URL: http://wiki.apache.org/jakarta-lucene/SearchNumericalFields

   Initial commit

New Page:

= Searching Numerical Fields =

 Original post: http://www.mail-archive.com/lucene-user@jakarta.apache.org/msg07107.html
 Goal: We want to do a search for something like this: [[BR]]
 number:[1 TO 2]

 and not have it return 11 or 103, etc.  But, return 1.5, for example.

 Answer (from: http://issues.apache.org/eyebrowse/ReadMsg?listId=30&msgNo=7103, Erik Hatcher)

 == Utility to pad the numbers ==
 public class Number''''''Utils {
   private static final Decimal''''''Format formatter =
       new Decimal''''''Format("00000"); // make this as wide as you need

   public static String pad(int n) {
     return formatter.format(n);
   }
 }

 == Index the relevant fields using the pad function ==

       doc.add(Field.Keyword("id", Number''''''Utils.pad(i)));

 == Create a custom QueryParser subclass: ==

  public class Custom''''''Query''''''Parser extends Query''''''Parser {
   public Custom''''''Query''''''Parser(String field, Analyzer analyzer) {
     super(field, analyzer);
   }

   protected Query getRangeQuery(String field, Analyzer analyzer,
                                 String part1, String part2,
                                 boolean inclusive)
       throws Parse''''''Exception {
     if ("id".equals(field)) {
       try {
         int num1 = Integer.parseInt(part1);
         int num2 = Integer.parseInt(part2);
         return new Range''''''Query(new Term(field, Number''''''Utils.pad(num1)),
                               new Term(field, Number''''''Utils.pad(num2)),
                               inclusive);
       } catch (Number''''''Format''''''Exception e) {
         throw new Parse''''''Exception(e.getMessage());
       }
     }

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

  Note: Only the "id" field is treated special, but your logic may vary.

  == Use the custom QueryParser ==

     Custom``Query''''''Parser parser =
         new Custom''''''Query``Parser("field", analyzer);

     Query query = parser.parse("id:[37 TO 346]");

     assertEquals("padded", "id:[00037 TO 00346]",
                            query.toString("field"));


  == For decimals (sv) ==

  You can use a multiplier to make sure you don't have decimals if they cause problems.

---------------------------------------------------------------------
To unsubscribe, e-mail: lucene-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: lucene-dev-help@jakarta.apache.org