Search in sources :

Example 6 with Expression

use of org.apache.lucene.expressions.Expression in project lucene-solr by apache.

the class TestJavascriptOperations method assertEvaluatesTo.

private void assertEvaluatesTo(String expression, long expected) throws Exception {
    Expression evaluator = JavascriptCompiler.compile(expression);
    long actual = (long) evaluator.evaluate(null);
    assertEquals(expected, actual);
}
Also used : Expression(org.apache.lucene.expressions.Expression)

Example 7 with Expression

use of org.apache.lucene.expressions.Expression in project lucene-solr by apache.

the class TestCustomFunctions method testThrowingException.

/** the method throws an exception. We should check the stack trace that it contains the source code of the expression as file name. */
public void testThrowingException() throws Exception {
    Map<String, Method> functions = new HashMap<>();
    functions.put("foo", StaticThrowingException.class.getMethod("method"));
    String source = "3 * foo() / 5";
    Expression expr = JavascriptCompiler.compile(source, functions, getClass().getClassLoader());
    ArithmeticException expected = expectThrows(ArithmeticException.class, () -> {
        expr.evaluate(null);
    });
    assertEquals(MESSAGE, expected.getMessage());
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    expected.printStackTrace(pw);
    pw.flush();
    assertTrue(sw.toString().contains("JavascriptCompiler$CompiledExpression.evaluate(" + source + ")"));
}
Also used : StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) Expression(org.apache.lucene.expressions.Expression) Method(java.lang.reflect.Method) PrintWriter(java.io.PrintWriter)

Example 8 with Expression

use of org.apache.lucene.expressions.Expression in project lucene-solr by apache.

the class DistanceFacetsExample method getDistanceValueSource.

private DoubleValuesSource getDistanceValueSource() {
    Expression distance;
    try {
        distance = JavascriptCompiler.compile("haversin(" + ORIGIN_LATITUDE + "," + ORIGIN_LONGITUDE + ",latitude,longitude)");
    } catch (ParseException pe) {
        // Should not happen
        throw new RuntimeException(pe);
    }
    SimpleBindings bindings = new SimpleBindings();
    bindings.add(new SortField("latitude", SortField.Type.DOUBLE));
    bindings.add(new SortField("longitude", SortField.Type.DOUBLE));
    return distance.getDoubleValuesSource(bindings);
}
Also used : Expression(org.apache.lucene.expressions.Expression) SimpleBindings(org.apache.lucene.expressions.SimpleBindings) SortField(org.apache.lucene.search.SortField) ParseException(java.text.ParseException)

Example 9 with Expression

use of org.apache.lucene.expressions.Expression in project elasticsearch by elastic.

the class ExpressionScriptEngineService method compile.

@Override
public Object compile(String scriptName, String scriptSource, Map<String, String> params) {
    // classloader created here
    final SecurityManager sm = System.getSecurityManager();
    SpecialPermission.check();
    return AccessController.doPrivileged(new PrivilegedAction<Expression>() {

        @Override
        public Expression run() {
            try {
                // snapshot our context here, we check on behalf of the expression
                AccessControlContext engineContext = AccessController.getContext();
                ClassLoader loader = getClass().getClassLoader();
                if (sm != null) {
                    loader = new ClassLoader(loader) {

                        @Override
                        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
                            try {
                                engineContext.checkPermission(new ClassPermission(name));
                            } catch (SecurityException e) {
                                throw new ClassNotFoundException(name, e);
                            }
                            return super.loadClass(name, resolve);
                        }
                    };
                }
                // NOTE: validation is delayed to allow runtime vars, and we don't have access to per index stuff here
                return JavascriptCompiler.compile(scriptSource, JavascriptCompiler.DEFAULT_FUNCTIONS, loader);
            } catch (ParseException e) {
                throw convertToScriptException("compile error", scriptSource, scriptSource, e);
            }
        }
    });
}
Also used : ClassPermission(org.elasticsearch.script.ClassPermission) AccessControlContext(java.security.AccessControlContext) Expression(org.apache.lucene.expressions.Expression) ParseException(java.text.ParseException)

Example 10 with Expression

use of org.apache.lucene.expressions.Expression in project elasticsearch by elastic.

the class ExpressionScriptEngineService method search.

@Override
public SearchScript search(CompiledScript compiledScript, SearchLookup lookup, @Nullable Map<String, Object> vars) {
    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();
    ReplaceableConstDoubleValueSource specialValue = null;
    boolean needsScores = false;
    for (String variable : expr.variables) {
        try {
            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;
                // .value is the default for doc['field'], its optional.
                String variablename = "value";
                // true if the variable is of type doc['field'].date.xxx
                boolean dateAccessor = false;
                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().fieldDataService().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(compiledScript, bindings, specialValue, needsScores);
}
Also used : DateFieldMapper(org.elasticsearch.index.mapper.DateFieldMapper) IndexNumericFieldData(org.elasticsearch.index.fielddata.IndexNumericFieldData) SortField(org.apache.lucene.search.SortField) VariableContext(org.apache.lucene.expressions.js.VariableContext) ParseException(java.text.ParseException) ScriptException(org.elasticsearch.script.ScriptException) DoubleConstValueSource(org.apache.lucene.queries.function.valuesource.DoubleConstValueSource) Expression(org.apache.lucene.expressions.Expression) SimpleBindings(org.apache.lucene.expressions.SimpleBindings) DoubleConstValueSource(org.apache.lucene.queries.function.valuesource.DoubleConstValueSource) ValueSource(org.apache.lucene.queries.function.ValueSource) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) GeoPointFieldType(org.elasticsearch.index.mapper.GeoPointFieldMapper.GeoPointFieldType) ParseException(java.text.ParseException) MapperService(org.elasticsearch.index.mapper.MapperService)

Aggregations

Expression (org.apache.lucene.expressions.Expression)18 Method (java.lang.reflect.Method)8 HashMap (java.util.HashMap)8 ParseException (java.text.ParseException)4 SimpleBindings (org.apache.lucene.expressions.SimpleBindings)4 SortField (org.apache.lucene.search.SortField)4 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 AccessControlContext (java.security.AccessControlContext)1 VariableContext (org.apache.lucene.expressions.js.VariableContext)1 FacetResult (org.apache.lucene.facet.FacetResult)1 Facets (org.apache.lucene.facet.Facets)1 FacetsCollector (org.apache.lucene.facet.FacetsCollector)1 TaxonomyFacetSumValueSource (org.apache.lucene.facet.taxonomy.TaxonomyFacetSumValueSource)1 TaxonomyReader (org.apache.lucene.facet.taxonomy.TaxonomyReader)1 DirectoryTaxonomyReader (org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader)1 DirectoryReader (org.apache.lucene.index.DirectoryReader)1 ValueSource (org.apache.lucene.queries.function.ValueSource)1 DoubleConstValueSource (org.apache.lucene.queries.function.valuesource.DoubleConstValueSource)1 IndexSearcher (org.apache.lucene.search.IndexSearcher)1