Example usage for org.apache.lucene.queries.function.valuesource DoubleConstValueSource DoubleConstValueSource

List of usage examples for org.apache.lucene.queries.function.valuesource DoubleConstValueSource DoubleConstValueSource

Introduction

In this page you can find the example usage for org.apache.lucene.queries.function.valuesource DoubleConstValueSource DoubleConstValueSource.

Prototype

public DoubleConstValueSource(double constant) 

Source Link

Usage

From source file:com.gogobot.DistanceParser.java

License:Apache License

private MultiValueSource parsePoint(FunctionQParser fp) throws SyntaxError {
    String pt = fp.getParam(SpatialParams.POINT);
    if (pt == null)
        return null;
    double[] point = null;
    try {/*from ww w. j a  v a 2 s .com*/
        point = ParseUtils.parseLatitudeLongitude(pt);
    } catch (InvalidShapeException e) {
        throw new SyntaxError("Bad spatial pt:" + pt);
    }
    return new VectorValueSource(Arrays.<ValueSource>asList(new DoubleConstValueSource(point[0]),
            new DoubleConstValueSource(point[1])));
}

From source file:com.ifactory.press.db.solr.HitCount.java

License:Apache License

@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
    // hitcount() takes no arguments.  If we wanted to pass a query
    // we could call fp.parseNestedQuery()
    HashSet<String> fields = new HashSet<String>();
    while (fp.hasMoreArguments()) {
        fields.add(fp.parseArg());/*from w  w w  .  j a  va 2s. co m*/
    }
    Query q = fp.subQuery(fp.getParams().get("q"), "lucene").getQuery();
    HashSet<Term> terms = new HashSet<Term>();
    try {
        q.extractTerms(terms);
    } catch (UnsupportedOperationException e) {
        return new DoubleConstValueSource(1);
    }
    ArrayList<ValueSource> termcounts = new ArrayList<ValueSource>();
    for (Term t : terms) {
        if (fields.isEmpty() || fields.contains(t.field())) {
            termcounts.add(new TermFreqValueSource(t.field(), t.text(), t.field(), t.bytes()));
        }
    }
    return new SumFloatFunction(termcounts.toArray(new ValueSource[termcounts.size()]));
}

From source file:org.apache.solr.search.FunctionQParser.java

License:Apache License

/**
 * Parse an individual value source.//from   ww w  . j a va2s .c  om
 * 
 * @param doConsumeDelimiter whether to consume a delimiter following the ValueSource  
 */
protected ValueSource parseValueSource(boolean doConsumeDelimiter) throws SyntaxError {
    ValueSource valueSource;

    int ch = sp.peek();
    if (ch >= '0' && ch <= '9' || ch == '.' || ch == '+' || ch == '-') {
        Number num = sp.getNumber();
        if (num instanceof Long) {
            valueSource = new LongConstValueSource(num.longValue());
        } else if (num instanceof Double) {
            valueSource = new DoubleConstValueSource(num.doubleValue());
        } else {
            // shouldn't happen
            valueSource = new ConstValueSource(num.floatValue());
        }
    } else if (ch == '"' || ch == '\'') {
        valueSource = new LiteralValueSource(sp.getQuotedString());
    } else if (ch == '$') {
        sp.pos++;
        String param = sp.getId();
        String val = getParam(param);
        if (val == null) {
            throw new SyntaxError("Missing param " + param + " while parsing function '" + sp.val + "'");
        }

        QParser subParser = subQuery(val, "func");
        if (subParser instanceof FunctionQParser) {
            ((FunctionQParser) subParser).setParseMultipleSources(true);
        }
        Query subQuery = subParser.getQuery();
        if (subQuery instanceof FunctionQuery) {
            valueSource = ((FunctionQuery) subQuery).getValueSource();
        } else {
            valueSource = new QueryValueSource(subQuery, 0.0f);
        }

        /***
         // dereference *simple* argument (i.e., can't currently be a function)
         // In the future we could support full function dereferencing via a stack of ValueSource (or StringParser) objects
        ch = val.length()==0 ? '\0' : val.charAt(0);
                
        if (ch>='0' && ch<='9'  || ch=='.' || ch=='+' || ch=='-') {
          QueryParsing.StrParser sp = new QueryParsing.StrParser(val);
          Number num = sp.getNumber();
          if (num instanceof Long) {
            valueSource = new LongConstValueSource(num.longValue());
          } else if (num instanceof Double) {
            valueSource = new DoubleConstValueSource(num.doubleValue());
          } else {
            // shouldn't happen
            valueSource = new ConstValueSource(num.floatValue());
          }
        } else if (ch == '"' || ch == '\'') {
          QueryParsing.StrParser sp = new QueryParsing.StrParser(val);
          val = sp.getQuotedString();
          valueSource = new LiteralValueSource(val);
        } else {
          if (val.length()==0) {
            valueSource = new LiteralValueSource(val);
          } else {
            String id = val;
            SchemaField f = req.getSchema().getField(id);
            valueSource = f.getType().getValueSource(f, this);
          }
        }
         ***/

    } else {

        String id = sp.getId();
        if (sp.opt("(")) {
            // a function... look it up.
            ValueSourceParser argParser = req.getCore().getValueSourceParser(id);
            if (argParser == null) {
                throw new SyntaxError("Unknown function " + id + " in FunctionQuery(" + sp + ")");
            }
            valueSource = argParser.parse(this);
            sp.expect(")");
        } else {
            if ("true".equals(id)) {
                valueSource = new BoolConstValueSource(true);
            } else if ("false".equals(id)) {
                valueSource = new BoolConstValueSource(false);
            } else {
                SchemaField f = req.getSchema().getField(id);
                valueSource = f.getType().getValueSource(f, this);
            }
        }

    }

    if (doConsumeDelimiter)
        consumeArgumentDelimiter();

    return valueSource;
}

From source file:org.elasticsearch.script.expression.ExpressionScriptEngine.java

License:Apache License

private SearchScript.LeafFactory newSearchScript(Expression expr, SearchLookup lookup,
        @Nullable Map<String, Object> vars) {
    MapperService mapper = lookup.doc().mapperService();
    // NOTE: if we need to do anything complicated with bindings in the future, we can just extend Bindings,
    // instead of complicating SimpleBindings (which should stay simple)
    SimpleBindings bindings = new SimpleBindings();
    ReplaceableConstDoubleValueSource specialValue = null;
    boolean needsScores = false;
    for (String variable : expr.variables) {
        try {//  w w w  .  j  av  a 2  s  .  c  o m
            if (variable.equals("_score")) {
                bindings.add(new SortField("_score", SortField.Type.SCORE));
                needsScores = true;
            } else if (variable.equals("_value")) {
                specialValue = new ReplaceableConstDoubleValueSource();
                bindings.add("_value", specialValue);
                // noop: _value is special for aggregations, and is handled in ExpressionScriptBindings
                // TODO: if some uses it in a scoring expression, they will get a nasty failure when evaluating...need a
                // way to know this is for aggregations and so _value is ok to have...

            } else if (vars != null && vars.containsKey(variable)) {
                // TODO: document and/or error if vars contains _score?
                // NOTE: by checking for the variable in vars first, it allows masking document fields with a global constant,
                // but if we were to reverse it, we could provide a way to supply dynamic defaults for documents missing the field?
                Object value = vars.get(variable);
                if (value instanceof Number) {
                    bindings.add(variable,
                            new DoubleConstValueSource(((Number) value).doubleValue()).asDoubleValuesSource());
                } else {
                    throw new ParseException("Parameter [" + variable + "] must be a numeric type", 0);
                }

            } else {
                String fieldname = null;
                String methodname = null;
                String variablename = "value"; // .value is the default for doc['field'], its optional.
                boolean dateAccessor = false; // true if the variable is of type doc['field'].date.xxx
                VariableContext[] parts = VariableContext.parse(variable);
                if (parts[0].text.equals("doc") == false) {
                    throw new ParseException("Unknown variable [" + parts[0].text + "]", 0);
                }
                if (parts.length < 2 || parts[1].type != VariableContext.Type.STR_INDEX) {
                    throw new ParseException(
                            "Variable 'doc' must be used with a specific field like: doc['myfield']", 3);
                } else {
                    fieldname = parts[1].text;
                }
                if (parts.length == 3) {
                    if (parts[2].type == VariableContext.Type.METHOD) {
                        methodname = parts[2].text;
                    } else if (parts[2].type == VariableContext.Type.MEMBER) {
                        variablename = parts[2].text;
                    } else {
                        throw new IllegalArgumentException(
                                "Only member variables or member methods may be accessed on a field when not accessing the field directly");
                    }
                }
                if (parts.length > 3) {
                    // access to the .date "object" within the field
                    if (parts.length == 4
                            && ("date".equals(parts[2].text) || "getDate".equals(parts[2].text))) {
                        if (parts[3].type == VariableContext.Type.METHOD) {
                            methodname = parts[3].text;
                            dateAccessor = true;
                        } else if (parts[3].type == VariableContext.Type.MEMBER) {
                            variablename = parts[3].text;
                            dateAccessor = true;
                        }
                    }
                    if (!dateAccessor) {
                        throw new IllegalArgumentException("Variable [" + variable
                                + "] does not follow an allowed format of either doc['field'] or doc['field'].method()");
                    }
                }

                MappedFieldType fieldType = mapper.fullName(fieldname);

                if (fieldType == null) {
                    throw new ParseException("Field [" + fieldname + "] does not exist in mappings", 5);
                }

                IndexFieldData<?> fieldData = lookup.doc().getForField(fieldType);

                // delegate valuesource creation based on field's type
                // there are three types of "fields" to expressions, and each one has a different "api" of variables and methods.

                final ValueSource valueSource;
                if (fieldType instanceof GeoPointFieldType) {
                    // geo
                    if (methodname == null) {
                        valueSource = GeoField.getVariable(fieldData, fieldname, variablename);
                    } else {
                        valueSource = GeoField.getMethod(fieldData, fieldname, methodname);
                    }
                } else if (fieldType instanceof DateFieldMapper.DateFieldType) {
                    if (dateAccessor) {
                        // date object
                        if (methodname == null) {
                            valueSource = DateObject.getVariable(fieldData, fieldname, variablename);
                        } else {
                            valueSource = DateObject.getMethod(fieldData, fieldname, methodname);
                        }
                    } else {
                        // date field itself
                        if (methodname == null) {
                            valueSource = DateField.getVariable(fieldData, fieldname, variablename);
                        } else {
                            valueSource = DateField.getMethod(fieldData, fieldname, methodname);
                        }
                    }
                } else if (fieldData instanceof IndexNumericFieldData) {
                    // number
                    if (methodname == null) {
                        valueSource = NumericField.getVariable(fieldData, fieldname, variablename);
                    } else {
                        valueSource = NumericField.getMethod(fieldData, fieldname, methodname);
                    }
                } else {
                    throw new ParseException("Field [" + fieldname + "] must be numeric, date, or geopoint", 5);
                }
                needsScores |= valueSource.getSortField(false).needsScores();
                bindings.add(variable, valueSource.asDoubleValuesSource());
            }
        } catch (Exception e) {
            // we defer "binding" of variables until here: give context for that variable
            throw convertToScriptException("link error", expr.sourceText, variable, e);
        }
    }
    return new ExpressionSearchScript(expr, bindings, specialValue, needsScores);
}

From source file:org.elasticsearch.script.expression.ExpressionScriptEngineService.java

License:Apache License

@Override
public SearchScript search(CompiledScript compiledScript, SearchLookup lookup,
        @Nullable Map<String, Object> vars) {
    try {//from w  w  w  . jav  a  2 s  .  c o m
        Expression expr = (Expression) compiledScript.compiled();
        MapperService mapper = lookup.doc().mapperService();
        // NOTE: if we need to do anything complicated with bindings in the future, we can just extend Bindings,
        // instead of complicating SimpleBindings (which should stay simple)
        SimpleBindings bindings = new SimpleBindings();
        ReplaceableConstValueSource specialValue = null;

        for (String variable : expr.variables) {
            if (variable.equals("_score")) {
                bindings.add(new SortField("_score", SortField.Type.SCORE));
            } else if (variable.equals("_value")) {
                specialValue = new ReplaceableConstValueSource();
                bindings.add("_value", specialValue);
                // noop: _value is special for aggregations, and is handled in ExpressionScriptBindings
                // TODO: if some uses it in a scoring expression, they will get a nasty failure when evaluating...need a
                // way to know this is for aggregations and so _value is ok to have...

            } else if (vars != null && vars.containsKey(variable)) {
                // TODO: document and/or error if vars contains _score?
                // NOTE: by checking for the variable in vars first, it allows masking document fields with a global constant,
                // but if we were to reverse it, we could provide a way to supply dynamic defaults for documents missing the field?
                Object value = vars.get(variable);
                if (value instanceof Number) {
                    bindings.add(variable, new DoubleConstValueSource(((Number) value).doubleValue()));
                } else {
                    throw new ScriptException("Parameter [" + variable + "] must be a numeric type");
                }

            } else {
                String fieldname = null;
                String methodname = null;
                VariableContext[] parts = VariableContext.parse(variable);
                if (parts[0].text.equals("doc") == false) {
                    throw new ScriptException("Unknown variable [" + parts[0].text + "] in expression");
                }
                if (parts.length < 2 || parts[1].type != VariableContext.Type.STR_INDEX) {
                    throw new ScriptException(
                            "Variable 'doc' in expression must be used with a specific field like: doc['myfield']");
                } else {
                    fieldname = parts[1].text;
                }
                if (parts.length == 3) {
                    if (parts[2].type == VariableContext.Type.METHOD) {
                        methodname = parts[2].text;
                    } else if (parts[2].type != VariableContext.Type.MEMBER || !"value".equals(parts[2].text)) {
                        throw new ScriptException(
                                "Only the member variable [value] or member methods may be accessed on a field when not accessing the field directly");
                    }
                }
                if (parts.length > 3) {
                    throw new ScriptException("Variable [" + variable
                            + "] does not follow an allowed format of either doc['field'] or doc['field'].method()");
                }

                MappedFieldType fieldType = mapper.smartNameFieldType(fieldname);

                if (fieldType == null) {
                    throw new ScriptException(
                            "Field [" + fieldname + "] used in expression does not exist in mappings");
                }
                if (fieldType.isNumeric() == false) {
                    // TODO: more context (which expression?)
                    throw new ScriptException("Field [" + fieldname + "] used in expression must be numeric");
                }

                IndexFieldData<?> fieldData = lookup.doc().fieldDataService()
                        .getForField((NumberFieldMapper.NumberFieldType) fieldType);
                if (methodname == null) {
                    bindings.add(variable, new FieldDataValueSource(fieldData, MultiValueMode.MIN));
                } else {
                    bindings.add(variable, getMethodValueSource(fieldType, fieldData, fieldname, methodname));
                }
            }
        }

        final boolean needsScores = expr.getSortField(bindings, false).needsScores();
        return new ExpressionSearchScript(compiledScript, bindings, specialValue, needsScores);
    } catch (Exception exception) {
        throw new ScriptException("Error during search with " + compiledScript, exception);
    }
}