Example usage for org.apache.lucene.search BooleanQuery clauses

List of usage examples for org.apache.lucene.search BooleanQuery clauses

Introduction

In this page you can find the example usage for org.apache.lucene.search BooleanQuery clauses.

Prototype

List clauses

To view the source code for org.apache.lucene.search BooleanQuery clauses.

Click Source Link

Usage

From source file:org.apache.solr.search.TestSolrCoreParser.java

License:Apache License

public void testCustomQueryWrapping() throws IOException, ParserException {
    final boolean span = random().nextBoolean();
    // the custom queries
    final String fieldName = "contents";
    final String[] randomTerms = new String[] { "bumble", "honey", "solitary" };
    final String randomQuery = composeChooseOneWordQueryXml(fieldName, randomTerms);
    final String apacheLuceneSolr = "<ApacheLuceneSolr fieldName='" + fieldName + "'/>";
    // the wrapping query
    final String parentQuery = (span ? "SpanOr" : "BooleanQuery");
    final String subQueryPrefix = (span ? "" : "<Clause occurs='must'>");
    final String subQuerySuffix = (span ? "" : "</Clause>");
    final String xml = "<" + parentQuery + ">" + subQueryPrefix + randomQuery + subQuerySuffix + subQueryPrefix
            + apacheLuceneSolr + subQuerySuffix + "</" + parentQuery + ">";
    // the test/*from w ww .j a  v a2  s.  c om*/
    final Query query = parseXmlString(xml);
    if (span) {
        assertTrue(unwrapSpanBoostQuery(query) instanceof SpanOrQuery);
        final SpanOrQuery soq = (SpanOrQuery) unwrapSpanBoostQuery(query);
        assertEquals(2, soq.getClauses().length);
        checkChooseOneWordQuery(span, soq.getClauses()[0], fieldName, randomTerms);
        checkApacheLuceneSolr(soq.getClauses()[1], fieldName);
    } else {
        assertTrue(query instanceof BooleanQuery);
        final BooleanQuery bq = (BooleanQuery) query;
        assertEquals(2, bq.clauses().size());
        checkChooseOneWordQuery(span, bq.clauses().get(0).getQuery(), fieldName, randomTerms);
        checkApacheLuceneSolr(bq.clauses().get(1).getQuery(), fieldName);
    }
}

From source file:org.apache.solr.util.SolrPluginUtils.java

License:Apache License

/**
 * Checks the number of optional clauses in the query, and compares it
 * with the specification string to determine the proper value to use.
 *
 * <p>/*from w  w  w.j a v a2 s.c o m*/
 * Details about the specification format can be found
 * <a href="doc-files/min-should-match.html">here</a>
 * </p>
 *
 * <p>A few important notes...</p>
 * <ul>
 * <li>
 * If the calculations based on the specification determine that no
 * optional clauses are needed, BooleanQuerysetMinMumberShouldMatch
 * will never be called, but the usual rules about BooleanQueries
 * still apply at search time (a BooleanQuery containing no required
 * clauses must still match at least one optional clause)
 * <li>
 * <li>
 * No matter what number the calculation arrives at,
 * BooleanQuery.setMinShouldMatch() will never be called with a
 * value greater then the number of optional clauses (or less then 1)
 * </li>
 * </ul>
 *
 * <p>:TODO: should optimize the case where number is same
 * as clauses to just make them all "required"
 * </p>
 */
public static void setMinShouldMatch(BooleanQuery q, String spec) {

    int optionalClauses = 0;
    for (BooleanClause c : q.clauses()) {
        if (c.getOccur() == Occur.SHOULD) {
            optionalClauses++;
        }
    }

    int msm = calculateMinShouldMatch(optionalClauses, spec);
    if (0 < msm) {
        q.setMinimumNumberShouldMatch(msm);
    }
}

From source file:org.apache.solr.util.SolrPluginUtils.java

License:Apache License

/**
 * Recursively walks the "from" query pulling out sub-queries and
 * adding them to the "to" query./*from  w  w w. ja  v a  2 s .  c o  m*/
 *
 * <p>
 * Boosts are multiplied as needed.  Sub-BooleanQueryies which are not
 * optional will not be flattened.  From will be mangled durring the walk,
 * so do not attempt to reuse it.
 * </p>
 */
public static void flattenBooleanQuery(BooleanQuery to, BooleanQuery from) {

    for (BooleanClause clause : from.clauses()) {

        Query cq = clause.getQuery();
        cq.setBoost(cq.getBoost() * from.getBoost());

        if (cq instanceof BooleanQuery && !clause.isRequired() && !clause.isProhibited()) {

            /* we can recurse */
            flattenBooleanQuery(to, (BooleanQuery) cq);

        } else {
            to.add(clause);
        }
    }
}

From source file:org.apache.solr.util.SolrPluginUtilsTest.java

License:Apache License

@Test
public void testDisjunctionMaxQueryParser() throws Exception {

    Query out;//from   w  ww.j a v a  2  s .  com
    String t;

    SolrQueryRequest req = req();
    QParser qparser = QParser.getParser("hi", "dismax", req);

    DisjunctionMaxQueryParser qp = new SolrPluginUtils.DisjunctionMaxQueryParser(qparser,
            req.getSchema().getDefaultSearchFieldName());

    qp.addAlias("hoss", 0.01f,
            SolrPluginUtils.parseFieldBoosts("title^2.0 title_stemmed name^1.2 subject^0.5"));
    qp.addAlias("test", 0.01f, SolrPluginUtils.parseFieldBoosts("text^2.0"));
    qp.addAlias("unused", 1.0f, SolrPluginUtils.parseFieldBoosts("subject^0.5 sind^1.5"));

    /* first some sanity tests that don't use aliasing at all */

    t = "XXXXXXXX";
    out = qp.parse(t);
    assertNotNull(t + " sanity test gave back null", out);
    assertTrue(t + " sanity test isn't TermQuery: " + out.getClass(), out instanceof TermQuery);
    assertEquals(t + " sanity test is wrong field", h.getCore().getLatestSchema().getDefaultSearchFieldName(),
            ((TermQuery) out).getTerm().field());

    t = "subject:XXXXXXXX";
    out = qp.parse(t);
    assertNotNull(t + " sanity test gave back null", out);
    assertTrue(t + " sanity test isn't TermQuery: " + out.getClass(), out instanceof TermQuery);
    assertEquals(t + " sanity test is wrong field", "subject", ((TermQuery) out).getTerm().field());

    /* field has untokenzied type, so this should be a term anyway */
    t = "sind:\"simple phrase\"";
    out = qp.parse(t);
    assertNotNull(t + " sanity test gave back null", out);
    assertTrue(t + " sanity test isn't TermQuery: " + out.getClass(), out instanceof TermQuery);
    assertEquals(t + " sanity test is wrong field", "sind", ((TermQuery) out).getTerm().field());

    t = "subject:\"simple phrase\"";
    out = qp.parse(t);
    assertNotNull(t + " sanity test gave back null", out);
    assertTrue(t + " sanity test isn't PhraseQuery: " + out.getClass(), out instanceof PhraseQuery);
    assertEquals(t + " sanity test is wrong field", "subject", ((PhraseQuery) out).getTerms()[0].field());

    /* now some tests that use aliasing */

    /* basic usage of single "term" */
    t = "hoss:XXXXXXXX";
    out = qp.parse(t);
    assertNotNull(t + " was null", out);
    assertTrue(t + " wasn't a DMQ:" + out.getClass(), out instanceof DisjunctionMaxQuery);
    assertEquals(t + " wrong number of clauses", 4, countItems(((DisjunctionMaxQuery) out).iterator()));

    /* odd case, but should still work, DMQ of one clause */
    t = "test:YYYYY";
    out = qp.parse(t);
    assertNotNull(t + " was null", out);
    assertTrue(t + " wasn't a DMQ:" + out.getClass(), out instanceof DisjunctionMaxQuery);
    assertEquals(t + " wrong number of clauses", 1, countItems(((DisjunctionMaxQuery) out).iterator()));

    /* basic usage of multiple "terms" */
    t = "hoss:XXXXXXXX test:YYYYY";
    out = qp.parse(t);
    assertNotNull(t + " was null", out);
    assertTrue(t + " wasn't a boolean:" + out.getClass(), out instanceof BooleanQuery);
    {
        BooleanQuery bq = (BooleanQuery) out;
        List<BooleanClause> clauses = bq.clauses();
        assertEquals(t + " wrong number of clauses", 2, clauses.size());
        Query sub = clauses.get(0).getQuery();
        assertTrue(t + " first wasn't a DMQ:" + sub.getClass(), sub instanceof DisjunctionMaxQuery);
        assertEquals(t + " first had wrong number of clauses", 4,
                countItems(((DisjunctionMaxQuery) sub).iterator()));
        sub = clauses.get(1).getQuery();
        assertTrue(t + " second wasn't a DMQ:" + sub.getClass(), sub instanceof DisjunctionMaxQuery);
        assertEquals(t + " second had wrong number of clauses", 1,
                countItems(((DisjunctionMaxQuery) sub).iterator()));
    }

    /* a phrase, and a term that is a stop word for some fields */
    t = "hoss:\"XXXXXX YYYYY\" hoss:the";
    out = qp.parse(t);
    assertNotNull(t + " was null", out);
    assertTrue(t + " wasn't a boolean:" + out.getClass(), out instanceof BooleanQuery);
    {
        BooleanQuery bq = (BooleanQuery) out;
        List<BooleanClause> clauses = bq.clauses();
        assertEquals(t + " wrong number of clauses", 2, clauses.size());
        Query sub = clauses.get(0).getQuery();
        assertTrue(t + " first wasn't a DMQ:" + sub.getClass(), sub instanceof DisjunctionMaxQuery);
        assertEquals(t + " first had wrong number of clauses", 4,
                countItems(((DisjunctionMaxQuery) sub).iterator()));
        sub = clauses.get(1).getQuery();
        assertTrue(t + " second wasn't a DMQ:" + sub.getClass(), sub instanceof DisjunctionMaxQuery);
        assertEquals(t + " second had wrong number of clauses (stop words)", 2,
                countItems(((DisjunctionMaxQuery) sub).iterator()));
    }

}

From source file:org.codelibs.elasticsearch.common.lucene.search.Queries.java

License:Apache License

public static Query applyMinimumShouldMatch(BooleanQuery query, @Nullable String minimumShouldMatch) {
    if (minimumShouldMatch == null) {
        return query;
    }/*w  w  w.ja  v a2 s  .c  o  m*/
    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;
    }
}

From source file:org.codelibs.fess.helper.QueryHelper.java

License:Apache License

protected QueryBuilder convertBooleanQuery(final QueryContext context, final BooleanQuery booleanQuery,
        final float boost) {
    final BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    for (final BooleanClause clause : booleanQuery.clauses()) {
        final QueryBuilder queryBuilder = convertQuery(context, clause.getQuery(), boost);
        if (queryBuilder != null) {
            switch (clause.getOccur()) {
            case MUST:
                boolQuery.must(queryBuilder);
                break;
            case SHOULD:
                boolQuery.should(queryBuilder);
                break;
            case MUST_NOT:
                boolQuery.mustNot(queryBuilder);
                break;
            default:
                break;
            }//from   w ww . j av  a2 s.c  o m
        }
    }
    if (boolQuery.hasClauses()) {
        return boolQuery;
    }
    return null;
}

From source file:org.dice.solrenhancements.morelikethis.MoreLikeThis.java

License:Apache License

private void buildBoostedNormalizedQuery(String fieldName, BooleanQuery tmpQuery, BooleanQuery outQuery,
        double vectorLength, boolean contentStreamQuery) {
    double denominator = (this.isNormalizeFieldBoosts() ? vectorLength : 1.0d);
    float termBoost = 0.0f;
    if (contentStreamQuery) {
        termBoost = this.getStreamFieldBoost(fieldName);
    } else {//ww w.j  a  va  2 s  . com
        termBoost = this.getFieldBoost(fieldName);
    }

    // only add in field boost here as we need to normalize first
    for (BooleanClause clause : tmpQuery.clauses()) {
        Query termQuery = (clause).getQuery();
        // note that this needs to be applied here, so that the length of the query equals the term boost

        Float boost = null;
        if (this.isNormalizeFieldBoosts()) {
            boost = ((float) (termBoost * termQuery.getBoost() / denominator));
        } else {
            boost = termBoost * termQuery.getBoost();
        }
        termQuery.setBoost(boost);
        outQuery.add(termQuery, BooleanClause.Occur.SHOULD);
    }
}

From source file:org.dice.solrenhancements.unsupervisedfeedback.UnsupervisedFeedback.java

License:Apache License

private double buildBoostedNormalizedQuery(String fieldName, BooleanQuery tmpQuery, BooleanQuery outQuery,
        double vectorLength) {
    double denominator = (this.isNormalizeFieldBoosts() ? vectorLength : 1.0d);
    Float termBoost = this.getBoostFields().get(fieldName);
    if (termBoost == null) {
        termBoost = 1.0f;//from   www.j av a  2  s .c  o  m
    }

    double normalizedLength = 0.0f;
    for (BooleanClause clause : tmpQuery.clauses()) {
        Query termQuery = (clause).getQuery();
        // note that this needs to be applied here, so that the length of the query equals the term boost

        Float boost = null;
        if (this.isNormalizeFieldBoosts()) {
            boost = ((float) (termBoost * termQuery.getBoost() / denominator));
        } else {
            boost = termBoost * termQuery.getBoost();
        }
        termQuery.setBoost(boost);
        normalizedLength += boost * boost;
        outQuery.add(termQuery, BooleanClause.Occur.SHOULD);
    }
    normalizedLength = Math.sqrt(normalizedLength);

    return normalizedLength;
}

From source file:org.eclipse.dltk.internal.core.index.lucene.LuceneSearchEngine.java

License:Open Source License

private Query createQuery(final String elementName, final String qualifier, final String parent,
        final int trueFlags, final int falseFlags, final boolean searchForRefs, MatchRule matchRule,
        IDLTKSearchScope scope) {//from w  ww . j  a  va2s .co m
    BooleanQuery query = new BooleanQuery();
    List<String> scripts = SearchScope.getScripts(scope);
    if (!scripts.isEmpty()) {
        BooleanQuery scriptQuery = new BooleanQuery();
        for (String script : scripts) {
            scriptQuery.add(new TermQuery(new Term(F_PATH, script)), Occur.FILTER);
        }
        query.add(scriptQuery, Occur.FILTER);
    }
    if (elementName != null && !elementName.isEmpty()) {
        String elementNameLC = elementName.toLowerCase();
        Query nameQuery = null;
        Term nameCaseInsensitiveTerm = new Term(F_ELEMENT_NAME_LC, elementNameLC);
        if (matchRule == MatchRule.PREFIX) {
            nameQuery = new PrefixQuery(nameCaseInsensitiveTerm);
        } else if (matchRule == MatchRule.EXACT) {
            nameQuery = new TermQuery(nameCaseInsensitiveTerm);
        } else if (matchRule == MatchRule.CAMEL_CASE) {
            String name = Utils.getCamelCaseName(elementName);
            if (name == null) {
                name = elementName;
            }
            nameQuery = new PrefixQuery(new Term(F_CC_NAME, name));
        } else if (matchRule == MatchRule.PATTERN) {
            nameQuery = new WildcardQuery(nameCaseInsensitiveTerm);
        } else {
            throw new UnsupportedOperationException();
        }
        if (nameQuery != null) {
            query.add(nameQuery, Occur.FILTER);
        }
    }
    if (qualifier != null && !qualifier.isEmpty()) {
        query.add(new TermQuery(new Term(F_QUALIFIER, qualifier)), Occur.FILTER);
    }
    if (parent != null && !parent.isEmpty()) {
        query.add(new TermQuery(new Term(F_PARENT, parent)), Occur.FILTER);
    }
    if (trueFlags != 0 || falseFlags != 0) {
        query.add(new BitFlagsQuery(trueFlags, falseFlags), Occur.FILTER);
    }
    return query.clauses().isEmpty() ? null : query;
}

From source file:org.elasticsearch.action.debugquery.QueryToMapTransformer.java

License:Apache License

@Override
public Map visit(BooleanQuery query) throws Exception {
    final Map map = newQuery(query);
    map.put("minShouldMatch", query.getMinimumNumberShouldMatch());
    map.put("coordDisabled", query.isCoordDisabled());
    final ArrayList clauses = new ArrayList(query.clauses().size());
    map.put("clauses", clauses);
    for (final BooleanClause clause : query.clauses()) {
        final Object child = QueryAcceptor.accept(clause.getQuery(), this);
        final Map<String, Object> clauseMap = new LinkedHashMap();
        clauses.add(clauseMap);//w ww .jav  a2  s.  c  o  m
        clauseMap.put("occur", clause.getOccur().name());
        clauseMap.put("query", child);
    }
    return map;
}