Search in sources :

Example 41 with Explanation

use of org.apache.lucene.search.Explanation in project elasticsearch by elastic.

the class TopHitsIT method testFetchFeatures.

public void testFetchFeatures() {
    SearchResponse response = client().prepareSearch("idx").setTypes("type").setQuery(matchQuery("text", "text").queryName("test")).addAggregation(terms("terms").executionHint(randomExecutionHint()).field(TERMS_AGGS_FIELD).subAggregation(topHits("hits").size(1).highlighter(new HighlightBuilder().field("text")).explain(true).storedField("text").fieldDataField("field1").scriptField("script", new Script(ScriptType.INLINE, MockScriptEngine.NAME, "5", Collections.emptyMap())).fetchSource("text", null).version(true))).get();
    assertSearchResponse(response);
    Terms terms = response.getAggregations().get("terms");
    assertThat(terms, notNullValue());
    assertThat(terms.getName(), equalTo("terms"));
    assertThat(terms.getBuckets().size(), equalTo(5));
    for (Terms.Bucket bucket : terms.getBuckets()) {
        TopHits topHits = bucket.getAggregations().get("hits");
        SearchHits hits = topHits.getHits();
        assertThat(hits.getTotalHits(), equalTo(10L));
        assertThat(hits.getHits().length, equalTo(1));
        SearchHit hit = hits.getAt(0);
        HighlightField highlightField = hit.getHighlightFields().get("text");
        assertThat(highlightField.getFragments().length, equalTo(1));
        assertThat(highlightField.getFragments()[0].string(), equalTo("some <em>text</em> to entertain"));
        Explanation explanation = hit.getExplanation();
        assertThat(explanation.toString(), containsString("text:text"));
        long version = hit.getVersion();
        assertThat(version, equalTo(1L));
        assertThat(hit.getMatchedQueries()[0], equalTo("test"));
        SearchHitField field = hit.field("field1");
        assertThat(field.getValue().toString(), equalTo("5"));
        assertThat(hit.getSourceAsMap().get("text").toString(), equalTo("some text to entertain"));
        field = hit.field("script");
        assertThat(field.getValue().toString(), equalTo("5"));
        assertThat(hit.getSourceAsMap().size(), equalTo(1));
        assertThat(hit.getSourceAsMap().get("text").toString(), equalTo("some text to entertain"));
    }
}
Also used : Script(org.elasticsearch.script.Script) TopHits(org.elasticsearch.search.aggregations.metrics.tophits.TopHits) SearchHit(org.elasticsearch.search.SearchHit) Explanation(org.apache.lucene.search.Explanation) Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms) HighlightField(org.elasticsearch.search.fetch.subphase.highlight.HighlightField) SearchHitField(org.elasticsearch.search.SearchHitField) SearchHits(org.elasticsearch.search.SearchHits) HighlightBuilder(org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)

Example 42 with Explanation

use of org.apache.lucene.search.Explanation in project elasticsearch by elastic.

the class CandidateQueryTests method duelRun.

private void duelRun(PercolateQuery.QueryStore queryStore, MemoryIndex memoryIndex, IndexSearcher shardSearcher) throws IOException {
    boolean requireScore = randomBoolean();
    IndexSearcher percolateSearcher = memoryIndex.createSearcher();
    Query percolateQuery = fieldType.percolateQuery("type", queryStore, new BytesArray("{}"), percolateSearcher);
    Query query = requireScore ? percolateQuery : new ConstantScoreQuery(percolateQuery);
    TopDocs topDocs = shardSearcher.search(query, 10);
    Query controlQuery = new ControlQuery(memoryIndex, queryStore);
    controlQuery = requireScore ? controlQuery : new ConstantScoreQuery(controlQuery);
    TopDocs controlTopDocs = shardSearcher.search(controlQuery, 10);
    assertThat(topDocs.totalHits, equalTo(controlTopDocs.totalHits));
    assertThat(topDocs.scoreDocs.length, equalTo(controlTopDocs.scoreDocs.length));
    for (int j = 0; j < topDocs.scoreDocs.length; j++) {
        assertThat(topDocs.scoreDocs[j].doc, equalTo(controlTopDocs.scoreDocs[j].doc));
        assertThat(topDocs.scoreDocs[j].score, equalTo(controlTopDocs.scoreDocs[j].score));
        if (requireScore) {
            Explanation explain1 = shardSearcher.explain(query, topDocs.scoreDocs[j].doc);
            Explanation explain2 = shardSearcher.explain(controlQuery, controlTopDocs.scoreDocs[j].doc);
            assertThat(explain1.isMatch(), equalTo(explain2.isMatch()));
            assertThat(explain1.getValue(), equalTo(explain2.getValue()));
        }
    }
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) TopDocs(org.apache.lucene.search.TopDocs) BytesArray(org.elasticsearch.common.bytes.BytesArray) Query(org.apache.lucene.search.Query) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) CommonTermsQuery(org.apache.lucene.queries.CommonTermsQuery) BlendedTermQuery(org.apache.lucene.queries.BlendedTermQuery) PrefixQuery(org.apache.lucene.search.PrefixQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) SpanNotQuery(org.apache.lucene.search.spans.SpanNotQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) SpanNearQuery(org.apache.lucene.search.spans.SpanNearQuery) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) SpanOrQuery(org.apache.lucene.search.spans.SpanOrQuery) Explanation(org.apache.lucene.search.Explanation) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) LongPoint(org.apache.lucene.document.LongPoint)

Example 43 with Explanation

use of org.apache.lucene.search.Explanation in project elasticsearch by elastic.

the class AllTermQuery method createWeight.

@Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
    if (needsScores == false) {
        return new TermQuery(term).createWeight(searcher, needsScores);
    }
    final TermContext termStates = TermContext.build(searcher.getTopReaderContext(), term);
    final CollectionStatistics collectionStats = searcher.collectionStatistics(term.field());
    final TermStatistics termStats = searcher.termStatistics(term, termStates);
    final Similarity similarity = searcher.getSimilarity(needsScores);
    final SimWeight stats = similarity.computeWeight(collectionStats, termStats);
    return new Weight(this) {

        @Override
        public float getValueForNormalization() throws IOException {
            return stats.getValueForNormalization();
        }

        @Override
        public void normalize(float norm, float topLevelBoost) {
            stats.normalize(norm, topLevelBoost);
        }

        @Override
        public void extractTerms(Set<Term> terms) {
            terms.add(term);
        }

        @Override
        public Explanation explain(LeafReaderContext context, int doc) throws IOException {
            AllTermScorer scorer = scorer(context);
            if (scorer != null) {
                int newDoc = scorer.iterator().advance(doc);
                if (newDoc == doc) {
                    float score = scorer.score();
                    float freq = scorer.freq();
                    SimScorer docScorer = similarity.simScorer(stats, context);
                    Explanation freqExplanation = Explanation.match(freq, "termFreq=" + freq);
                    Explanation termScoreExplanation = docScorer.explain(doc, freqExplanation);
                    Explanation payloadBoostExplanation = Explanation.match(scorer.payloadBoost(), "payloadBoost=" + scorer.payloadBoost());
                    return Explanation.match(score, "weight(" + getQuery() + " in " + doc + ") [" + similarity.getClass().getSimpleName() + "], product of:", termScoreExplanation, payloadBoostExplanation);
                }
            }
            return Explanation.noMatch("no matching term");
        }

        @Override
        public AllTermScorer scorer(LeafReaderContext context) throws IOException {
            final Terms terms = context.reader().terms(term.field());
            if (terms == null) {
                return null;
            }
            final TermsEnum termsEnum = terms.iterator();
            if (termsEnum == null) {
                return null;
            }
            final TermState state = termStates.get(context.ord);
            if (state == null) {
                // Term does not exist in this segment
                return null;
            }
            termsEnum.seekExact(term.bytes(), state);
            PostingsEnum docs = termsEnum.postings(null, PostingsEnum.PAYLOADS);
            assert docs != null;
            return new AllTermScorer(this, docs, similarity.simScorer(stats, context));
        }
    };
}
Also used : TermQuery(org.apache.lucene.search.TermQuery) Set(java.util.Set) Similarity(org.apache.lucene.search.similarities.Similarity) Explanation(org.apache.lucene.search.Explanation) SimWeight(org.apache.lucene.search.similarities.Similarity.SimWeight) Terms(org.apache.lucene.index.Terms) SimScorer(org.apache.lucene.search.similarities.Similarity.SimScorer) TermStatistics(org.apache.lucene.search.TermStatistics) TermContext(org.apache.lucene.index.TermContext) Weight(org.apache.lucene.search.Weight) SimWeight(org.apache.lucene.search.similarities.Similarity.SimWeight) CollectionStatistics(org.apache.lucene.search.CollectionStatistics) TermsEnum(org.apache.lucene.index.TermsEnum) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) TermState(org.apache.lucene.index.TermState) PostingsEnum(org.apache.lucene.index.PostingsEnum)

Example 44 with Explanation

use of org.apache.lucene.search.Explanation in project elasticsearch by elastic.

the class RandomScoreFunction method getLeafScoreFunction.

@Override
public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) {
    AtomicFieldData leafData = uidFieldData.load(ctx);
    final SortedBinaryDocValues uidByteData = leafData.getBytesValues();
    if (uidByteData == null)
        throw new NullPointerException("failed to get uid byte data");
    return new LeafScoreFunction() {

        @Override
        public double score(int docId, float subQueryScore) {
            uidByteData.setDocument(docId);
            int hash = StringHelper.murmurhash3_x86_32(uidByteData.valueAt(0), saltedSeed);
            // only use the lower 24 bits to construct a float from 0.0-1.0
            return (hash & 0x00FFFFFF) / (float) (1 << 24);
        }

        @Override
        public Explanation explainScore(int docId, Explanation subQueryScore) {
            return Explanation.match(CombineFunction.toFloat(score(docId, subQueryScore.getValue())), "random score function (seed: " + originalSeed + ")");
        }
    };
}
Also used : Explanation(org.apache.lucene.search.Explanation) AtomicFieldData(org.elasticsearch.index.fielddata.AtomicFieldData) SortedBinaryDocValues(org.elasticsearch.index.fielddata.SortedBinaryDocValues)

Example 45 with Explanation

use of org.apache.lucene.search.Explanation in project elasticsearch by elastic.

the class FieldValueFactorFunction method getLeafScoreFunction.

@Override
public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) {
    final SortedNumericDoubleValues values;
    if (indexFieldData == null) {
        values = FieldData.emptySortedNumericDoubles(ctx.reader().maxDoc());
    } else {
        values = this.indexFieldData.load(ctx).getDoubleValues();
    }
    return new LeafScoreFunction() {

        @Override
        public double score(int docId, float subQueryScore) {
            values.setDocument(docId);
            final int numValues = values.count();
            double value;
            if (numValues > 0) {
                value = values.valueAt(0);
            } else if (missing != null) {
                value = missing;
            } else {
                throw new ElasticsearchException("Missing value for field [" + field + "]");
            }
            double val = value * boostFactor;
            double result = modifier.apply(val);
            if (Double.isNaN(result) || Double.isInfinite(result)) {
                throw new ElasticsearchException("Result of field modification [" + modifier.toString() + "(" + val + ")] must be a number");
            }
            return result;
        }

        @Override
        public Explanation explainScore(int docId, Explanation subQueryScore) {
            String modifierStr = modifier != null ? modifier.toString() : "";
            String defaultStr = missing != null ? "?:" + missing : "";
            double score = score(docId, subQueryScore.getValue());
            return Explanation.match(CombineFunction.toFloat(score), String.format(Locale.ROOT, "field value function: %s(doc['%s'].value%s * factor=%s)", modifierStr, field, defaultStr, boostFactor));
        }
    };
}
Also used : Explanation(org.apache.lucene.search.Explanation) ElasticsearchException(org.elasticsearch.ElasticsearchException) SortedNumericDoubleValues(org.elasticsearch.index.fielddata.SortedNumericDoubleValues)

Aggregations

Explanation (org.apache.lucene.search.Explanation)66 TermQuery (org.apache.lucene.search.TermQuery)15 Query (org.apache.lucene.search.Query)14 IndexSearcher (org.apache.lucene.search.IndexSearcher)13 ArrayList (java.util.ArrayList)12 Term (org.apache.lucene.index.Term)10 IOException (java.io.IOException)8 BooleanQuery (org.apache.lucene.search.BooleanQuery)8 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)8 Directory (org.apache.lucene.store.Directory)8 Document (org.apache.lucene.document.Document)7 IndexReader (org.apache.lucene.index.IndexReader)7 TopDocs (org.apache.lucene.search.TopDocs)7 IndexWriter (org.apache.lucene.index.IndexWriter)6 DirectoryReader (org.apache.lucene.index.DirectoryReader)5 LeafReaderContext (org.apache.lucene.index.LeafReaderContext)5 Collectors (java.util.stream.Collectors)4 IntStream (java.util.stream.IntStream)4 Store (org.apache.lucene.document.Field.Store)4 FunctionValues (org.apache.lucene.queries.function.FunctionValues)4