org.apache.lucene.search.ConstantScoreQuery Java Examples
The following examples show how to use
org.apache.lucene.search.ConstantScoreQuery.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomFieldQuery.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override void flatten(Query sourceQuery, IndexReader reader, Collection<Query> flatQueries, float boost) throws IOException { if (sourceQuery instanceof SpanTermQuery) { super.flatten(new TermQuery(((SpanTermQuery) sourceQuery).getTerm()), reader, flatQueries, boost); } else if (sourceQuery instanceof ConstantScoreQuery) { flatten(((ConstantScoreQuery) sourceQuery).getQuery(), reader, flatQueries, boost); } else if (sourceQuery instanceof FunctionScoreQuery) { flatten(((FunctionScoreQuery) sourceQuery).getSubQuery(), reader, flatQueries, boost); } else if (sourceQuery instanceof MultiPhrasePrefixQuery) { flatten(sourceQuery.rewrite(reader), reader, flatQueries, boost); } else if (sourceQuery instanceof FiltersFunctionScoreQuery) { flatten(((FiltersFunctionScoreQuery) sourceQuery).getSubQuery(), reader, flatQueries, boost); } else if (sourceQuery instanceof MultiPhraseQuery) { MultiPhraseQuery q = ((MultiPhraseQuery) sourceQuery); convertMultiPhraseQuery(0, new int[q.getTermArrays().size()], q, q.getTermArrays(), q.getPositions(), reader, flatQueries); } else if (sourceQuery instanceof BlendedTermQuery) { final BlendedTermQuery blendedTermQuery = (BlendedTermQuery) sourceQuery; flatten(blendedTermQuery.rewrite(reader), reader, flatQueries, boost); } else { super.flatten(sourceQuery, reader, flatQueries, boost); } }
Example #2
Source File: HashQParserPlugin.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException { SolrIndexSearcher solrIndexSearcher = (SolrIndexSearcher)searcher; IndexReaderContext context = solrIndexSearcher.getTopReaderContext(); List<LeafReaderContext> leaves = context.leaves(); FixedBitSet[] fixedBitSets = new FixedBitSet[leaves.size()]; for(LeafReaderContext leaf : leaves) { try { SegmentPartitioner segmentPartitioner = new SegmentPartitioner(leaf,worker,workers, keys, solrIndexSearcher); segmentPartitioner.run(); fixedBitSets[segmentPartitioner.context.ord] = segmentPartitioner.docs; } catch(Exception e) { throw new IOException(e); } } ConstantScoreQuery constantScoreQuery = new ConstantScoreQuery(new BitsFilter(fixedBitSets)); return searcher.rewrite(constantScoreQuery).createWeight(searcher, ScoreMode.COMPLETE_NO_SCORES, boost); }
Example #3
Source File: QueryUtils.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Combines a scoring query with a non-scoring (filter) query. * If both parameters are null then return a {@link MatchAllDocsQuery}. * If only {@code scoreQuery} is present then return it. * If only {@code filterQuery} is present then return it wrapped with constant scoring. * If neither are null then we combine with a BooleanQuery. */ public static Query combineQueryAndFilter(Query scoreQuery, Query filterQuery) { // check for *:* is simple and avoids needless BooleanQuery wrapper even though BQ.rewrite optimizes this away if (scoreQuery == null || scoreQuery instanceof MatchAllDocsQuery) { if (filterQuery == null) { return new MatchAllDocsQuery(); // default if nothing -- match everything } else { return new ConstantScoreQuery(filterQuery); } } else { if (filterQuery == null || filterQuery instanceof MatchAllDocsQuery) { return scoreQuery; } else { return new BooleanQuery.Builder() .add(scoreQuery, Occur.MUST) .add(filterQuery, Occur.FILTER) .build(); } } }
Example #4
Source File: TestMinHashQParser.java From lucene-solr with Apache License 2.0 | 6 votes |
@Test public void testBandsWrap() throws SyntaxError { NamedList<Object> par = new NamedList<>(); par.add("sim", "0.8"); par.add("tp", "0.694"); par.add("sep", ","); par.add("debug", "false"); QParser qparser = h.getCore().getQueryPlugin("minhash").createParser("1, 2, 3, 4, 5, 6, 7, 8, 9, 10", SolrParams.toSolrParams(par), null, null); Query query = qparser.getQuery(); BooleanQuery bq = (BooleanQuery)query; assertEquals(4, bq.clauses().size()); for(BooleanClause clause : bq.clauses()) { assertEquals(3, ((BooleanQuery)((ConstantScoreQuery)clause.getQuery()).getQuery()) .clauses().size()); } }
Example #5
Source File: BBoxStrategy.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override public Query makeQuery(SpatialArgs args) { Shape shape = args.getShape(); if (!(shape instanceof Rectangle)) throw new UnsupportedOperationException("Can only query by Rectangle, not " + shape); Rectangle bbox = (Rectangle) shape; Query spatial; // Useful for understanding Relations: // http://edndoc.esri.com/arcsde/9.1/general_topics/understand_spatial_relations.htm SpatialOperation op = args.getOperation(); if( op == SpatialOperation.BBoxIntersects ) spatial = makeIntersects(bbox); else if( op == SpatialOperation.BBoxWithin ) spatial = makeWithin(bbox); else if( op == SpatialOperation.Contains ) spatial = makeContains(bbox); else if( op == SpatialOperation.Intersects ) spatial = makeIntersects(bbox); else if( op == SpatialOperation.IsEqualTo ) spatial = makeEquals(bbox); else if( op == SpatialOperation.IsDisjointTo ) spatial = makeDisjoint(bbox); else if( op == SpatialOperation.IsWithin ) spatial = makeWithin(bbox); else { //no Overlaps support yet throw new UnsupportedSpatialOperation(op); } return new ConstantScoreQuery(spatial); }
Example #6
Source File: FuzzyLikeThisQuery.java From lucene-solr with Apache License 2.0 | 6 votes |
private Query newTermQuery(IndexReader reader, Term term) throws IOException { if (ignoreTF) { return new ConstantScoreQuery(new TermQuery(term)); } else { // we build an artificial TermStates that will give an overall df and ttf // equal to 1 TermStates context = new TermStates(reader.getContext()); for (LeafReaderContext leafContext : reader.leaves()) { Terms terms = leafContext.reader().terms(term.field()); if (terms != null) { TermsEnum termsEnum = terms.iterator(); if (termsEnum.seekExact(term.bytes())) { int freq = 1 - context.docFreq(); // we want the total df and ttf to be 1 context.register(termsEnum.termState(), leafContext.ord, freq, freq); } } } return new TermQuery(term, context); } }
Example #7
Source File: ToParentBlockJoinQuery.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override public Weight createWeight(IndexSearcher searcher, org.apache.lucene.search.ScoreMode weightScoreMode, float boost) throws IOException { ScoreMode childScoreMode = weightScoreMode.needsScores() ? scoreMode : ScoreMode.None; final Weight childWeight; if (childScoreMode == ScoreMode.None) { // we don't need to compute a score for the child query so we wrap // it under a constant score query that can early terminate if the // minimum score is greater than 0 and the total hits that match the // query is not requested. childWeight = searcher.rewrite(new ConstantScoreQuery(childQuery)).createWeight(searcher, weightScoreMode, 0f); } else { // if the score is needed we force the collection mode to COMPLETE because the child query cannot skip // non-competitive documents. childWeight = childQuery.createWeight(searcher, weightScoreMode.needsScores() ? COMPLETE : weightScoreMode, boost); } return new BlockJoinWeight(this, childWeight, parentsFilter, childScoreMode); }
Example #8
Source File: HighlighterTest.java From lucene-solr with Apache License 2.0 | 6 votes |
public void testGetBestFragmentsConstantScore() throws Exception { TestHighlightRunner helper = new TestHighlightRunner() { @Override public void run() throws Exception { numHighlights = 0; if (random().nextBoolean()) { BooleanQuery.Builder bq = new BooleanQuery.Builder(); bq.add(new ConstantScoreQuery(new TermQuery( new Term(FIELD_NAME, "kennedy"))), Occur.MUST); bq.add(new ConstantScoreQuery(new TermQuery(new Term(FIELD_NAME, "kennedy"))), Occur.MUST); doSearching(bq.build()); } else { doSearching(new ConstantScoreQuery(new TermQuery(new Term(FIELD_NAME, "kennedy")))); } doStandardHighlights(analyzer, searcher, hits, query, HighlighterTest.this); assertTrue("Failed to find correct number of highlights " + numHighlights + " found", numHighlights == 4); } }; helper.start(); }
Example #9
Source File: BBoxStrategy.java From lucene-solr with Apache License 2.0 | 6 votes |
@Override public Query makeQuery(SpatialArgs args) { Shape shape = args.getShape(); if (!(shape instanceof Rectangle)) throw new UnsupportedOperationException("Can only query by Rectangle, not " + shape); Rectangle bbox = (Rectangle) shape; Query spatial; // Useful for understanding Relations: // http://edndoc.esri.com/arcsde/9.1/general_topics/understand_spatial_relations.htm SpatialOperation op = args.getOperation(); if( op == SpatialOperation.BBoxIntersects ) spatial = makeIntersects(bbox); else if( op == SpatialOperation.BBoxWithin ) spatial = makeWithin(bbox); else if( op == SpatialOperation.Contains ) spatial = makeContains(bbox); else if( op == SpatialOperation.Intersects ) spatial = makeIntersects(bbox); else if( op == SpatialOperation.IsEqualTo ) spatial = makeEquals(bbox); else if( op == SpatialOperation.IsDisjointTo ) spatial = makeDisjoint(bbox); else if( op == SpatialOperation.IsWithin ) spatial = makeWithin(bbox); else { //no Overlaps support yet throw new UnsupportedSpatialOperation(op); } return new ConstantScoreQuery(spatial); }
Example #10
Source File: TestConstantScoreQueryExtractor.java From solr-redis with Apache License 2.0 | 5 votes |
@Test public void testExtractWrappedQuery() { Query q1 = mock(Query.class); ConstantScoreQueryExtractor constantScoreQueryExtractor = new ConstantScoreQueryExtractor(); ConstantScoreQuery constantScoreQuery = new ConstantScoreQuery(q1); List<Query> extractedQueries = new ArrayList<>(); constantScoreQueryExtractor.extract(constantScoreQuery, DEFAULT_EXTRACTORS, extractedQueries); assertEquals(1, extractedQueries.size()); assertEquals(q1, extractedQueries.get(0)); }
Example #11
Source File: TestSolrQueryParser.java From lucene-solr with Apache License 2.0 | 5 votes |
@Test public void testCSQ() throws Exception { SolrQueryRequest req = req(); QParser qParser = QParser.getParser("text:x^=3", req); Query q = qParser.getQuery(); assertTrue(q instanceof BoostQuery); assertTrue(((BoostQuery) q).getQuery() instanceof ConstantScoreQuery); assertEquals(3.0, ((BoostQuery) q).getBoost(), 0.0f); req.close(); }
Example #12
Source File: ConstantScoreQueryExtractor.java From solr-redis with Apache License 2.0 | 5 votes |
@Override public void extract(final ConstantScoreQuery q, final Iterable<QueryExtractor<? extends Query>> extractors, final List<Query> extractedQueries) throws UnsupportedOperationException { if (q.getQuery() != null) { extractQuery(q.getQuery(), extractors, extractedQueries); } else { extractedQueries.add(q); } }
Example #13
Source File: ConstantScoreQueryExtractor.java From solr-redis with Apache License 2.0 | 5 votes |
@Override public void extractSubQueriesFields(final ConstantScoreQuery q, final Iterable<QueryExtractor<? extends Query>> extractors, final Set<String> extractedFields) throws UnsupportedOperationException { if (q.getQuery() != null) { extractFields(q.getQuery(), extractors, extractedFields); } }
Example #14
Source File: NumericFieldType.java From lucene-solr with Apache License 2.0 | 5 votes |
/** * Override the default existence behavior, so that the non-docValued/norms implementation matches NaN values for double and float fields. * The [* TO *] query for those fields does not match 'NaN' values, so they must be matched separately. * <p> * For doubles and floats the query behavior is equivalent to (field:[* TO *] OR field:NaN). * For all other numeric types, the default existence query behavior is used. */ @Override public Query getSpecializedExistenceQuery(QParser parser, SchemaField field) { if (doubleOrFloat.contains(getNumberType())) { return new ConstantScoreQuery(new BooleanQuery.Builder() .add(getSpecializedRangeQuery(parser, field, null, null, true, true), BooleanClause.Occur.SHOULD) .add(getFieldQuery(parser, field, Float.toString(Float.NaN)), BooleanClause.Occur.SHOULD) .setMinimumNumberShouldMatch(1).build()); } else { return super.getSpecializedExistenceQuery(parser, field); } }
Example #15
Source File: TestConstantScoreQueryExtractor.java From solr-redis with Apache License 2.0 | 5 votes |
@Test public void testExtractSubqueryField() { Query q1 = new TermQuery(new Term("field1", "value1")); ConstantScoreQueryExtractor constantScoreQueryExtractor = new ConstantScoreQueryExtractor(); ConstantScoreQuery constantScoreQuery = new ConstantScoreQuery(q1); Set<String> extractedFieldNames = new HashSet<>(); constantScoreQueryExtractor.extractSubQueriesFields(constantScoreQuery, DEFAULT_EXTRACTORS, extractedFieldNames); assertEquals(1, extractedFieldNames.size()); assertTrue(extractedFieldNames.contains("field1")); }
Example #16
Source File: TestRedisQParser.java From solr-redis with Apache License 2.0 | 5 votes |
private static Set<Term> extractTerms(IndexSearcher searcher, Query query) throws IOException { final Set<Term> terms = new HashSet<>(); Query rewrittenQuery = searcher.rewrite(query); if (rewrittenQuery instanceof ConstantScoreQuery) { ConstantScoreQuery constantScoreQuery = (ConstantScoreQuery)rewrittenQuery; rewrittenQuery = constantScoreQuery.getQuery(); } searcher.createNormalizedWeight(rewrittenQuery, true).extractTerms(terms); return terms; }
Example #17
Source File: QueryTransformer.java From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 | 5 votes |
@Override public Query handle(Query query, QueryTransformer queryTransformer) { ConstantScoreQuery constantScoreQuery = (ConstantScoreQuery) query; Query newInnerConstantScoreQuery = queryTransformer.transform(constantScoreQuery.getQuery()); if (newInnerConstantScoreQuery != constantScoreQuery.getQuery()) { return new ConstantScoreQuery(newInnerConstantScoreQuery); } return query; }
Example #18
Source File: ProfileScorer.java From crate with Apache License 2.0 | 5 votes |
ProfileScorer(ProfileWeight w, Scorer scorer, QueryProfileBreakdown profile) throws IOException { super(w); this.scorer = scorer; this.profileWeight = w; scoreTimer = profile.getTimer(QueryTimingType.SCORE); nextDocTimer = profile.getTimer(QueryTimingType.NEXT_DOC); advanceTimer = profile.getTimer(QueryTimingType.ADVANCE); matchTimer = profile.getTimer(QueryTimingType.MATCH); shallowAdvanceTimer = profile.getTimer(QueryTimingType.SHALLOW_ADVANCE); computeMaxScoreTimer = profile.getTimer(QueryTimingType.COMPUTE_MAX_SCORE); ProfileScorer profileScorer = null; if (w.getQuery() instanceof ConstantScoreQuery && scorer instanceof ProfileScorer) { //Case when we have a totalHits query and it is not cached profileScorer = (ProfileScorer) scorer; } else if (w.getQuery() instanceof ConstantScoreQuery && scorer.getChildren().size() == 1) { //Case when we have a top N query. If the scorer has no children, it is because it is cached //and in that case we do not do any special treatment Scorable childScorer = scorer.getChildren().iterator().next().child; if (childScorer instanceof ProfileScorer) { profileScorer = (ProfileScorer) childScorer; } } if (profileScorer != null) { isConstantScoreQuery = true; profile.setTimer(QueryTimingType.NEXT_DOC, profileScorer.nextDocTimer); profile.setTimer(QueryTimingType.ADVANCE, profileScorer.advanceTimer); profile.setTimer(QueryTimingType.MATCH, profileScorer.matchTimer); } else { isConstantScoreQuery = false; } }
Example #19
Source File: ExistsQueryBuilder.java From crate with Apache License 2.0 | 5 votes |
private static Query newFieldExistsQuery(QueryShardContext context, String field) { MappedFieldType fieldType = context.getMapperService().fullName(field); if (fieldType == null) { // The field does not exist as a leaf but could be an object so // check for an object mapper if (context.getObjectMapper(field) != null) { return newObjectFieldExistsQuery(context, field); } return Queries.newMatchNoDocsQuery("No field \"" + field + "\" exists in mappings."); } Query filter = fieldType.existsQuery(context); return new ConstantScoreQuery(filter); }
Example #20
Source File: ExistsQueryBuilder.java From crate with Apache License 2.0 | 5 votes |
private static Query newObjectFieldExistsQuery(QueryShardContext context, String objField) { BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder(); Collection<String> fields = context.simpleMatchToIndexNames(objField + ".*"); for (String field : fields) { Query existsQuery = context.getMapperService().fullName(field).existsQuery(context); booleanQuery.add(existsQuery, Occur.SHOULD); } return new ConstantScoreQuery(booleanQuery.build()); }
Example #21
Source File: TextFieldMapper.java From crate with Apache License 2.0 | 5 votes |
@Override public Query prefixQuery(String value, MultiTermQuery.RewriteMethod method, QueryShardContext context) { if (prefixFieldType == null || prefixFieldType.accept(value.length()) == false) { return super.prefixQuery(value, method, context); } Query tq = prefixFieldType.termQuery(value, context); if (method == null || method == MultiTermQuery.CONSTANT_SCORE_REWRITE || method == MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE) { return new ConstantScoreQuery(tq); } return tq; }
Example #22
Source File: MappedFieldType.java From crate with Apache License 2.0 | 5 votes |
/** Build a constant-scoring query that matches all values. The default implementation uses a * {@link ConstantScoreQuery} around a {@link BooleanQuery} whose {@link Occur#SHOULD} clauses * are generated with {@link #termQuery}. */ public Query termsQuery(List<?> values, @Nullable QueryShardContext context) { BooleanQuery.Builder builder = new BooleanQuery.Builder(); for (Object value : values) { builder.add(termQuery(value, context), Occur.SHOULD); } return new ConstantScoreQuery(builder.build()); }
Example #23
Source File: CommonQueryBuilderTest.java From crate with Apache License 2.0 | 5 votes |
/** * Make sure we still sport the fast Lucene regular * expression engine when not using PCRE features. */ @Test public void testRegexQueryFast() throws Exception { Query query = convert("name ~ '[a-z]'"); assertThat(query, instanceOf(ConstantScoreQuery.class)); ConstantScoreQuery scoreQuery = (ConstantScoreQuery) query; assertThat(scoreQuery.getQuery(), instanceOf(RegexpQuery.class)); }
Example #24
Source File: CommonQueryBuilderTest.java From crate with Apache License 2.0 | 5 votes |
@Test public void testGeoShapeMatchDisJoint() throws Exception { Query query = convert("match(shape, 'POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))') using disjoint"); assertThat(query, instanceOf(ConstantScoreQuery.class)); Query booleanQuery = ((ConstantScoreQuery) query).getQuery(); assertThat(booleanQuery, instanceOf(BooleanQuery.class)); BooleanClause existsClause = ((BooleanQuery) booleanQuery).clauses().get(0); BooleanClause intersectsClause = ((BooleanQuery) booleanQuery).clauses().get(1); assertThat(existsClause.getQuery(), instanceOf(TermRangeQuery.class)); assertThat(intersectsClause.getQuery(), instanceOf(IntersectsPrefixTreeQuery.class)); }
Example #25
Source File: FilterQuery.java From lucene-solr with Apache License 2.0 | 5 votes |
@Override public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException { // SolrRequestInfo reqInfo = SolrRequestInfo.getRequestInfo(); if (!(searcher instanceof SolrIndexSearcher)) { // delete-by-query won't have SolrIndexSearcher return new BoostQuery(new ConstantScoreQuery(q), 0).createWeight(searcher, scoreMode, 1f); } SolrIndexSearcher solrSearcher = (SolrIndexSearcher)searcher; DocSet docs = solrSearcher.getDocSet(q); // reqInfo.addCloseHook(docs); // needed for off-heap refcounting return new BoostQuery(new SolrConstantScoreQuery(docs.getTopFilter()), 0).createWeight(searcher, scoreMode, 1f); }
Example #26
Source File: DefaultSearchContext.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public Query searchFilter(String[] types) { Query filter = mapperService().searchFilter(types); if (filter == null && aliasFilter == null) { return null; } BooleanQuery.Builder bq = new BooleanQuery.Builder(); if (filter != null) { bq.add(filter, Occur.MUST); } if (aliasFilter != null) { bq.add(aliasFilter, Occur.MUST); } return new ConstantScoreQuery(bq.build()); }
Example #27
Source File: IndexedGeoBoundingBoxQuery.java From Elasticsearch with Apache License 2.0 | 5 votes |
private static Query westGeoBoundingBoxFilter(GeoPoint topLeft, GeoPoint bottomRight, GeoPointFieldMapperLegacy.GeoPointFieldType fieldType) { BooleanQuery.Builder filter = new BooleanQuery.Builder(); filter.setMinimumNumberShouldMatch(1); filter.add(fieldType.lonFieldType().rangeQuery(null, bottomRight.lon(), true, true), Occur.SHOULD); filter.add(fieldType.lonFieldType().rangeQuery(topLeft.lon(), null, true, true), Occur.SHOULD); filter.add(fieldType.latFieldType().rangeQuery(bottomRight.lat(), topLeft.lat(), true, true), Occur.MUST); return new ConstantScoreQuery(filter.build()); }
Example #28
Source File: TypeFieldMapper.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public Query termQuery(Object value, @Nullable QueryParseContext context) { if (indexOptions() == IndexOptions.NONE) { return new ConstantScoreQuery(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value))))); } return new ConstantScoreQuery(new TermQuery(createTerm(value))); }
Example #29
Source File: SolrDenySetQuery.java From SearchServices with GNU Lesser General Public License v3.0 | 5 votes |
@Override public Weight createWeight(IndexSearcher searcher, boolean requiresScore) throws IOException { if(!(searcher instanceof SolrIndexSearcher)) { throw new IllegalStateException("Must have a SolrIndexSearcher"); } String[] auths = authorities.substring(1).split(authorities.substring(0, 1)); BitsFilter denyFilter = getACLFilter(auths, QueryConstants.FIELD_DENIED, (SolrIndexSearcher) searcher); return new ConstantScoreQuery(denyFilter).createWeight(searcher, false); }
Example #30
Source File: SolrOwnerQuery.java From SearchServices with GNU Lesser General Public License v3.0 | 5 votes |
@Override public Weight createWeight(IndexSearcher searcher, boolean needsScore) throws IOException { if(!(searcher instanceof SolrIndexSearcher)) { throw new IllegalStateException("Must have a SolrIndexSearcher"); } BitsFilter ownerFilter = getOwnerFilter(authority, (SolrIndexSearcher)searcher); return new ConstantScoreQuery(ownerFilter).createWeight(searcher, false); }