Java 类org.apache.lucene.search.MatchNoDocsQuery 实例源码

项目:elasticsearch_my    文件:ParentIdQueryBuilder.java   
@Override
protected Query doToQuery(QueryShardContext context) throws IOException {
    DocumentMapper childDocMapper = context.getMapperService().documentMapper(type);
    if (childDocMapper == null) {
        if (ignoreUnmapped) {
            return new MatchNoDocsQuery();
        } else {
            throw new QueryShardException(context, "[" + NAME + "] no mapping found for type [" + type + "]");
        }
    }
    ParentFieldMapper parentFieldMapper = childDocMapper.parentFieldMapper();
    if (parentFieldMapper.active() == false) {
        throw new QueryShardException(context, "[" + NAME + "] _parent field has no parent type configured");
    }
    String fieldName = ParentFieldMapper.joinField(parentFieldMapper.type());

    BooleanQuery.Builder query = new BooleanQuery.Builder();
    query.add(new DocValuesTermsQuery(fieldName, id), BooleanClause.Occur.MUST);
    // Need to take child type into account, otherwise a child doc of different type with the same id could match
    query.add(new TermQuery(new Term(TypeFieldMapper.NAME, type)), BooleanClause.Occur.FILTER);
    return query.build();
}
项目:elasticsearch_my    文件:SeqNoFieldMapper.java   
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower,
                        boolean includeUpper, QueryShardContext context) {
    long l = Long.MIN_VALUE;
    long u = Long.MAX_VALUE;
    if (lowerTerm != null) {
        l = parse(lowerTerm);
        if (includeLower == false) {
            if (l == Long.MAX_VALUE) {
                return new MatchNoDocsQuery();
            }
            ++l;
        }
    }
    if (upperTerm != null) {
        u = parse(upperTerm);
        if (includeUpper == false) {
            if (u == Long.MIN_VALUE) {
                return new MatchNoDocsQuery();
            }
            --u;
        }
    }
    return LongPoint.newRangeQuery(name(), l, u);
}
项目:elasticsearch_my    文件:QueryPhaseTests.java   
public void testPostFilterDisablesCountOptimization() throws Exception {
    TestSearchContext context = new TestSearchContext(null);
    context.parsedQuery(new ParsedQuery(new MatchAllDocsQuery()));
    context.setSize(0);
    context.setTask(new SearchTask(123L, "", "", "", null));

    final AtomicBoolean collected = new AtomicBoolean();
    IndexSearcher contextSearcher = new IndexSearcher(new MultiReader()) {
        protected void search(List<LeafReaderContext> leaves, Weight weight, Collector collector) throws IOException {
            collected.set(true);
            super.search(leaves, weight, collector);
        }
    };

    QueryPhase.execute(context, contextSearcher);
    assertEquals(0, context.queryResult().topDocs().totalHits);
    assertFalse(collected.get());

    context.parsedPostFilter(new ParsedQuery(new MatchNoDocsQuery()));
    QueryPhase.execute(context, contextSearcher);
    assertEquals(0, context.queryResult().topDocs().totalHits);
    assertTrue(collected.get());
}
项目:elasticsearch_my    文件:GeoBoundingBoxQueryBuilderTests.java   
@Override
protected void doAssertLuceneQuery(GeoBoundingBoxQueryBuilder queryBuilder, Query query, SearchContext searchContext)
    throws IOException {
    QueryShardContext context = searchContext.getQueryShardContext();
    MappedFieldType fieldType = context.fieldMapper(queryBuilder.fieldName());
    if (fieldType == null) {
        assertTrue("Found no indexed geo query.", query instanceof MatchNoDocsQuery);
    } else if (query instanceof IndexOrDocValuesQuery) { // TODO: remove the if statement once we always use LatLonPoint
        Query indexQuery = ((IndexOrDocValuesQuery) query).getIndexQuery();
        assertEquals(LatLonPoint.newBoxQuery(queryBuilder.fieldName(),
                queryBuilder.bottomRight().lat(),
                queryBuilder.topLeft().lat(),
                queryBuilder.topLeft().lon(),
                queryBuilder.bottomRight().lon()), indexQuery);
        Query dvQuery = ((IndexOrDocValuesQuery) query).getRandomAccessQuery();
        assertEquals(LatLonDocValuesField.newBoxQuery(queryBuilder.fieldName(),
                queryBuilder.bottomRight().lat(),
                queryBuilder.topLeft().lat(),
                queryBuilder.topLeft().lon(),
                queryBuilder.bottomRight().lon()), dvQuery);
    }
}
项目:resource-query-parser    文件:QueryParserTestBase.java   
@Test
public void testStopwords() throws Exception {
    CharacterRunAutomaton stopSet = new CharacterRunAutomaton(new RegExp("the|foo").toAutomaton());
    QueryParser qp = getParserConfig(new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, stopSet));
    Query result = getQuery("field:the OR field:foo", qp);
    Assert.assertNotNull("result is null and it shouldn't be", result);
    Assert.assertTrue("result is not a BooleanQuery",
            result instanceof BooleanQuery || result instanceof MatchNoDocsQuery);
    if (result instanceof BooleanQuery) {
        Assert.assertEquals(0, ((BooleanQuery) result).clauses().size());
    }
    result = getQuery("field:woo OR field:the", qp);
    Assert.assertNotNull("result is null and it shouldn't be", result);
    Assert.assertTrue("result is not a TermQuery", result instanceof TermQuery);
    result = getQuery("(fieldX:xxxxx OR fieldy:xxxxxxxx)^2 AND (fieldx:the OR fieldy:foo)", qp);
    Assert.assertNotNull("result is null and it shouldn't be", result);
    Assert.assertTrue("result is not a BoostQuery", result instanceof BoostQuery);
    result = ((BoostQuery) result).getQuery();
    Assert.assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
    if (VERBOSE)
        System.out.println("Result: " + result);
    Assert.assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: " + 2,
            ((BooleanQuery) result).clauses().size() == 2);
}
项目:lucene-addons    文件:QueryParserTestBase.java   
public void testStopwords() throws Exception {
  CharacterRunAutomaton stopSet = new CharacterRunAutomaton(new RegExp("the|foo").toAutomaton());
  CommonQueryParserConfiguration qp = getParserConfig(new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, stopSet));
  Query result = getQuery("field:the OR field:foo",qp);
  assertNotNull("result is null and it shouldn't be", result);
  System.out.println(result.getClass());
  assertTrue("result is not a BooleanQuery", result instanceof SpanOrQuery || result instanceof BooleanQuery || result instanceof MatchNoDocsQuery);
  if (result instanceof BooleanQuery) {
    assertEquals(0, ((BooleanQuery) result).clauses().size());
  }
  result = getQuery("field:woo OR field:the",qp);
  assertNotNull("result is null and it shouldn't be", result);
  assertTrue("result is not a TermQuery", result instanceof TermQuery);
  result = getQuery("(fieldX:xxxxx OR fieldy:xxxxxxxx)^2 AND (fieldx:the OR fieldy:foo)",qp);
  assertNotNull("result is null and it shouldn't be", result);
  assertTrue("result is not a BoostQuery", result instanceof BoostQuery);
  result = ((BoostQuery) result).getQuery();
  assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
  if (VERBOSE) System.out.println("Result: " + result);
  assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: " + 2, ((BooleanQuery) result).clauses().size() == 2);
}
项目:elasticsearch_my    文件:QueryAnalyzerTests.java   
public void testExtractQueryMetadata_matchNoDocsQuery() {
    Result result = analyze(new MatchNoDocsQuery("sometimes there is no reason at all"));
    assertThat(result.verified, is(true));
    assertEquals(0, result.terms.size());

    BooleanQuery.Builder bq = new BooleanQuery.Builder();
    bq.add(new TermQuery(new Term("field", "value")), BooleanClause.Occur.MUST);
    bq.add(new MatchNoDocsQuery("sometimes there is no reason at all"), BooleanClause.Occur.MUST);
    result = analyze(bq.build());
    assertThat(result.verified, is(false));
    assertEquals(0, result.terms.size());

    bq = new BooleanQuery.Builder();
    bq.add(new TermQuery(new Term("field", "value")), BooleanClause.Occur.SHOULD);
    bq.add(new MatchNoDocsQuery("sometimes there is no reason at all"), BooleanClause.Occur.SHOULD);
    result = analyze(bq.build());
    assertThat(result.verified, is(true));
    assertTermsEqual(result.terms, new Term("field", "value"));

    DisjunctionMaxQuery disjunctionMaxQuery = new DisjunctionMaxQuery(
            Arrays.asList(new TermQuery(new Term("field", "value")), new MatchNoDocsQuery("sometimes there is no reason at all")),
            1f
    );
    result = analyze(disjunctionMaxQuery);
    assertThat(result.verified, is(true));
    assertTermsEqual(result.terms, new Term("field", "value"));
}
项目:elasticsearch_my    文件:MapperQueryParser.java   
@Override
public Query parse(String query) throws ParseException {
    if (query.trim().isEmpty()) {
        // if the query string is empty we return no docs / empty result
        // the behavior is simple to change in the client if all docs is required
        // or a default query
        return new MatchNoDocsQuery();
    }
    return super.parse(query);
}
项目:elasticsearch_my    文件:NestedQueryBuilder.java   
@Override
protected Query doToQuery(QueryShardContext context) throws IOException {
    ObjectMapper nestedObjectMapper = context.getObjectMapper(path);
    if (nestedObjectMapper == null) {
        if (ignoreUnmapped) {
            return new MatchNoDocsQuery();
        } else {
            throw new IllegalStateException("[" + NAME + "] failed to find nested object under path [" + path + "]");
        }
    }
    if (!nestedObjectMapper.nested().isNested()) {
        throw new IllegalStateException("[" + NAME + "] nested object under path [" + path + "] is not of nested type");
    }
    final BitSetProducer parentFilter;
    Query innerQuery;
    ObjectMapper objectMapper = context.nestedScope().getObjectMapper();
    if (objectMapper == null) {
        parentFilter = context.bitsetFilter(Queries.newNonNestedFilter());
    } else {
        parentFilter = context.bitsetFilter(objectMapper.nestedTypeFilter());
    }

    try {
        context.nestedScope().nextLevel(nestedObjectMapper);
        innerQuery = this.query.toQuery(context);
    } finally {
        context.nestedScope().previousLevel();
    }

    // ToParentBlockJoinQuery requires that the inner query only matches documents
    // in its child space
    if (new NestedHelper(context.getMapperService()).mightMatchNonNestedDocs(innerQuery, path)) {
        innerQuery = Queries.filtered(innerQuery, nestedObjectMapper.nestedTypeFilter());
    }

    return new ESToParentBlockJoinQuery(innerQuery, parentFilter, scoreMode,
            objectMapper == null ? null : objectMapper.fullPath());
}
项目:elasticsearch_my    文件:HasChildQueryBuilder.java   
@Override
protected Query doToQuery(QueryShardContext context) throws IOException {
    Query innerQuery;
    final String[] previousTypes = context.getTypes();
    context.setTypes(type);
    try {
        innerQuery = query.toQuery(context);
    } finally {
        context.setTypes(previousTypes);
    }

    DocumentMapper childDocMapper = context.documentMapper(type);
    if (childDocMapper == null) {
        if (ignoreUnmapped) {
            return new MatchNoDocsQuery();
        } else {
            throw new QueryShardException(context, "[" + NAME + "] no mapping found for type [" + type + "]");
        }
    }
    ParentFieldMapper parentFieldMapper = childDocMapper.parentFieldMapper();
    if (parentFieldMapper.active() == false) {
        throw new QueryShardException(context, "[" + NAME + "] _parent field has no parent type configured");
    }
    String parentType = parentFieldMapper.type();
    DocumentMapper parentDocMapper = context.getMapperService().documentMapper(parentType);
    if (parentDocMapper == null) {
        throw new QueryShardException(context,
                "[" + NAME + "] Type [" + type + "] points to a non existent parent type [" + parentType + "]");
    }

    // wrap the query with type query
    innerQuery = Queries.filtered(innerQuery, childDocMapper.typeFilter());

    final ParentChildIndexFieldData parentChildIndexFieldData = context.getForField(parentFieldMapper.fieldType());
    return new LateParsingQuery(parentDocMapper.typeFilter(), innerQuery, minChildren(), maxChildren(),
                                parentType, scoreMode, parentChildIndexFieldData, context.getSearchSimilarity());
}
项目:elasticsearch_my    文件:HasChildQueryBuilder.java   
@Override
public Query rewrite(IndexReader reader) throws IOException {
    Query rewritten = super.rewrite(reader);
    if (rewritten != this) {
        return rewritten;
    }
    if (reader instanceof DirectoryReader) {
        String joinField = ParentFieldMapper.joinField(parentType);
        IndexSearcher indexSearcher = new IndexSearcher(reader);
        indexSearcher.setQueryCache(null);
        indexSearcher.setSimilarity(similarity);
        IndexParentChildFieldData indexParentChildFieldData = parentChildIndexFieldData.loadGlobal((DirectoryReader) reader);
        MultiDocValues.OrdinalMap ordinalMap = ParentChildIndexFieldData.getOrdinalMap(indexParentChildFieldData, parentType);
        return JoinUtil.createJoinQuery(joinField, innerQuery, toQuery, indexSearcher, scoreMode,
                ordinalMap, minChildren, maxChildren);
    } else {
        if (reader.leaves().isEmpty() && reader.numDocs() == 0) {
            // asserting reader passes down a MultiReader during rewrite which makes this
            // blow up since for this query to work we have to have a DirectoryReader otherwise
            // we can't load global ordinals - for this to work we simply check if the reader has no leaves
            // and rewrite to match nothing
            return new MatchNoDocsQuery();
        }
        throw new IllegalStateException("can't load global ordinals for reader of type: " +
                reader.getClass() + " must be a DirectoryReader");
    }
}
项目:elasticsearch_my    文件:GeoDistanceQueryBuilder.java   
@Override
protected Query doToQuery(QueryShardContext shardContext) throws IOException {
    MappedFieldType fieldType = shardContext.fieldMapper(fieldName);
    if (fieldType == null) {
        if (ignoreUnmapped) {
            return new MatchNoDocsQuery();
        } else {
            throw new QueryShardException(shardContext, "failed to find geo_point field [" + fieldName + "]");
        }
    }

    if (!(fieldType instanceof GeoPointFieldType)) {
        throw new QueryShardException(shardContext, "field [" + fieldName + "] is not a geo_point field");
    }

    final Version indexVersionCreated = shardContext.indexVersionCreated();
    QueryValidationException exception = checkLatLon(shardContext.indexVersionCreated().before(Version.V_2_0_0));
    if (exception != null) {
        throw new QueryShardException(shardContext, "couldn't validate latitude/ longitude values", exception);
    }

    if (indexVersionCreated.onOrAfter(Version.V_2_2_0) || GeoValidationMethod.isCoerce(validationMethod)) {
        GeoUtils.normalizePoint(center, true, true);
    }

    Query query = LatLonPoint.newDistanceQuery(fieldType.name(), center.lat(), center.lon(), this.distance);
    if (fieldType.hasDocValues()) {
        Query dvQuery = LatLonDocValuesField.newDistanceQuery(fieldType.name(), center.lat(), center.lon(), this.distance);
        query = new IndexOrDocValuesQuery(query, dvQuery);
    }
    return query;
}
项目:elasticsearch_my    文件:TypeQueryBuilder.java   
@Override
protected Query doToQuery(QueryShardContext context) throws IOException {
    //LUCENE 4 UPGRADE document mapper should use bytesref as well?
    DocumentMapper documentMapper = context.getMapperService().documentMapper(type.utf8ToString());
    if (documentMapper == null) {
        // no type means no documents
        return new MatchNoDocsQuery();
    } else {
        return documentMapper.typeFilter();
    }
}
项目:elasticsearch_my    文件:NestedHelper.java   
/** Returns true if the given query might match nested documents. */
public boolean mightMatchNestedDocs(Query query) {
    if (query instanceof ConstantScoreQuery) {
        return mightMatchNestedDocs(((ConstantScoreQuery) query).getQuery());
    } else if (query instanceof BoostQuery) {
        return mightMatchNestedDocs(((BoostQuery) query).getQuery());
    } else if (query instanceof MatchAllDocsQuery) {
        return true;
    } else if (query instanceof MatchNoDocsQuery) {
        return false;
    } else if (query instanceof TermQuery) {
        // We only handle term queries and range queries, which should already
        // cover a high majority of use-cases
        return mightMatchNestedDocs(((TermQuery) query).getTerm().field());
    } else if (query instanceof PointRangeQuery) {
        return mightMatchNestedDocs(((PointRangeQuery) query).getField());
    } else if (query instanceof IndexOrDocValuesQuery) {
        return mightMatchNestedDocs(((IndexOrDocValuesQuery) query).getIndexQuery());
    } else if (query instanceof BooleanQuery) {
        final BooleanQuery bq = (BooleanQuery) query;
        final boolean hasRequiredClauses = bq.clauses().stream().anyMatch(BooleanClause::isRequired);
        if (hasRequiredClauses) {
            return bq.clauses().stream()
                    .filter(BooleanClause::isRequired)
                    .map(BooleanClause::getQuery)
                    .allMatch(this::mightMatchNestedDocs);
        } else {
            return bq.clauses().stream()
                    .filter(c -> c.getOccur() == Occur.SHOULD)
                    .map(BooleanClause::getQuery)
                    .anyMatch(this::mightMatchNestedDocs);
        }
    } else if (query instanceof ESToParentBlockJoinQuery) {
        return ((ESToParentBlockJoinQuery) query).getPath() != null;
    } else {
        return true;
    }
}
项目:elasticsearch_my    文件:NestedHelper.java   
/** Returns true if the given query might match parent documents or documents
 *  that are nested under a different path. */
public boolean mightMatchNonNestedDocs(Query query, String nestedPath) {
    if (query instanceof ConstantScoreQuery) {
        return mightMatchNonNestedDocs(((ConstantScoreQuery) query).getQuery(), nestedPath);
    } else if (query instanceof BoostQuery) {
        return mightMatchNonNestedDocs(((BoostQuery) query).getQuery(), nestedPath);
    } else if (query instanceof MatchAllDocsQuery) {
        return true;
    } else if (query instanceof MatchNoDocsQuery) {
        return false;
    } else if (query instanceof TermQuery) {
        return mightMatchNonNestedDocs(((TermQuery) query).getTerm().field(), nestedPath);
    } else if (query instanceof PointRangeQuery) {
        return mightMatchNonNestedDocs(((PointRangeQuery) query).getField(), nestedPath);
    } else if (query instanceof IndexOrDocValuesQuery) {
        return mightMatchNonNestedDocs(((IndexOrDocValuesQuery) query).getIndexQuery(), nestedPath);
    } else if (query instanceof BooleanQuery) {
        final BooleanQuery bq = (BooleanQuery) query;
        final boolean hasRequiredClauses = bq.clauses().stream().anyMatch(BooleanClause::isRequired);
        if (hasRequiredClauses) {
            return bq.clauses().stream()
                    .filter(BooleanClause::isRequired)
                    .map(BooleanClause::getQuery)
                    .allMatch(q -> mightMatchNonNestedDocs(q, nestedPath));
        } else {
            return bq.clauses().stream()
                    .filter(c -> c.getOccur() == Occur.SHOULD)
                    .map(BooleanClause::getQuery)
                    .anyMatch(q -> mightMatchNonNestedDocs(q, nestedPath));
        }
    } else {
        return true;
    }
}
项目:elasticsearch_my    文件:NumberFieldMapper.java   
@Override
Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
                 boolean includeLower, boolean includeUpper,
                 boolean hasDocValues) {
    int l = Integer.MIN_VALUE;
    int u = Integer.MAX_VALUE;
    if (lowerTerm != null) {
        l = parse(lowerTerm, true);
        // if the lower bound is decimal:
        // - if the bound is positive then we increment it:
        //      if lowerTerm=1.5 then the (inclusive) bound becomes 2
        // - if the bound is negative then we leave it as is:
        //      if lowerTerm=-1.5 then the (inclusive) bound becomes -1 due to the call to longValue
        boolean lowerTermHasDecimalPart = hasDecimalPart(lowerTerm);
        if ((lowerTermHasDecimalPart == false && includeLower == false) ||
                (lowerTermHasDecimalPart && signum(lowerTerm) > 0)) {
            if (l == Integer.MAX_VALUE) {
                return new MatchNoDocsQuery();
            }
            ++l;
        }
    }
    if (upperTerm != null) {
        u = parse(upperTerm, true);
        boolean upperTermHasDecimalPart = hasDecimalPart(upperTerm);
        if ((upperTermHasDecimalPart == false && includeUpper == false) ||
                (upperTermHasDecimalPart && signum(upperTerm) < 0)) {
            if (u == Integer.MIN_VALUE) {
                return new MatchNoDocsQuery();
            }
            --u;
        }
    }
    Query query = IntPoint.newRangeQuery(field, l, u);
    if (hasDocValues) {
        Query dvQuery = SortedNumericDocValuesField.newRangeQuery(field, l, u);
        query = new IndexOrDocValuesQuery(query, dvQuery);
    }
    return query;
}
项目:elasticsearch_my    文件:NumberFieldMapper.java   
@Override
Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
                 boolean includeLower, boolean includeUpper,
                 boolean hasDocValues) {
    long l = Long.MIN_VALUE;
    long u = Long.MAX_VALUE;
    if (lowerTerm != null) {
        l = parse(lowerTerm, true);
        // if the lower bound is decimal:
        // - if the bound is positive then we increment it:
        //      if lowerTerm=1.5 then the (inclusive) bound becomes 2
        // - if the bound is negative then we leave it as is:
        //      if lowerTerm=-1.5 then the (inclusive) bound becomes -1 due to the call to longValue
        boolean lowerTermHasDecimalPart = hasDecimalPart(lowerTerm);
        if ((lowerTermHasDecimalPart == false && includeLower == false) ||
                (lowerTermHasDecimalPart && signum(lowerTerm) > 0)) {
            if (l == Long.MAX_VALUE) {
                return new MatchNoDocsQuery();
            }
            ++l;
        }
    }
    if (upperTerm != null) {
        u = parse(upperTerm, true);
        boolean upperTermHasDecimalPart = hasDecimalPart(upperTerm);
        if ((upperTermHasDecimalPart == false && includeUpper == false) ||
                (upperTermHasDecimalPart && signum(upperTerm) < 0)) {
            if (u == Long.MIN_VALUE) {
                return new MatchNoDocsQuery();
            }
            --u;
        }
    }
    Query query = LongPoint.newRangeQuery(field, l, u);
    if (hasDocValues) {
        Query dvQuery = SortedNumericDocValuesField.newRangeQuery(field, l, u);
        query = new IndexOrDocValuesQuery(query, dvQuery);
    }
    return query;
}
项目:elasticsearch_my    文件:IpFieldMapper.java   
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, QueryShardContext context) {
    failIfNotIndexed();
    InetAddress lower;
    if (lowerTerm == null) {
        lower = InetAddressPoint.MIN_VALUE;
    } else {
        lower = parse(lowerTerm);
        if (includeLower == false) {
            if (lower.equals(InetAddressPoint.MAX_VALUE)) {
                return new MatchNoDocsQuery();
            }
            lower = InetAddressPoint.nextUp(lower);
        }
    }

    InetAddress upper;
    if (upperTerm == null) {
        upper = InetAddressPoint.MAX_VALUE;
    } else {
        upper = parse(upperTerm);
        if (includeUpper == false) {
            if (upper.equals(InetAddressPoint.MIN_VALUE)) {
                return new MatchNoDocsQuery();
            }
            upper = InetAddressPoint.nextDown(upper);
        }
    }

    return InetAddressPoint.newRangeQuery(name(), lower, upper);
}
项目:elasticsearch_my    文件:MultiPhrasePrefixQuery.java   
@Override
public Query rewrite(IndexReader reader) throws IOException {
    Query rewritten = super.rewrite(reader);
    if (rewritten != this) {
        return rewritten;
    }
    if (termArrays.isEmpty()) {
        return new MatchNoDocsQuery();
    }
    MultiPhraseQuery.Builder query = new MultiPhraseQuery.Builder();
    query.setSlop(slop);
    int sizeMinus1 = termArrays.size() - 1;
    for (int i = 0; i < sizeMinus1; i++) {
        query.add(termArrays.get(i), positions.get(i));
    }
    Term[] suffixTerms = termArrays.get(sizeMinus1);
    int position = positions.get(sizeMinus1);
    ObjectHashSet<Term> terms = new ObjectHashSet<>();
    for (Term term : suffixTerms) {
        getPrefixTerms(terms, term, reader);
        if (terms.size() > maxExpansions) {
            break;
        }
    }
    if (terms.isEmpty()) {
        // if the terms does not exist we could return a MatchNoDocsQuery but this would break the unified highlighter
        // which rewrites query with an empty reader.
        return new BooleanQuery.Builder()
            .add(query.build(), BooleanClause.Occur.MUST)
            .add(Queries.newMatchNoDocsQuery("No terms supplied for " + MultiPhrasePrefixQuery.class.getName()),
                BooleanClause.Occur.MUST).build();
    }
    query.add(terms.toArray(Term.class), position);
    return query.build();
}
项目:elasticsearch_my    文件:TransportValidateQueryAction.java   
private String explain(SearchContext context, boolean rewritten) throws IOException {
    Query query = context.query();
    if (rewritten && query instanceof MatchNoDocsQuery) {
        return context.parsedQuery().query().toString();
    } else {
        return query.toString();
    }
}
项目:elasticsearch_my    文件:DateHistogramAggregatorTests.java   
public void testNoDocs() throws IOException {
    Query query = new MatchNoDocsQuery();
    List<String> dates = Collections.emptyList();
    Consumer<DateHistogramAggregationBuilder> aggregation = agg ->
            agg.dateHistogramInterval(DateHistogramInterval.YEAR).field(DATE_FIELD);

    testSearchCase(query, dates, aggregation,
            histogram -> assertEquals(0, histogram.getBuckets().size())
    );
    testSearchAndReduceCase(query, dates, aggregation,
            histogram -> assertNull(histogram)
    );
}
项目:elasticsearch_my    文件:HasChildQueryBuilderTests.java   
public void testIgnoreUnmapped() throws IOException {
    final HasChildQueryBuilder queryBuilder = new HasChildQueryBuilder("unmapped", new MatchAllQueryBuilder(), ScoreMode.None);
    queryBuilder.ignoreUnmapped(true);
    Query query = queryBuilder.toQuery(createShardContext());
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));

    final HasChildQueryBuilder failingQueryBuilder = new HasChildQueryBuilder("unmapped", new MatchAllQueryBuilder(), ScoreMode.None);
    failingQueryBuilder.ignoreUnmapped(false);
    QueryShardException e = expectThrows(QueryShardException.class, () -> failingQueryBuilder.toQuery(createShardContext()));
    assertThat(e.getMessage(), containsString("[" + HasChildQueryBuilder.NAME + "] no mapping found for type [unmapped]"));
}
项目:elasticsearch_my    文件:HasChildQueryBuilderTests.java   
public void testIgnoreUnmappedWithRewrite() throws IOException {
    // WrapperQueryBuilder makes sure we always rewrite
    final HasChildQueryBuilder queryBuilder
        = new HasChildQueryBuilder("unmapped", new WrapperQueryBuilder(new MatchAllQueryBuilder().toString()), ScoreMode.None);
    queryBuilder.ignoreUnmapped(true);
    QueryShardContext queryShardContext = createShardContext();
    Query query = queryBuilder.rewrite(queryShardContext).toQuery(queryShardContext);
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));
}
项目:elasticsearch_my    文件:FunctionScoreEquivalenceTests.java   
public void testMinScoreAllExcluded() throws Exception {
    Term term = randomTerm();
    Query query = new TermQuery(term);

    FunctionScoreQuery fsq = new FunctionScoreQuery(query, null, Float.POSITIVE_INFINITY, null, Float.POSITIVE_INFINITY);
    assertSameScores(new MatchNoDocsQuery(), fsq);

    FiltersFunctionScoreQuery ffsq = new FiltersFunctionScoreQuery(query, ScoreMode.SUM, new FilterFunction[0], Float.POSITIVE_INFINITY,
            Float.POSITIVE_INFINITY, CombineFunction.MULTIPLY);
    assertSameScores(new MatchNoDocsQuery(), ffsq);
}
项目:elasticsearch_my    文件:NestedQueryBuilderTests.java   
public void testIgnoreUnmapped() throws IOException {
    final NestedQueryBuilder queryBuilder = new NestedQueryBuilder("unmapped", new MatchAllQueryBuilder(), ScoreMode.None);
    queryBuilder.ignoreUnmapped(true);
    Query query = queryBuilder.toQuery(createShardContext());
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));

    final NestedQueryBuilder failingQueryBuilder = new NestedQueryBuilder("unmapped", new MatchAllQueryBuilder(), ScoreMode.None);
    failingQueryBuilder.ignoreUnmapped(false);
    IllegalStateException e = expectThrows(IllegalStateException.class, () -> failingQueryBuilder.toQuery(createShardContext()));
    assertThat(e.getMessage(), containsString("[" + NestedQueryBuilder.NAME + "] failed to find nested object under path [unmapped]"));
}
项目:elasticsearch_my    文件:NestedQueryBuilderTests.java   
public void testIgnoreUnmappedWithRewrite() throws IOException {
    // WrapperQueryBuilder makes sure we always rewrite
    final NestedQueryBuilder queryBuilder =
        new NestedQueryBuilder("unmapped", new WrapperQueryBuilder(new MatchAllQueryBuilder().toString()), ScoreMode.None);
    queryBuilder.ignoreUnmapped(true);
    QueryShardContext queryShardContext = createShardContext();
    Query query = queryBuilder.rewrite(queryShardContext).toQuery(queryShardContext);
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));
}
项目:elasticsearch_my    文件:GeoShapeQueryBuilderTests.java   
public void testIgnoreUnmapped() throws IOException {
    ShapeType shapeType = ShapeType.randomType(random());
    ShapeBuilder shape = RandomShapeGenerator.createShapeWithin(random(), null, shapeType);
    final GeoShapeQueryBuilder queryBuilder = new GeoShapeQueryBuilder("unmapped", shape);
    queryBuilder.ignoreUnmapped(true);
    Query query = queryBuilder.toQuery(createShardContext());
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));

    final GeoShapeQueryBuilder failingQueryBuilder = new GeoShapeQueryBuilder("unmapped", shape);
    failingQueryBuilder.ignoreUnmapped(false);
    QueryShardException e = expectThrows(QueryShardException.class, () -> failingQueryBuilder.toQuery(createShardContext()));
    assertThat(e.getMessage(), containsString("failed to find geo_shape field [unmapped]"));
}
项目:elasticsearch_my    文件:GeoPolygonQueryBuilderTests.java   
public void testIgnoreUnmapped() throws IOException {
    List<GeoPoint> polygon = randomPolygon();
    final GeoPolygonQueryBuilder queryBuilder = new GeoPolygonQueryBuilder("unmapped", polygon);
    queryBuilder.ignoreUnmapped(true);
    Query query = queryBuilder.toQuery(createShardContext());
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));

    final GeoPolygonQueryBuilder failingQueryBuilder = new GeoPolygonQueryBuilder("unmapped", polygon);
    failingQueryBuilder.ignoreUnmapped(false);
    QueryShardException e = expectThrows(QueryShardException.class, () -> failingQueryBuilder.toQuery(createShardContext()));
    assertThat(e.getMessage(), containsString("failed to find geo_point field [unmapped]"));
}
项目:elasticsearch_my    文件:QueryStringQueryBuilderTests.java   
@Override
protected void doAssertLuceneQuery(QueryStringQueryBuilder queryBuilder,
                                   Query query, SearchContext context) throws IOException {
    if ("".equals(queryBuilder.queryString())) {
        assertThat(query, instanceOf(MatchNoDocsQuery.class));
    } else {
        assertThat(query, either(instanceOf(TermQuery.class)).or(instanceOf(AllTermQuery.class))
                .or(instanceOf(BooleanQuery.class)).or(instanceOf(DisjunctionMaxQuery.class))
                .or(instanceOf(PhraseQuery.class)));
    }
}
项目:elasticsearch_my    文件:MatchPhrasePrefixQueryBuilderTests.java   
@Override
protected void doAssertLuceneQuery(MatchPhrasePrefixQueryBuilder queryBuilder, Query query, SearchContext context)
        throws IOException {
    assertThat(query, notNullValue());
    assertThat(query,
            either(instanceOf(BooleanQuery.class)).or(instanceOf(MultiPhrasePrefixQuery.class))
            .or(instanceOf(TermQuery.class)).or(instanceOf(PointRangeQuery.class))
            .or(instanceOf(IndexOrDocValuesQuery.class)).or(instanceOf(MatchNoDocsQuery.class)));
}
项目:elasticsearch_my    文件:GeoDistanceQueryBuilderTests.java   
public void testIgnoreUnmapped() throws IOException {
    final GeoDistanceQueryBuilder queryBuilder = new GeoDistanceQueryBuilder("unmapped").point(0.0, 0.0).distance("20m");
    queryBuilder.ignoreUnmapped(true);
    QueryShardContext shardContext = createShardContext();
    Query query = queryBuilder.toQuery(shardContext);
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));

    final GeoDistanceQueryBuilder failingQueryBuilder = new GeoDistanceQueryBuilder("unmapped").point(0.0, 0.0).distance("20m");
    failingQueryBuilder.ignoreUnmapped(false);
    QueryShardException e = expectThrows(QueryShardException.class, () -> failingQueryBuilder.toQuery(shardContext));
    assertThat(e.getMessage(), containsString("failed to find geo_point field [unmapped]"));
}
项目:elasticsearch_my    文件:IdsQueryBuilderTests.java   
@Override
protected void doAssertLuceneQuery(IdsQueryBuilder queryBuilder, Query query, SearchContext context) throws IOException {
    if (queryBuilder.ids().size() == 0) {
        assertThat(query, instanceOf(MatchNoDocsQuery.class));
    } else {
        assertThat(query, instanceOf(TermInSetQuery.class));
    }
}
项目:elasticsearch_my    文件:TypeQueryBuilderTests.java   
@Override
protected void doAssertLuceneQuery(TypeQueryBuilder queryBuilder, Query query, SearchContext context) throws IOException {
    if (createShardContext().getMapperService().documentMapper(queryBuilder.type()) == null) {
        assertEquals(new MatchNoDocsQuery(), query);
    } else {
        assertEquals(new TypeFieldMapper.TypesQuery(new BytesRef(queryBuilder.type())), query);
    }
}
项目:elasticsearch_my    文件:ParentIdQueryBuilderTests.java   
public void testIgnoreUnmapped() throws IOException {
    final ParentIdQueryBuilder queryBuilder = new ParentIdQueryBuilder("unmapped", "foo");
    queryBuilder.ignoreUnmapped(true);
    Query query = queryBuilder.toQuery(createShardContext());
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));

    final ParentIdQueryBuilder failingQueryBuilder = new ParentIdQueryBuilder("unmapped", "foo");
    failingQueryBuilder.ignoreUnmapped(false);
    QueryShardException e = expectThrows(QueryShardException.class, () -> failingQueryBuilder.toQuery(createShardContext()));
    assertThat(e.getMessage(), containsString("[" + ParentIdQueryBuilder.NAME + "] no mapping found for type [unmapped]"));
}
项目:elasticsearch_my    文件:GeoBoundingBoxQueryBuilderTests.java   
public void testIgnoreUnmapped() throws IOException {
    final GeoBoundingBoxQueryBuilder queryBuilder = new GeoBoundingBoxQueryBuilder("unmapped").setCorners(1.0, 0.0, 0.0, 1.0);
    queryBuilder.ignoreUnmapped(true);
    QueryShardContext shardContext = createShardContext();
    Query query = queryBuilder.toQuery(shardContext);
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));

    final GeoBoundingBoxQueryBuilder failingQueryBuilder = new GeoBoundingBoxQueryBuilder("unmapped").setCorners(1.0, 0.0, 0.0, 1.0);
    failingQueryBuilder.ignoreUnmapped(false);
    QueryShardException e = expectThrows(QueryShardException.class, () -> failingQueryBuilder.toQuery(shardContext));
    assertThat(e.getMessage(), containsString("failed to find geo_point field [unmapped]"));
}
项目:elasticsearch_my    文件:MatchPhraseQueryBuilderTests.java   
@Override
protected void doAssertLuceneQuery(MatchPhraseQueryBuilder queryBuilder, Query query, SearchContext context) throws IOException {
    assertThat(query, notNullValue());
    assertThat(query, either(instanceOf(BooleanQuery.class)).or(instanceOf(PhraseQuery.class))
            .or(instanceOf(TermQuery.class)).or(instanceOf(PointRangeQuery.class))
            .or(instanceOf(IndexOrDocValuesQuery.class)).or(instanceOf(MatchNoDocsQuery.class)));
}
项目:elasticsearch_my    文件:MultiMatchQueryBuilderTests.java   
@Override
protected void doAssertLuceneQuery(MultiMatchQueryBuilder queryBuilder, Query query, SearchContext context) throws IOException {
    // we rely on integration tests for deeper checks here
    assertThat(query, either(instanceOf(BoostQuery.class)).or(instanceOf(TermQuery.class)).or(instanceOf(AllTermQuery.class))
            .or(instanceOf(BooleanQuery.class)).or(instanceOf(DisjunctionMaxQuery.class))
            .or(instanceOf(FuzzyQuery.class)).or(instanceOf(MultiPhrasePrefixQuery.class))
            .or(instanceOf(MatchAllDocsQuery.class)).or(instanceOf(ExtendedCommonTermsQuery.class))
            .or(instanceOf(MatchNoDocsQuery.class)).or(instanceOf(PhraseQuery.class))
            .or(instanceOf(LegacyNumericRangeQuery.class))
            .or(instanceOf(PointRangeQuery.class)).or(instanceOf(IndexOrDocValuesQuery.class)));
}
项目:elasticsearch_my    文件:HasParentQueryBuilderTests.java   
public void testIgnoreUnmapped() throws IOException {
    final HasParentQueryBuilder queryBuilder = new HasParentQueryBuilder("unmapped", new MatchAllQueryBuilder(), false);
    queryBuilder.ignoreUnmapped(true);
    Query query = queryBuilder.toQuery(createShardContext());
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));

    final HasParentQueryBuilder failingQueryBuilder = new HasParentQueryBuilder("unmapped", new MatchAllQueryBuilder(), false);
    failingQueryBuilder.ignoreUnmapped(false);
    QueryShardException e = expectThrows(QueryShardException.class, () -> failingQueryBuilder.toQuery(createShardContext()));
    assertThat(e.getMessage(),
                containsString("[" + HasParentQueryBuilder.NAME + "] query configured 'parent_type' [unmapped] is not a valid type"));
}
项目:elasticsearch_my    文件:HasParentQueryBuilderTests.java   
public void testIgnoreUnmappedWithRewrite() throws IOException {
    // WrapperQueryBuilder makes sure we always rewrite
    final HasParentQueryBuilder queryBuilder =
        new HasParentQueryBuilder("unmapped", new WrapperQueryBuilder(new MatchAllQueryBuilder().toString()), false);
    queryBuilder.ignoreUnmapped(true);
    QueryShardContext queryShardContext = createShardContext();
    Query query = queryBuilder.rewrite(queryShardContext).toQuery(queryShardContext);
    assertThat(query, notNullValue());
    assertThat(query, instanceOf(MatchNoDocsQuery.class));
}
项目:elasticsearch_my    文件:NestedHelperTests.java   
public void testMatchNo() {
    assertFalse(new NestedHelper(mapperService).mightMatchNestedDocs(new MatchNoDocsQuery()));
    assertFalse(new NestedHelper(mapperService).mightMatchNonNestedDocs(new MatchNoDocsQuery(), "nested1"));
    assertFalse(new NestedHelper(mapperService).mightMatchNonNestedDocs(new MatchNoDocsQuery(), "nested2"));
    assertFalse(new NestedHelper(mapperService).mightMatchNonNestedDocs(new MatchNoDocsQuery(), "nested3"));
    assertFalse(new NestedHelper(mapperService).mightMatchNonNestedDocs(new MatchNoDocsQuery(), "nested_missing"));
}