diff src/goodjava/lucene/queryparser/NumberFieldParser.java @ 1771:c62324841dfb

improve NumberFieldParser and add key map lucene query
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 25 Jun 2023 15:05:09 -0600
parents b04b8fc5f4f4
children
line wrap: on
line diff
--- a/src/goodjava/lucene/queryparser/NumberFieldParser.java	Thu Jun 15 17:55:47 2023 -0600
+++ b/src/goodjava/lucene/queryparser/NumberFieldParser.java	Sun Jun 25 15:05:09 2023 -0600
@@ -4,8 +4,11 @@
 import org.apache.lucene.search.NumericRangeQuery;
 import org.apache.lucene.search.SortField;
 import org.apache.lucene.search.PrefixQuery;
+import org.apache.lucene.search.TermQuery;
 import org.apache.lucene.index.Term;
+import org.apache.lucene.util.BytesRef;
 import goodjava.parser.ParseException;
+import org.apache.lucene.util.NumericUtils;
 
 
 public abstract class NumberFieldParser implements FieldParser {
@@ -13,7 +16,15 @@
 	@Override public final Query getQuery(GoodQueryParser qp,String field,String query) throws ParseException {
 		if( query.equals("*") )
 			return new PrefixQuery(new Term(field,""));
-		return getRangeQuery(qp,field,query,query,true,true);
+		try {
+			return getQuery(field,query);
+		} catch(NumberFormatException e) {
+			throw qp.exception(e);
+		}
+	}
+
+	protected Query getQuery(String field,String query) {
+		return getRangeQuery(field,query,query,true,true);
 	}
 
 	@Override public final Query getRangeQuery(GoodQueryParser qp,String field,String minQuery,String maxQuery,boolean includeMin,boolean includeMax) throws ParseException {
@@ -35,6 +46,11 @@
 
 	public static final FieldParser INT = new NumberFieldParser() {
 
+		@Override protected Query getQuery(String field,String query) {
+			int n = Integer.valueOf(query);
+			return new TermQuery( term(field,n) );
+		}
+
 		@Override protected Query getRangeQuery(String field,String minQuery,String maxQuery,boolean includeMin,boolean includeMax) {
 			Integer min = minQuery.equals("*") ? null : Integer.valueOf(minQuery);
 			Integer max = maxQuery.equals("*") ? null : Integer.valueOf(maxQuery);
@@ -48,6 +64,11 @@
 
 	public static final FieldParser LONG = new NumberFieldParser() {
 
+		@Override protected Query getQuery(String field,String query) {
+			long n = Long.valueOf(query);
+			return new TermQuery( term(field,n) );
+		}
+
 		@Override protected Query getRangeQuery(String field,String minQuery,String maxQuery,boolean includeMin,boolean includeMax) {
 			Long min = minQuery.equals("*") ? null : Long.valueOf(minQuery);
 			Long max = maxQuery.equals("*") ? null : Long.valueOf(maxQuery);
@@ -85,4 +106,16 @@
 		}
 	};
 
+	public static Term term(String name,int value) {
+		BytesRef br = new BytesRef();
+		NumericUtils.intToPrefixCoded(value,0,br);
+		return new Term(name,br);
+	}
+
+	public static Term term(String name,long value) {
+		BytesRef br = new BytesRef();
+		NumericUtils.longToPrefixCoded(value,0,br);
+		return new Term(name,br);
+	}
+
 }