Search in sources :

Example 1 with SearchScript

use of org.elasticsearch.script.SearchScript in project elasticsearch by elastic.

the class NeedsScoreTests method testNeedsScores.

public void testNeedsScores() {
    IndexService index = createIndex("test", Settings.EMPTY, "type", "d", "type=double");
    PainlessScriptEngineService service = new PainlessScriptEngineService(Settings.EMPTY);
    SearchLookup lookup = new SearchLookup(index.mapperService(), index.fieldData(), null);
    Object compiled = service.compile(null, "1.2", Collections.emptyMap());
    SearchScript ss = service.search(new CompiledScript(ScriptType.INLINE, "randomName", "painless", compiled), lookup, Collections.<String, Object>emptyMap());
    assertFalse(ss.needsScores());
    compiled = service.compile(null, "doc['d'].value", Collections.emptyMap());
    ss = service.search(new CompiledScript(ScriptType.INLINE, "randomName", "painless", compiled), lookup, Collections.<String, Object>emptyMap());
    assertFalse(ss.needsScores());
    compiled = service.compile(null, "1/_score", Collections.emptyMap());
    ss = service.search(new CompiledScript(ScriptType.INLINE, "randomName", "painless", compiled), lookup, Collections.<String, Object>emptyMap());
    assertTrue(ss.needsScores());
    compiled = service.compile(null, "doc['d'].value * _score", Collections.emptyMap());
    ss = service.search(new CompiledScript(ScriptType.INLINE, "randomName", "painless", compiled), lookup, Collections.<String, Object>emptyMap());
    assertTrue(ss.needsScores());
    service.close();
}
Also used : CompiledScript(org.elasticsearch.script.CompiledScript) SearchScript(org.elasticsearch.script.SearchScript) IndexService(org.elasticsearch.index.IndexService) SearchLookup(org.elasticsearch.search.lookup.SearchLookup)

Example 2 with SearchScript

use of org.elasticsearch.script.SearchScript in project elasticsearch by elastic.

the class ScriptSortBuilder method build.

@Override
public SortFieldAndFormat build(QueryShardContext context) throws IOException {
    final SearchScript searchScript = context.getSearchScript(script, ScriptContext.Standard.SEARCH);
    MultiValueMode valueMode = null;
    if (sortMode != null) {
        valueMode = MultiValueMode.fromString(sortMode.toString());
    }
    boolean reverse = (order == SortOrder.DESC);
    if (valueMode == null) {
        valueMode = reverse ? MultiValueMode.MAX : MultiValueMode.MIN;
    }
    final Nested nested = resolveNested(context, nestedPath, nestedFilter);
    final IndexFieldData.XFieldComparatorSource fieldComparatorSource;
    switch(type) {
        case STRING:
            fieldComparatorSource = new BytesRefFieldComparatorSource(null, null, valueMode, nested) {

                LeafSearchScript leafScript;

                @Override
                protected SortedBinaryDocValues getValues(LeafReaderContext context) throws IOException {
                    leafScript = searchScript.getLeafSearchScript(context);
                    final BinaryDocValues values = new BinaryDocValues() {

                        final BytesRefBuilder spare = new BytesRefBuilder();

                        @Override
                        public BytesRef get(int docID) {
                            leafScript.setDocument(docID);
                            spare.copyChars(leafScript.run().toString());
                            return spare.get();
                        }
                    };
                    return FieldData.singleton(values, null);
                }

                @Override
                protected void setScorer(Scorer scorer) {
                    leafScript.setScorer(scorer);
                }
            };
            break;
        case NUMBER:
            fieldComparatorSource = new DoubleValuesComparatorSource(null, Double.MAX_VALUE, valueMode, nested) {

                LeafSearchScript leafScript;

                @Override
                protected SortedNumericDoubleValues getValues(LeafReaderContext context) throws IOException {
                    leafScript = searchScript.getLeafSearchScript(context);
                    final NumericDoubleValues values = new NumericDoubleValues() {

                        @Override
                        public double get(int docID) {
                            leafScript.setDocument(docID);
                            return leafScript.runAsDouble();
                        }
                    };
                    return FieldData.singleton(values, null);
                }

                @Override
                protected void setScorer(Scorer scorer) {
                    leafScript.setScorer(scorer);
                }
            };
            break;
        default:
            throw new QueryShardException(context, "custom script sort type [" + type + "] not supported");
    }
    return new SortFieldAndFormat(new SortField("_script", fieldComparatorSource, reverse), DocValueFormat.RAW);
}
Also used : BytesRefBuilder(org.apache.lucene.util.BytesRefBuilder) DoubleValuesComparatorSource(org.elasticsearch.index.fielddata.fieldcomparator.DoubleValuesComparatorSource) Nested(org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested) BytesRefFieldComparatorSource(org.elasticsearch.index.fielddata.fieldcomparator.BytesRefFieldComparatorSource) Scorer(org.apache.lucene.search.Scorer) NumericDoubleValues(org.elasticsearch.index.fielddata.NumericDoubleValues) SortedNumericDoubleValues(org.elasticsearch.index.fielddata.SortedNumericDoubleValues) SortField(org.apache.lucene.search.SortField) IOException(java.io.IOException) MultiValueMode(org.elasticsearch.search.MultiValueMode) SortedBinaryDocValues(org.elasticsearch.index.fielddata.SortedBinaryDocValues) BinaryDocValues(org.apache.lucene.index.BinaryDocValues) SortedBinaryDocValues(org.elasticsearch.index.fielddata.SortedBinaryDocValues) LeafSearchScript(org.elasticsearch.script.LeafSearchScript) SearchScript(org.elasticsearch.script.SearchScript) LeafSearchScript(org.elasticsearch.script.LeafSearchScript) IndexFieldData(org.elasticsearch.index.fielddata.IndexFieldData) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) QueryShardException(org.elasticsearch.index.query.QueryShardException) SortedNumericDoubleValues(org.elasticsearch.index.fielddata.SortedNumericDoubleValues) BytesRef(org.apache.lucene.util.BytesRef)

Example 3 with SearchScript

use of org.elasticsearch.script.SearchScript in project elasticsearch by elastic.

the class QueryShardContext method getLazySearchScript.

/**
     * Returns a lazily created {@link SearchScript} that is compiled immediately but can be pulled later once all
     * parameters are available.
     */
public final Function<Map<String, Object>, SearchScript> getLazySearchScript(Script script, ScriptContext context) {
    failIfFrozen();
    CompiledScript compile = scriptService.compile(script, context);
    return (p) -> scriptService.search(lookup(), compile, p);
}
Also used : CompiledScript(org.elasticsearch.script.CompiledScript) Query(org.apache.lucene.search.Query) BitsetFilterCache(org.elasticsearch.index.cache.bitset.BitsetFilterCache) Arrays(java.util.Arrays) LongSupplier(java.util.function.LongSupplier) ParsingException(org.elasticsearch.common.ParsingException) IndexFieldDataService(org.elasticsearch.index.fielddata.IndexFieldDataService) IndexAnalyzers(org.elasticsearch.index.analysis.IndexAnalyzers) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) MapperQueryParser(org.apache.lucene.queryparser.classic.MapperQueryParser) Function(java.util.function.Function) ScriptContext(org.elasticsearch.script.ScriptContext) Strings(org.elasticsearch.common.Strings) NestedScope(org.elasticsearch.index.query.support.NestedScope) BitSetProducer(org.apache.lucene.search.join.BitSetProducer) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) Similarity(org.apache.lucene.search.similarities.Similarity) Map(java.util.Map) IndexSettings(org.elasticsearch.index.IndexSettings) QueryParserSettings(org.apache.lucene.queryparser.classic.QueryParserSettings) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) DocumentMapper(org.elasticsearch.index.mapper.DocumentMapper) SearchScript(org.elasticsearch.script.SearchScript) SearchLookup(org.elasticsearch.search.lookup.SearchLookup) ObjectMapper(org.elasticsearch.index.mapper.ObjectMapper) Script(org.elasticsearch.script.Script) SetOnce(org.apache.lucene.util.SetOnce) Mapper(org.elasticsearch.index.mapper.Mapper) Analyzer(org.apache.lucene.analysis.Analyzer) Client(org.elasticsearch.client.Client) Collection(java.util.Collection) IOException(java.io.IOException) TextFieldMapper(org.elasticsearch.index.mapper.TextFieldMapper) BytesReference(org.elasticsearch.common.bytes.BytesReference) SimilarityService(org.elasticsearch.index.similarity.SimilarityService) CheckedFunction(org.elasticsearch.common.CheckedFunction) MapperService(org.elasticsearch.index.mapper.MapperService) Version(org.elasticsearch.Version) CompiledScript(org.elasticsearch.script.CompiledScript) IndexFieldData(org.elasticsearch.index.fielddata.IndexFieldData) Queries(org.elasticsearch.common.lucene.search.Queries) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) ExecutableScript(org.elasticsearch.script.ExecutableScript) ContentPath(org.elasticsearch.index.mapper.ContentPath) ScriptService(org.elasticsearch.script.ScriptService) IndexReader(org.apache.lucene.index.IndexReader)

Example 4 with SearchScript

use of org.elasticsearch.script.SearchScript in project elasticsearch by elastic.

the class InnerHitBuilder method setupInnerHitsContext.

private void setupInnerHitsContext(QueryShardContext context, InnerHitsContext.BaseInnerHits innerHitsContext) throws IOException {
    innerHitsContext.from(from);
    innerHitsContext.size(size);
    innerHitsContext.explain(explain);
    innerHitsContext.version(version);
    innerHitsContext.trackScores(trackScores);
    if (storedFieldsContext != null) {
        innerHitsContext.storedFieldsContext(storedFieldsContext);
    }
    if (docValueFields != null) {
        innerHitsContext.docValueFieldsContext(new DocValueFieldsContext(docValueFields));
    }
    if (scriptFields != null) {
        for (ScriptField field : scriptFields) {
            SearchScript searchScript = innerHitsContext.getQueryShardContext().getSearchScript(field.script(), ScriptContext.Standard.SEARCH);
            innerHitsContext.scriptFields().add(new org.elasticsearch.search.fetch.subphase.ScriptFieldsContext.ScriptField(field.fieldName(), searchScript, field.ignoreFailure()));
        }
    }
    if (fetchSourceContext != null) {
        innerHitsContext.fetchSourceContext(fetchSourceContext);
    }
    if (sorts != null) {
        Optional<SortAndFormats> optionalSort = SortBuilder.buildSort(sorts, context);
        if (optionalSort.isPresent()) {
            innerHitsContext.sort(optionalSort.get());
        }
    }
    if (highlightBuilder != null) {
        innerHitsContext.highlight(highlightBuilder.build(context));
    }
    ParsedQuery parsedQuery = new ParsedQuery(query.toQuery(context), context.copyNamedQueries());
    innerHitsContext.parsedQuery(parsedQuery);
}
Also used : SearchScript(org.elasticsearch.script.SearchScript) ScriptField(org.elasticsearch.search.builder.SearchSourceBuilder.ScriptField) DocValueFieldsContext(org.elasticsearch.search.fetch.subphase.DocValueFieldsContext) SortAndFormats(org.elasticsearch.search.sort.SortAndFormats)

Example 5 with SearchScript

use of org.elasticsearch.script.SearchScript in project elasticsearch by elastic.

the class TopHitsAggregationBuilder method doBuild.

@Override
protected TopHitsAggregatorFactory doBuild(SearchContext context, AggregatorFactory<?> parent, Builder subfactoriesBuilder) throws IOException {
    List<ScriptFieldsContext.ScriptField> fields = new ArrayList<>();
    if (scriptFields != null) {
        for (ScriptField field : scriptFields) {
            SearchScript searchScript = context.getQueryShardContext().getSearchScript(field.script(), ScriptContext.Standard.SEARCH);
            fields.add(new org.elasticsearch.search.fetch.subphase.ScriptFieldsContext.ScriptField(field.fieldName(), searchScript, field.ignoreFailure()));
        }
    }
    final Optional<SortAndFormats> optionalSort;
    if (sorts == null) {
        optionalSort = Optional.empty();
    } else {
        optionalSort = SortBuilder.buildSort(sorts, context.getQueryShardContext());
    }
    return new TopHitsAggregatorFactory(name, from, size, explain, version, trackScores, optionalSort, highlightBuilder, storedFieldsContext, fieldDataFields, fields, fetchSourceContext, context, parent, subfactoriesBuilder, metaData);
}
Also used : ScriptFieldsContext(org.elasticsearch.search.fetch.subphase.ScriptFieldsContext) SearchScript(org.elasticsearch.script.SearchScript) ScriptField(org.elasticsearch.search.builder.SearchSourceBuilder.ScriptField) ArrayList(java.util.ArrayList) SortAndFormats(org.elasticsearch.search.sort.SortAndFormats)

Aggregations

SearchScript (org.elasticsearch.script.SearchScript)9 IOException (java.io.IOException)4 Map (java.util.Map)3 SortAndFormats (org.elasticsearch.search.sort.SortAndFormats)3 HashMap (java.util.HashMap)2 LeafReaderContext (org.apache.lucene.index.LeafReaderContext)2 IndexFieldData (org.elasticsearch.index.fielddata.IndexFieldData)2 QueryShardContext (org.elasticsearch.index.query.QueryShardContext)2 CompiledScript (org.elasticsearch.script.CompiledScript)2 ExecutableScript (org.elasticsearch.script.ExecutableScript)2 Script (org.elasticsearch.script.Script)2 ScriptField (org.elasticsearch.search.builder.SearchSourceBuilder.ScriptField)2 SearchLookup (org.elasticsearch.search.lookup.SearchLookup)2 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Collections.unmodifiableMap (java.util.Collections.unmodifiableMap)1 Function (java.util.function.Function)1 LongSupplier (java.util.function.LongSupplier)1 Analyzer (org.apache.lucene.analysis.Analyzer)1