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

项目:incubator-netbeans    文件:DocumentUtil.java   
static Query binaryNameQuery (final String resourceName) {
    final BooleanQuery query = new BooleanQuery ();
    int index = resourceName.lastIndexOf(BinaryName.PKG_SEPARATOR);  // NOI18N
    String pkgName, sName;
    if (index < 0) {
        pkgName = "";   // NOI18N
        sName = resourceName;
    }
    else {
        pkgName = resourceName.substring(0,index);
        sName = resourceName.substring(index+1);
    }
    sName = sName + WILDCARD_QUERY_WILDCARD;   //Type of type element (Enum, Class, Interface, Annotation)
    query.add (new TermQuery (new Term (FIELD_PACKAGE_NAME, pkgName)),BooleanClause.Occur.MUST);
    query.add (new WildcardQuery (new Term (FIELD_BINARY_NAME, sName)),BooleanClause.Occur.MUST);
    return query;
}
项目:lams    文件:MultiFieldQueryParser.java   
/**
 * @deprecated Use {@link #parse(String[], String[], BooleanClause.Occur[], Analyzer)}
 */
@Deprecated
public static Query parse(Version matchVersion, String[] queries, String[] fields, BooleanClause.Occur[] flags,
    Analyzer analyzer) throws ParseException
{
  if (!(queries.length == fields.length && queries.length == flags.length))
    throw new IllegalArgumentException("queries, fields, and flags array have have different length");
  BooleanQuery bQuery = new BooleanQuery();
  for (int i = 0; i < fields.length; i++)
  {
    QueryParser qp = new QueryParser(matchVersion, fields[i], analyzer);
    Query q = qp.parse(queries[i]);
    if (q!=null && // q never null, just being defensive
        (!(q instanceof BooleanQuery) || ((BooleanQuery)q).getClauses().length>0)) {
      bQuery.add(q, flags[i]);
    }
  }
  return bQuery;
}
项目:elasticsearch_my    文件:PercolatorFieldMapperTests.java   
public void testExtractTerms() throws Exception {
    addQueryMapping();
    BooleanQuery.Builder bq = new BooleanQuery.Builder();
    TermQuery termQuery1 = new TermQuery(new Term("field", "term1"));
    bq.add(termQuery1, BooleanClause.Occur.SHOULD);
    TermQuery termQuery2 = new TermQuery(new Term("field", "term2"));
    bq.add(termQuery2, BooleanClause.Occur.SHOULD);

    DocumentMapper documentMapper = mapperService.documentMapper(typeName);
    PercolatorFieldMapper fieldMapper = (PercolatorFieldMapper) documentMapper.mappers().getMapper(fieldName);
    ParseContext.InternalParseContext parseContext = new ParseContext.InternalParseContext(Settings.EMPTY,
            mapperService.documentMapperParser(), documentMapper, null, null);
    fieldMapper.processQuery(bq.build(), parseContext);
    ParseContext.Document document = parseContext.doc();

    PercolatorFieldMapper.FieldType fieldType = (PercolatorFieldMapper.FieldType) fieldMapper.fieldType();
    assertThat(document.getField(fieldType.extractionResultField.name()).stringValue(), equalTo(EXTRACTION_COMPLETE));
    List<IndexableField> fields = new ArrayList<>(Arrays.asList(document.getFields(fieldType.queryTermsField.name())));
    Collections.sort(fields, (field1, field2) -> field1.binaryValue().compareTo(field2.binaryValue()));
    assertThat(fields.size(), equalTo(2));
    assertThat(fields.get(0).binaryValue().utf8ToString(), equalTo("field\u0000term1"));
    assertThat(fields.get(1).binaryValue().utf8ToString(), equalTo("field\u0000term2"));
}
项目:elasticsearch_my    文件:PercolateQueryBuilderTests.java   
public void testCreateMultiDocumentSearcher() throws Exception {
    int numDocs = randomIntBetween(2, 8);
    List<ParseContext.Document> docs = new ArrayList<>(numDocs);
    for (int i = 0; i < numDocs; i++) {
        docs.add(new ParseContext.Document());
    }

    Analyzer analyzer = new WhitespaceAnalyzer();
    ParsedDocument parsedDocument = new ParsedDocument(null, null, "_id", "_type", null, docs, null, null, null);
    IndexSearcher indexSearcher = PercolateQueryBuilder.createMultiDocumentSearcher(analyzer, parsedDocument);
    assertThat(indexSearcher.getIndexReader().numDocs(), equalTo(numDocs));

    // ensure that any query get modified so that the nested docs are never included as hits:
    Query query = new MatchAllDocsQuery();
    BooleanQuery result = (BooleanQuery) indexSearcher.createNormalizedWeight(query, true).getQuery();
    assertThat(result.clauses().size(), equalTo(2));
    assertThat(result.clauses().get(0).getQuery(), sameInstance(query));
    assertThat(result.clauses().get(0).getOccur(), equalTo(BooleanClause.Occur.MUST));
    assertThat(result.clauses().get(1).getOccur(), equalTo(BooleanClause.Occur.MUST_NOT));
}
项目:elasticsearch_my    文件:BoolQueryBuilder.java   
@Override
protected Query doToQuery(QueryShardContext context) throws IOException {
    BooleanQuery.Builder booleanQueryBuilder = new BooleanQuery.Builder();
    booleanQueryBuilder.setDisableCoord(disableCoord);
    addBooleanClauses(context, booleanQueryBuilder, mustClauses, BooleanClause.Occur.MUST);
    addBooleanClauses(context, booleanQueryBuilder, mustNotClauses, BooleanClause.Occur.MUST_NOT);
    addBooleanClauses(context, booleanQueryBuilder, shouldClauses, BooleanClause.Occur.SHOULD);
    addBooleanClauses(context, booleanQueryBuilder, filterClauses, BooleanClause.Occur.FILTER);
    BooleanQuery booleanQuery = booleanQueryBuilder.build();
    if (booleanQuery.clauses().isEmpty()) {
        return new MatchAllDocsQuery();
    }

    final String minimumShouldMatch;
    if (context.isFilter() && this.minimumShouldMatch == null && shouldClauses.size() > 0) {
        minimumShouldMatch = "1";
    } else {
        minimumShouldMatch = this.minimumShouldMatch;
    }
    Query query = Queries.applyMinimumShouldMatch(booleanQuery, minimumShouldMatch);
    return adjustPureNegative ? fixNegativeQueryIfNeeded(query) : query;
}
项目:elasticsearch_my    文件:BoolQueryBuilder.java   
private static void addBooleanClauses(QueryShardContext context, BooleanQuery.Builder booleanQueryBuilder,
                                      List<QueryBuilder> clauses, Occur occurs) throws IOException {
    for (QueryBuilder query : clauses) {
        Query luceneQuery = null;
        switch (occurs) {
            case MUST:
            case SHOULD:
                luceneQuery = query.toQuery(context);
                break;
            case FILTER:
            case MUST_NOT:
                luceneQuery = query.toFilter(context);
                break;
        }
        booleanQueryBuilder.add(new BooleanClause(luceneQuery, occurs));
    }
}
项目: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    文件:SimpleQueryParser.java   
/**
 * Dispatches to Lucene's SimpleQueryParser's newFuzzyQuery, optionally
 * lowercasing the term first
 */
@Override
public Query newFuzzyQuery(String text, int fuzziness) {
    BooleanQuery.Builder bq = new BooleanQuery.Builder();
    bq.setDisableCoord(true);
    for (Map.Entry<String,Float> entry : weights.entrySet()) {
        final String fieldName = entry.getKey();
        try {
            final BytesRef term = getAnalyzer().normalize(fieldName, text);
            Query query = new FuzzyQuery(new Term(fieldName, term), fuzziness);
            bq.add(wrapWithBoost(query, entry.getValue()), BooleanClause.Occur.SHOULD);
        } catch (RuntimeException e) {
            rethrowUnlessLenient(e);
        }
    }
    return super.simplify(bq.build());
}
项目:elasticsearch_my    文件:SimpleQueryParser.java   
@Override
public Query newPhraseQuery(String text, int slop) {
    BooleanQuery.Builder bq = new BooleanQuery.Builder();
    bq.setDisableCoord(true);
    for (Map.Entry<String,Float> entry : weights.entrySet()) {
        try {
            String field = entry.getKey();
            if (settings.quoteFieldSuffix() != null) {
                String quoteField = field + settings.quoteFieldSuffix();
                MappedFieldType quotedFieldType = context.fieldMapper(quoteField);
                if (quotedFieldType != null) {
                    field = quoteField;
                }
            }
            Float boost = entry.getValue();
            Query q = createPhraseQuery(field, text, slop);
            if (q != null) {
                bq.add(wrapWithBoost(q, boost), BooleanClause.Occur.SHOULD);
            }
        } catch (RuntimeException e) {
            rethrowUnlessLenient(e);
        }
    }
    return super.simplify(bq.build());
}
项目:elasticsearch_my    文件:SimpleQueryParser.java   
/**
 * Dispatches to Lucene's SimpleQueryParser's newPrefixQuery, optionally
 * lowercasing the term first or trying to analyze terms
 */
@Override
public Query newPrefixQuery(String text) {
    BooleanQuery.Builder bq = new BooleanQuery.Builder();
    bq.setDisableCoord(true);
    for (Map.Entry<String,Float> entry : weights.entrySet()) {
        final String fieldName = entry.getKey();
        try {
            if (settings.analyzeWildcard()) {
                Query analyzedQuery = newPossiblyAnalyzedQuery(fieldName, text);
                if (analyzedQuery != null) {
                    bq.add(wrapWithBoost(analyzedQuery, entry.getValue()), BooleanClause.Occur.SHOULD);
                }
            } else {
                Term term = new Term(fieldName, getAnalyzer().normalize(fieldName, text));
                Query query = new PrefixQuery(term);
                bq.add(wrapWithBoost(query, entry.getValue()), BooleanClause.Occur.SHOULD);
            }
        } catch (RuntimeException e) {
            return rethrowUnlessLenient(e);
        }
    }
    return super.simplify(bq.build());
}
项目:Elasticsearch    文件:PercolatorService.java   
private void queryBasedPercolating(Engine.Searcher percolatorSearcher, PercolateContext context, QueryCollector percolateCollector) throws IOException {
    Query percolatorTypeFilter = context.indexService().mapperService().documentMapper(TYPE_NAME).typeFilter();

    final Query filter;
    if (context.aliasFilter() != null) {
        BooleanQuery.Builder booleanFilter = new BooleanQuery.Builder();
        booleanFilter.add(context.aliasFilter(), BooleanClause.Occur.MUST);
        booleanFilter.add(percolatorTypeFilter, BooleanClause.Occur.MUST);
        filter = booleanFilter.build();
    } else {
        filter = percolatorTypeFilter;
    }

    Query query = Queries.filtered(context.percolateQuery(), filter);
    percolatorSearcher.searcher().search(query, percolateCollector);
    percolateCollector.aggregatorCollector.postCollection();
    if (context.aggregations() != null) {
        aggregationPhase.execute(context);
    }
}
项目:elasticsearch_my    文件:Queries.java   
public static Query applyMinimumShouldMatch(BooleanQuery query, @Nullable String minimumShouldMatch) {
    if (minimumShouldMatch == null) {
        return query;
    }
    int optionalClauses = 0;
    for (BooleanClause c : query.clauses()) {
        if (c.getOccur() == BooleanClause.Occur.SHOULD) {
            optionalClauses++;
        }
    }

    int msm = calculateMinShouldMatch(optionalClauses, minimumShouldMatch);
    if (0 < msm) {
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        builder.setDisableCoord(query.isCoordDisabled());
        for (BooleanClause clause : query) {
            builder.add(clause);
        }
        builder.setMinimumNumberShouldMatch(msm);
        return builder.build();
    } else {
        return query;
    }
}
项目:elasticsearch_my    文件:PlainHighlighterTests.java   
public void checkGeoQueryHighlighting(Query geoQuery) throws IOException, InvalidTokenOffsetsException {
    Map analysers = new HashMap<String, Analyzer>();
    analysers.put("text", new StandardAnalyzer());
    FieldNameAnalyzer fieldNameAnalyzer = new FieldNameAnalyzer(analysers);
    Query termQuery = new TermQuery(new Term("text", "failure"));
    Query boolQuery = new BooleanQuery.Builder().add(new BooleanClause(geoQuery, BooleanClause.Occur.SHOULD))
        .add(new BooleanClause(termQuery, BooleanClause.Occur.SHOULD)).build();
    org.apache.lucene.search.highlight.Highlighter highlighter =
        new org.apache.lucene.search.highlight.Highlighter(new CustomQueryScorer(boolQuery));
    String fragment = highlighter.getBestFragment(fieldNameAnalyzer.tokenStream("text", "Arbitrary text field which should not cause " +
        "a failure"), "Arbitrary text field which should not cause a failure");
    assertThat(fragment, equalTo("Arbitrary text field which should not cause a <B>failure</B>"));
    Query rewritten = boolQuery.rewrite(null);
    highlighter = new org.apache.lucene.search.highlight.Highlighter(new CustomQueryScorer(rewritten));
    fragment = highlighter.getBestFragment(fieldNameAnalyzer.tokenStream("text", "Arbitrary text field which should not cause " +
        "a failure"), "Arbitrary text field which should not cause a failure");
    assertThat(fragment, equalTo("Arbitrary text field which should not cause a <B>failure</B>"));
}
项目:elasticsearch_my    文件:SimpleQueryParserTests.java   
public void testAnalyzeWildcard() {
    SimpleQueryParser.Settings settings = new SimpleQueryParser.Settings();
    settings.analyzeWildcard(true);
    Map<String, Float> weights = new HashMap<>();
    weights.put("field1", 1.0f);
    SimpleQueryParser parser = new MockSimpleQueryParser(new StandardAnalyzer(), weights, -1, settings);
    for (Operator op : Operator.values()) {
        BooleanClause.Occur defaultOp = op.toBooleanClauseOccur();
        parser.setDefaultOperator(defaultOp);
        Query query = parser.parse("first foo-bar-foobar* last");
        Query expectedQuery =
            new BooleanQuery.Builder()
                .add(new BooleanClause(new TermQuery(new Term("field1", "first")), defaultOp))
                .add(new BooleanQuery.Builder()
                    .add(new BooleanClause(new TermQuery(new Term("field1", "foo")), defaultOp))
                    .add(new BooleanClause(new TermQuery(new Term("field1", "bar")), defaultOp))
                    .add(new BooleanClause(new PrefixQuery(new Term("field1", "foobar")), defaultOp))
                    .build(), defaultOp)
                .add(new BooleanClause(new TermQuery(new Term("field1", "last")), defaultOp))
                .build();
        assertThat(query, equalTo(expectedQuery));
    }
}
项目:RelevancyFeedback    文件:RelevancyFeedback.java   
private BooleanQuery buildMustMatchQuery(Map<String,Map<String, Flt>> fieldValues, boolean mustMatch){
    BooleanQuery.Builder qryBuilder = new BooleanQuery.Builder();
    for(Map.Entry<String,Map<String,Flt>> entry: fieldValues.entrySet()){
        String fieldName = entry.getKey();
        for(Map.Entry<String,Flt> fieldValue: entry.getValue().entrySet()){
            String value = fieldValue.getKey();
            TermQuery tq = new TermQuery(new Term(fieldName, value));
            if(mustMatch) {
                qryBuilder.add(tq, BooleanClause.Occur.MUST);
            }
            else{
                qryBuilder.add(tq, BooleanClause.Occur.MUST_NOT);
            }
        }
    }
    return qryBuilder.build();
}
项目:elasticsearch_my    文件:BoolQueryBuilderTests.java   
public void testMinShouldMatchFilterWithoutShouldClauses() throws Exception {
    BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    boolQueryBuilder.filter(new BoolQueryBuilder().must(new MatchAllQueryBuilder()));
    Query query = boolQueryBuilder.toQuery(createShardContext());
    assertThat(query, instanceOf(BooleanQuery.class));
    BooleanQuery booleanQuery = (BooleanQuery) query;
    assertThat(booleanQuery.getMinimumNumberShouldMatch(), equalTo(0));
    assertThat(booleanQuery.clauses().size(), equalTo(1));
    BooleanClause booleanClause = booleanQuery.clauses().get(0);
    assertThat(booleanClause.getOccur(), equalTo(BooleanClause.Occur.FILTER));
    assertThat(booleanClause.getQuery(), instanceOf(BooleanQuery.class));
    BooleanQuery innerBooleanQuery = (BooleanQuery) booleanClause.getQuery();
    //we didn't set minimum should match initially, there are no should clauses so it should be 0
    assertThat(innerBooleanQuery.getMinimumNumberShouldMatch(), equalTo(0));
    assertThat(innerBooleanQuery.clauses().size(), equalTo(1));
    BooleanClause innerBooleanClause = innerBooleanQuery.clauses().get(0);
    assertThat(innerBooleanClause.getOccur(), equalTo(BooleanClause.Occur.MUST));
    assertThat(innerBooleanClause.getQuery(), instanceOf(MatchAllDocsQuery.class));
}
项目:elasticsearch_my    文件:BoolQueryBuilderTests.java   
public void testMinShouldMatchFilterWithShouldClauses() throws Exception {
    BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    boolQueryBuilder.filter(new BoolQueryBuilder().must(new MatchAllQueryBuilder()).should(new MatchAllQueryBuilder()));
    Query query = boolQueryBuilder.toQuery(createShardContext());
    assertThat(query, instanceOf(BooleanQuery.class));
    BooleanQuery booleanQuery = (BooleanQuery) query;
    assertThat(booleanQuery.getMinimumNumberShouldMatch(), equalTo(0));
    assertThat(booleanQuery.clauses().size(), equalTo(1));
    BooleanClause booleanClause = booleanQuery.clauses().get(0);
    assertThat(booleanClause.getOccur(), equalTo(BooleanClause.Occur.FILTER));
    assertThat(booleanClause.getQuery(), instanceOf(BooleanQuery.class));
    BooleanQuery innerBooleanQuery = (BooleanQuery) booleanClause.getQuery();
    //we didn't set minimum should match initially, but there are should clauses so it should be 1
    assertThat(innerBooleanQuery.getMinimumNumberShouldMatch(), equalTo(1));
    assertThat(innerBooleanQuery.clauses().size(), equalTo(2));
    BooleanClause innerBooleanClause1 = innerBooleanQuery.clauses().get(0);
    assertThat(innerBooleanClause1.getOccur(), equalTo(BooleanClause.Occur.MUST));
    assertThat(innerBooleanClause1.getQuery(), instanceOf(MatchAllDocsQuery.class));
    BooleanClause innerBooleanClause2 = innerBooleanQuery.clauses().get(1);
    assertThat(innerBooleanClause2.getOccur(), equalTo(BooleanClause.Occur.SHOULD));
    assertThat(innerBooleanClause2.getQuery(), instanceOf(MatchAllDocsQuery.class));
}
项目:sjk    文件:SearchServiceImpl.java   
/**
 * 查询索引
 * 
 * @param keywords
 * @return
 * @throws Exception
 */
public List<Document> searchIndex(Integer typeId, String keywords) throws Exception {
    // 1.init searcher
    Analyzer analyzer = new PaodingAnalyzer();
    IndexReader reader = IndexReader.open(typeId == appConfig.getGameTypeId() ? appConfig.getGameIndexDir()
            : appConfig.getSoftIndexDir());
    BooleanClause.Occur[] flags = new BooleanClause.Occur[] { BooleanClause.Occur.SHOULD,
            BooleanClause.Occur.SHOULD };
    Query query = MultiFieldQueryParser.parse(keywords, appConfig.getQueryFields(), flags, analyzer);
    query = query.rewrite(reader);

    // 2.search
    List<Document> docs = new ArrayList<Document>();
    Hits hits = (typeId == appConfig.getGameTypeId() ? gameSearcher.search(query, Sort.RELEVANCE) : softSearcher
            .search(query, Sort.RELEVANCE));// searcher.search(query,
                                            // Sort.RELEVANCE);
    for (int i = 0; i < hits.length(); i++) {
        docs.add(hits.doc(i));
    }

    // 3.return
    reader.close();
    return docs;
}
项目:Elasticsearch    文件:MultiMatchQueryBuilder.java   
public Query combineGrouped(List<Query> queries) {
    if (queries == null || queries.isEmpty()) {
        return null;
    }
    if (queries.size() == 1) {
        return queries.get(0);
    }
    if (groupDismax) {
        return new DisjunctionMaxQuery(queries, tieBreaker);
    } else {
        BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder();
        for (Query query : queries) {
            booleanQuery.add(query, BooleanClause.Occur.SHOULD);
        }
        return booleanQuery.build();
    }
}
项目:Equella    文件:ItemIndex.java   
/**
 * @dytech.jira see Jira Review TLE-784 :
 *              http://apps.dytech.com.au/jira/browse/TLE-784
 */
protected Query addExtraQuery(@Nullable Query query, Search searchreq, IndexReader reader)
{
    FreeTextQuery fullftQuery = searchreq.getFreeTextQuery();
    if( fullftQuery == null )
    {
        return query;
    }
    BooleanClause clause = convertToBooleanClause(fullftQuery, reader);
    if( !clause.isProhibited() && !clause.isRequired() )
    {
        clause.setOccur(Occur.MUST);
    }

    BooleanQuery andThem = new BooleanQuery();
    andThem.add(clause);
    if( query != null )
    {
        andThem.add(query, Occur.MUST);
    }
    return andThem;
}
项目:Equella    文件:ItemIndex.java   
/**
 * Takes a FreeTextQuery and converts it to a BooleanClause by dispatching
 * to the correct implementation.
 * 
 * @throws IOException
 * @throws ParseException
 */
@Nullable
private BooleanClause convertToBooleanClause(FreeTextQuery query, IndexReader reader)
{
    if( query instanceof FreeTextFieldQuery )
    {
        return convertField((FreeTextFieldQuery) query, reader);
    }
    else if( query instanceof FreeTextFieldExistsQuery )
    {
        return convertFieldExists((FreeTextFieldExistsQuery) query, reader);
    }
    else if( query instanceof FreeTextDateQuery )
    {
        return convertDate((FreeTextDateQuery) query);
    }
    else if( query instanceof FreeTextAutocompleteQuery )
    {
        return convertAutoComplete((FreeTextAutocompleteQuery) query, reader);
    }
    else
    {
        return convertBoolean((FreeTextBooleanQuery) query, reader);
    }
}
项目:lams    文件:StandardBooleanQueryNodeBuilder.java   
private static BooleanClause.Occur getModifierValue(QueryNode node) {

    if (node instanceof ModifierQueryNode) {
      ModifierQueryNode mNode = ((ModifierQueryNode) node);
      Modifier modifier = mNode.getModifier();

      if (Modifier.MOD_NONE.equals(modifier)) {
        return BooleanClause.Occur.SHOULD;

      } else if (Modifier.MOD_NOT.equals(modifier)) {
        return BooleanClause.Occur.MUST_NOT;

      } else {
        return BooleanClause.Occur.MUST;
      }
    }

    return BooleanClause.Occur.SHOULD;

  }
项目:lams    文件:BooleanFilterBuilder.java   
@Override
public Filter getFilter(Element e) throws ParserException {
  BooleanFilter bf = new BooleanFilter();
  NodeList nl = e.getChildNodes();

  for (int i = 0; i < nl.getLength(); i++) {
    Node node = nl.item(i);
    if (node.getNodeName().equals("Clause")) {
      Element clauseElem = (Element) node;
      BooleanClause.Occur occurs = BooleanQueryBuilder.getOccursValue(clauseElem);

      Element clauseFilter = DOMUtils.getFirstChildOrFail(clauseElem);
      Filter f = factory.getFilter(clauseFilter);
      bf.add(new FilterClause(f, occurs));
    }
  }

  return bf;
}
项目:lams    文件:BooleanQueryBuilder.java   
@Override
public Query getQuery(Element e) throws ParserException {
  BooleanQuery bq = new BooleanQuery(DOMUtils.getAttribute(e, "disableCoord", false));
  bq.setMinimumNumberShouldMatch(DOMUtils.getAttribute(e, "minimumNumberShouldMatch", 0));
  bq.setBoost(DOMUtils.getAttribute(e, "boost", 1.0f));

  NodeList nl = e.getChildNodes();
  for (int i = 0; i < nl.getLength(); i++) {
    Node node = nl.item(i);
    if (node.getNodeName().equals("Clause")) {
      Element clauseElem = (Element) node;
      BooleanClause.Occur occurs = getOccursValue(clauseElem);

      Element clauseQuery = DOMUtils.getFirstChildOrFail(clauseElem);
      Query q = factory.getQuery(clauseQuery);
      bq.add(new BooleanClause(q, occurs));
    }
  }

  return bq;
}
项目:lams    文件:BooleanQueryBuilder.java   
static BooleanClause.Occur getOccursValue(Element clauseElem) throws ParserException {
  String occs = clauseElem.getAttribute("occurs");
  BooleanClause.Occur occurs = BooleanClause.Occur.SHOULD;
  if ("must".equalsIgnoreCase(occs)) {
    occurs = BooleanClause.Occur.MUST;
  } else {
    if ("mustNot".equalsIgnoreCase(occs)) {
      occurs = BooleanClause.Occur.MUST_NOT;
    } else {
      if (("should".equalsIgnoreCase(occs)) || ("".equals(occs))) {
        occurs = BooleanClause.Occur.SHOULD;
      } else {
        if (occs != null) {
          throw new ParserException("Invalid value for \"occurs\" attribute of clause:" + occs);
        }
      }
    }
  }
  return occurs;

}
项目:lams    文件:SimpleTermRewriteQuery.java   
@Override
public Query rewrite(IndexReader reader) throws IOException {
  final List<Query> luceneSubQueries = new ArrayList<>();
  srndQuery.visitMatchingTerms(reader, fieldName,
  new SimpleTerm.MatchingTermVisitor() {
    @Override
    public void visitMatchingTerm(Term term) throws IOException {
      luceneSubQueries.add(qf.newTermQuery(term));
    }
  });
  return  (luceneSubQueries.size() == 0) ? SrndQuery.theEmptyLcnQuery
  : (luceneSubQueries.size() == 1) ? luceneSubQueries.get(0)
  : SrndBooleanQuery.makeBooleanQuery(
    /* luceneSubQueries all have default weight */
    luceneSubQueries, BooleanClause.Occur.SHOULD); /* OR the subquery terms */
}
项目:NGB-master    文件:VcfFilterForm.java   
private void addGeneFilter(BooleanQuery.Builder builder) {
    if (genes != null && !genes.field.isEmpty()) {
        BooleanQuery.Builder genesBuilder = new BooleanQuery.Builder();
        for (int i = 0; i < genes.field.size(); i++) {
            PrefixQuery geneIdPrefixQuery = new PrefixQuery(new Term(FeatureIndexFields.GENE_ID.getFieldName(),
                    genes.field.get(i).toLowerCase()));
            PrefixQuery geneNamePrefixQuery = new PrefixQuery(
                new Term(FeatureIndexFields.GENE_NAME.getFieldName(), genes.field.get(i).toLowerCase()));
            BooleanQuery.Builder geneIdOrNameQuery = new BooleanQuery.Builder();
            geneIdOrNameQuery.add(geneIdPrefixQuery, BooleanClause.Occur.SHOULD);
            geneIdOrNameQuery.add(geneNamePrefixQuery, BooleanClause.Occur.SHOULD);

            genesBuilder.add(geneIdOrNameQuery.build(), genes.conjunction ? BooleanClause.Occur.MUST :
                    BooleanClause.Occur.SHOULD);
        }

        builder.add(genesBuilder.build(), BooleanClause.Occur.MUST);
    }
}
项目:lams    文件:MultiFieldQueryParser.java   
/**
 * @deprecated Use {@link #parse(String, String[], BooleanClause.Occur[], Analyzer)}
 */
@Deprecated
public static Query parse(Version matchVersion, String query, String[] fields,
      BooleanClause.Occur[] flags, Analyzer analyzer) throws ParseException {
  if (fields.length != flags.length)
    throw new IllegalArgumentException("fields.length != flags.length");
  BooleanQuery bQuery = new BooleanQuery();
  for (int i = 0; i < fields.length; i++) {
    QueryParser qp = new QueryParser(matchVersion, fields[i], analyzer);
    Query q = qp.parse(query);
    if (q!=null && // q never null, just being defensive 
        (!(q instanceof BooleanQuery) || ((BooleanQuery)q).getClauses().length>0)) {
      bQuery.add(q, flags[i]);
    }
  }
  return bQuery;
}
项目:incubator-netbeans    文件:Queries.java   
private static void attach (final BooleanQuery query, final TermCollector collector) {
    for (BooleanClause clause : query.getClauses()) {
        final Query q = clause.getQuery();
        if (!(q instanceof TermCollector.TermCollecting)) {
            throw new IllegalArgumentException();
        }
        ((TermCollector.TermCollecting)q).attach(collector);
    }
}
项目:incubator-netbeans    文件:QuerySupport.java   
/**
 * Creates a boolean OR query.
 * @param queries the queries to compose into the OR query
 * @return the newly created OR query
 */
@NonNull
public Query or(@NonNull final Query...queries) {
    Parameters.notNull("queries", queries);     //NOI18N
    final org.apache.lucene.search.BooleanQuery bq = new org.apache.lucene.search.BooleanQuery();
    for (Query q : queries) {
        bq.add(new BooleanClause(q.queryImpl, org.apache.lucene.search.BooleanClause.Occur.SHOULD));
    }
    return new Query(
        qs,
        bq);
}
项目:incubator-netbeans    文件:ArtifactDependencyIndexCreator.java   
static Query query(String groupId, String artifactId, String version) {
    final BooleanQuery q = new BooleanQuery();
    q.add(new BooleanClause(new TermQuery(new Term(NB_DEPENDENCY_GROUP, groupId)), BooleanClause.Occur.MUST));
    q.add(new BooleanClause(new TermQuery(new Term(NB_DEPENDENCY_ARTIFACT, artifactId)), BooleanClause.Occur.MUST));
    q.add(new BooleanClause(new TermQuery(new Term(NB_DEPENDENCY_VERSION, version)), BooleanClause.Occur.MUST));
    return q;
}
项目:elasticsearch_my    文件:QueryAnalyzerTests.java   
public void testExtractQueryMetadata_booleanQuery() {
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    TermQuery termQuery1 = new TermQuery(new Term("_field", "_term"));
    builder.add(termQuery1, BooleanClause.Occur.SHOULD);
    PhraseQuery phraseQuery = new PhraseQuery("_field", "_term1", "term2");
    builder.add(phraseQuery, BooleanClause.Occur.SHOULD);

    BooleanQuery.Builder subBuilder = new BooleanQuery.Builder();
    TermQuery termQuery2 = new TermQuery(new Term("_field1", "_term"));
    subBuilder.add(termQuery2, BooleanClause.Occur.MUST);
    TermQuery termQuery3 = new TermQuery(new Term("_field3", "_long_term"));
    subBuilder.add(termQuery3, BooleanClause.Occur.MUST);
    builder.add(subBuilder.build(), BooleanClause.Occur.SHOULD);

    BooleanQuery booleanQuery = builder.build();
    Result result = analyze(booleanQuery);
    assertThat("Should clause with phrase query isn't verified, so entire query can't be verified", result.verified, is(false));
    List<Term> terms = new ArrayList<>(result.terms);
    Collections.sort(terms);
    assertThat(terms.size(), equalTo(3));
    assertThat(terms.get(0).field(), equalTo(termQuery1.getTerm().field()));
    assertThat(terms.get(0).bytes(), equalTo(termQuery1.getTerm().bytes()));
    assertThat(terms.get(1).field(), equalTo(phraseQuery.getTerms()[0].field()));
    assertThat(terms.get(1).bytes(), equalTo(phraseQuery.getTerms()[0].bytes()));
    assertThat(terms.get(2).field(), equalTo(termQuery3.getTerm().field()));
    assertThat(terms.get(2).bytes(), equalTo(termQuery3.getTerm().bytes()));
}
项目:elasticsearch_my    文件:QueryAnalyzerTests.java   
public void testExtractQueryMetadata_booleanQueryWithMustNot() {
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    TermQuery termQuery1 = new TermQuery(new Term("_field", "_term"));
    builder.add(termQuery1, BooleanClause.Occur.MUST_NOT);
    PhraseQuery phraseQuery = new PhraseQuery("_field", "_term1", "term2");
    builder.add(phraseQuery, BooleanClause.Occur.SHOULD);

    BooleanQuery booleanQuery = builder.build();
    Result result = analyze(booleanQuery);
    assertThat(result.verified, is(false));
    List<Term> terms = new ArrayList<>(result.terms);
    assertThat(terms.size(), equalTo(1));
    assertThat(terms.get(0).field(), equalTo(phraseQuery.getTerms()[0].field()));
    assertThat(terms.get(0).bytes(), equalTo(phraseQuery.getTerms()[0].bytes()));
}
项目:elasticsearch_my    文件:QueryAnalyzerTests.java   
public void testExtractQueryMetadata_commonTermsQuery() {
    CommonTermsQuery commonTermsQuery = new CommonTermsQuery(BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD, 100);
    commonTermsQuery.add(new Term("_field", "_term1"));
    commonTermsQuery.add(new Term("_field", "_term2"));
    Result result = analyze(commonTermsQuery);
    assertThat(result.verified, is(false));
    List<Term> terms = new ArrayList<>(result.terms);
    Collections.sort(terms);
    assertThat(terms.size(), equalTo(2));
    assertThat(terms.get(0).field(), equalTo("_field"));
    assertThat(terms.get(0).text(), equalTo("_term1"));
    assertThat(terms.get(1).field(), equalTo("_field"));
    assertThat(terms.get(1).text(), equalTo("_term2"));
}
项目: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"));
}
项目:NGB-master    文件:VcfFilterForm.java   
private void addAdditionalFilter(BooleanQuery.Builder builder,
        Map.Entry<String, Object> entry) {
    String key = entry.getKey().toLowerCase();
    if (entry.getValue() instanceof List) {
        addFiltersFromList(builder, entry, key);
    } else if (entry.getValue() instanceof Integer || entry.getValue() instanceof Long) {
        builder.add(IntPoint.newExactQuery(key, (Integer) entry.getValue()), BooleanClause.Occur.MUST);
    } else if (entry.getValue() instanceof Float || entry.getValue() instanceof Double) {
        builder.add(FloatPoint.newExactQuery(key, (Float) entry.getValue()), BooleanClause.Occur.MUST);
    } else {
        builder.add(new TermQuery(new Term(key, entry.getValue().toString().toLowerCase())),
                BooleanClause.Occur.MUST);
    }
}
项目:elasticsearch_my    文件:QueryAnalyzerTests.java   
public void testExtractQueryMetadata_unsupportedQuery() {
    TermRangeQuery termRangeQuery = new TermRangeQuery("_field", null, null, true, false);
    UnsupportedQueryException e = expectThrows(UnsupportedQueryException.class, () -> analyze(termRangeQuery));
    assertThat(e.getUnsupportedQuery(), sameInstance(termRangeQuery));

    TermQuery termQuery1 = new TermQuery(new Term("_field", "_term"));
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    builder.add(termQuery1, BooleanClause.Occur.SHOULD);
    builder.add(termRangeQuery, BooleanClause.Occur.SHOULD);
    BooleanQuery bq = builder.build();

    e = expectThrows(UnsupportedQueryException.class, () -> analyze(bq));
    assertThat(e.getUnsupportedQuery(), sameInstance(termRangeQuery));
}
项目:elasticsearch_my    文件:QueryAnalyzerTests.java   
public void testExtractQueryMetadata_unsupportedQueryInBoolQueryWithMustClauses() {
    TermRangeQuery unsupportedQuery = new TermRangeQuery("_field", null, null, true, false);

    TermQuery termQuery1 = new TermQuery(new Term("_field", "_term"));
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    builder.add(termQuery1, BooleanClause.Occur.MUST);
    builder.add(unsupportedQuery, BooleanClause.Occur.MUST);
    BooleanQuery bq1 = builder.build();

    Result result = analyze(bq1);
    assertThat(result.verified, is(false));
    assertTermsEqual(result.terms, termQuery1.getTerm());

    TermQuery termQuery2 = new TermQuery(new Term("_field", "_longer_term"));
    builder = new BooleanQuery.Builder();
    builder.add(termQuery1, BooleanClause.Occur.MUST);
    builder.add(termQuery2, BooleanClause.Occur.MUST);
    builder.add(unsupportedQuery, BooleanClause.Occur.MUST);
    bq1 = builder.build();
    result = analyze(bq1);
    assertThat(result.verified, is(false));
    assertTermsEqual(result.terms, termQuery2.getTerm());

    builder = new BooleanQuery.Builder();
    builder.add(unsupportedQuery, BooleanClause.Occur.MUST);
    builder.add(unsupportedQuery, BooleanClause.Occur.MUST);
    BooleanQuery bq2 = builder.build();
    UnsupportedQueryException e = expectThrows(UnsupportedQueryException.class, () -> analyze(bq2));
    assertThat(e.getUnsupportedQuery(), sameInstance(unsupportedQuery));
}
项目:elasticsearch_my    文件:MapperQueryParser.java   
/**
 * @deprecated review all use of this, don't rely on coord
 */
@Deprecated
protected Query getBooleanQueryCoordDisabled(List<BooleanClause> clauses) throws ParseException {
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    builder.setDisableCoord(true);
    for (BooleanClause clause : clauses) {
        builder.add(clause);
    }
    return fixNegativeQueryIfNeeded(builder.build());
}
项目:elasticsearch_my    文件:MapperQueryParser.java   
@Override
protected Query getBooleanQuery(List<BooleanClause> clauses) throws ParseException {
    Query q = super.getBooleanQuery(clauses);
    if (q == null) {
        return null;
    }
    return fixNegativeQueryIfNeeded(q);
}