Package org.hibernate.search.bridge.util

Source Code of org.hibernate.search.bridge.util.NumericFieldUtils

package org.hibernate.search.bridge.util;

import org.apache.lucene.document.NumericField;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.NumericUtils;
import org.hibernate.search.SearchException;

/**
* Utility class to handle Numeric Fields
*
* @author: Gustavo Fernandes
*/
public class NumericFieldUtils {

  public static Query createNumericRangeQuery(String fieldName, Object from, Object to,
                        boolean includeLower, boolean includeUpper) {
    Class numericClass = from.getClass();
    if (numericClass.isAssignableFrom(Double.class)) {
      return NumericRangeQuery.newDoubleRange(fieldName, (Double) from, (Double) to, includeLower, includeUpper);
    }
    if (numericClass.isAssignableFrom(Long.class)) {
      return NumericRangeQuery.newLongRange(fieldName, (Long) from, (Long) to, includeLower, includeUpper);
    }
    if (numericClass.isAssignableFrom(Integer.class)) {
      return NumericRangeQuery.newIntRange(fieldName, (Integer) from, (Integer) to, includeLower, includeUpper);
    }
    if (numericClass.isAssignableFrom(Float.class)) {
      return NumericRangeQuery.newFloatRange(fieldName, (Float) from, (Float) to, includeLower, includeUpper);
    }
    // TODO: check for type before in the mapping
    throw new SearchException(
        "Cannot create numeric range query for field " + fieldName + ", since values are not numeric " +
            "(int,long, short or double) ");
  }


  public static Query createExactMatchQuery(String fieldName, Object value) {
    return createNumericRangeQuery(fieldName, value, value, true, true);
  }

  public static void setNumericValue(Object value, NumericField numericField) {
    Class numericClass = value.getClass();
    if (numericClass.isAssignableFrom(Double.class)) {
      numericField.setDoubleValue((Double) value);
    }
    if (numericClass.isAssignableFrom(Long.class)) {
      numericField.setLongValue((Long) value);
    }
    if (numericClass.isAssignableFrom(Integer.class)) {
      numericField.setIntValue((Integer) value);
    }
    if (numericClass.isAssignableFrom(Float.class)) {
      numericField.setFloatValue((Float) value);
    }
  }
}
TOP

Related Classes of org.hibernate.search.bridge.util.NumericFieldUtils

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.