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

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

Introduction

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

Prototype

BooleanQuery

Source Link

Usage

From source file:com.esri.gpt.server.assertion.handler.AsnCommentHandler.java

License:Apache License

/**
 * Queries comments.//from  ww w . jav a  2s  . c o m
 * @param context the assertion operation context
 * @throws Exception if an exception occurs
 */
private void query(AsnContext context) throws Exception {

    // initialize
    AsnOperation operation = context.getOperation();
    AsnAssertionSet asnSet = operation.getAssertionSet();
    AsnValueType vType = asnSet.getValueType();
    String subject = operation.getSubject().getURN();
    String predicate = vType.getRdfPredicate();

    // build a query to match all occurrences of the subject/predicate pair
    BooleanQuery query = new BooleanQuery();
    Query qSubject = new TermQuery(new Term(AsnConstants.FIELD_RDF_SUBJECT, subject));
    Query qPredicate = new TermQuery(new Term(AsnConstants.FIELD_RDF_PREDICATE, predicate));
    query.add(qSubject, BooleanClause.Occur.MUST);
    query.add(qPredicate, BooleanClause.Occur.MUST);

    // sort on descending timestamp
    String tsField = AsnConstants.FIELD_SYS_TIMESTAMP;
    Sort sortOption = new Sort(new SortField(tsField, SortField.STRING, true));

    // determine the start and end positions
    int startRecord = context.getRequestOptions().getStartRecord() - 1;
    int maxRecords = context.getRequestOptions().getMaxRecords();
    if (startRecord < 0)
        startRecord = 0;
    int recordsPerPage = maxRecords;
    if (recordsPerPage <= 0)
        recordsPerPage = 1;
    int hitsToReturn = startRecord + recordsPerPage;
    int nextRecord = 0;
    int numDocs = 0;

    IndexReader reader = null;
    IndexSearcher searcher = null;
    try {

        // make the reader and searcher, execute the search
        reader = this.getIndexAdapter().makeIndexReader();
        searcher = new IndexSearcher(reader);
        TopDocs topDocs = searcher.search(query, null, hitsToReturn, sortOption);
        ScoreDoc[] scoreDocs = null;
        int totalHits = topDocs.totalHits;
        if (maxRecords > 0) {
            scoreDocs = topDocs.scoreDocs;
            if ((scoreDocs != null) && (scoreDocs.length) > 0) {
                numDocs = scoreDocs.length;
                if (totalHits > numDocs) {
                    nextRecord = numDocs + 1;
                }
            }
        }

        // root property for the response
        String rootSubject = subject;
        String roorPredicate = operation.getPredicate().getURN() + "response";
        AsnProperty rootProp = new AsnProperty(rootSubject, roorPredicate, null);

        // hit count and next record
        String queryPfx = asnSet.getURNPrefix() + ":query";
        rootProp.getChildren().add(new AsnProperty(null, queryPfx + ":hits", "" + totalHits));
        if (nextRecord > 0) {
            rootProp.getChildren().add(new AsnProperty(null, queryPfx + ":nextRecord", "" + nextRecord));
        }

        // canCreate capability for the active user
        String canCreatePred = asnSet.getURNPrefix() + ":activeUser:canCreate";
        String canCreateVal = "" + context.getAuthorizer().canCreate(context, asnSet.getAuthPolicy());
        rootProp.getChildren().add(new AsnProperty(null, canCreatePred, canCreateVal));

        // process the documents, generate the response
        AsnAssertionRenderer renderer = new AsnAssertionRenderer();
        for (int i = startRecord; i < numDocs; i++) {
            Document document = reader.document(scoreDocs[i].doc);
            Assertion assertion = asnSet.newAssertion(context, false);
            assertion.load(document);
            rootProp.getChildren().add(renderer.makeProperty(context, assertion));
        }
        context.getOperationResponse().generateResponse(context, rootProp.getChildren());

    } finally {
        this.getIndexAdapter().closeReader(reader);
        this.getIndexAdapter().closeSearcher(searcher);
    }

}

From source file:com.esri.gpt.server.assertion.index.AsnIndexAdapter.java

License:Apache License

/**
 * Returns a hit count for a subject, predicate and value combination.
 * <br/>This will only work correctly for values that have not been analyzed 
 * prior to indexing./* w w  w . j  ava  2  s. co  m*/
 * @param context the assertion operation context
 * @param searcher the index searcher
 * @param valueField the value field name
 * @param subject the subject
 * @param predicate the predicate
 * @param value the value
 * @return the cardinality
 * @throws CorruptIndexException if the index is corrupt
 * @throws IOException if an I/O exception occurs
 */
public long count(AsnContext context, IndexSearcher searcher, String valueField, String subject,
        String predicate, String value) throws CorruptIndexException, IOException {

    // build a query to match the subject/predicate/value triple
    BooleanQuery query = new BooleanQuery();
    Query qSubject = new TermQuery(new Term(AsnConstants.FIELD_RDF_SUBJECT, subject));
    Query qPredicate = new TermQuery(new Term(AsnConstants.FIELD_RDF_PREDICATE, predicate));
    Query qValue = new TermQuery(new Term(valueField, value));
    query.add(qSubject, BooleanClause.Occur.MUST);
    query.add(qPredicate, BooleanClause.Occur.MUST);
    query.add(qValue, BooleanClause.Occur.MUST);

    // execute the search, return the hits
    TopDocs topDocs = searcher.search(query, 1);
    return topDocs.totalHits;
}

From source file:com.esri.gpt.server.assertion.index.AsnIndexAdapter.java

License:Apache License

/**
 * Loads the assertion previously cast for the active subject, predicate and user.
 * @param context the assertion operation context
 * @param searcher the index searcher/*from   ww w . j a  v  a2 s  . c  om*/
 * @return the previously cast assertion (can be null)
 * @throws Exception if an exception occurs
 */
public Assertion loadPreviousUserAssertion(AsnContext context, IndexSearcher searcher) throws Exception {
    AsnOperation operation = context.getOperation();
    String userKey = Val.chkStr(operation.getUserPart().getKey());
    String username = Val.chkStr(operation.getUserPart().getName());
    boolean isAnonymous = username.equalsIgnoreCase(AsnConstants.ANONYMOUS_USERNAME);
    if (!isAnonymous && (userKey.length() > 0)) {
        AsnAssertionSet asnSet = operation.getAssertionSet();
        AsnValueType vType = asnSet.getValueType();
        String subject = operation.getSubject().getURN();
        String predicate = vType.getRdfPredicate();

        // build a query to match the subject/predicate/user triple
        BooleanQuery query = new BooleanQuery();
        Query qSubject = new TermQuery(new Term(AsnConstants.FIELD_RDF_SUBJECT, subject));
        Query qPredicate = new TermQuery(new Term(AsnConstants.FIELD_RDF_PREDICATE, predicate));
        Query qUserKey = new TermQuery(new Term(AsnConstants.FIELD_USER_KEY, userKey));
        query.add(qSubject, BooleanClause.Occur.MUST);
        query.add(qPredicate, BooleanClause.Occur.MUST);
        query.add(qUserKey, BooleanClause.Occur.MUST);

        // make the reader and searcher, execute the search, return the previous assertion
        TopDocs topDocs = searcher.search(query, 1);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        if ((scoreDocs != null) && (scoreDocs.length) > 0) {
            Document document = searcher.getIndexReader().document(scoreDocs[0].doc);
            Assertion assertion = asnSet.newAssertion(context, false);
            assertion.load(document);
            return assertion;
        }
    }
    return null;
}

From source file:com.ewcms.content.document.util.analyzer.lucene.IKQueryParser.java

License:Open Source License

/**
 * query/*from   www  .j a  v a  2  s  .c o  m*/
 * ?Query?
 * @param queries
 * @return
 */
private static Query optimizeQueries(List<Query> queries) {
    //??branch query
    if (queries.size() == 0) {
        return null;
    } else if (queries.size() == 1) {
        return queries.get(0);
    } else {
        BooleanQuery mustQueries = new BooleanQuery();
        for (Query q : queries) {
            mustQueries.add(q, Occur.MUST);
        }
        return mustQueries;
    }
}

From source file:com.ewcms.content.document.util.analyzer.lucene.IKQueryParser.java

License:Open Source License

/**
/**//  ww w .  j ava 2s  .  c  om
 * ??,?Field?
 * @param field -- Document field name
 * @param query -- keyword
 * @return Query 
 * @throws IOException
 */
public static Query parse(String field, String query) throws IOException {
    if (field == null) {
        throw new IllegalArgumentException("parameter \"field\" is null");
    }
    String[] qParts = query.split("\\s");
    if (qParts.length > 1) {
        BooleanQuery resultQuery = new BooleanQuery();
        for (String q : qParts) {
            //?
            if ("".equals(q)) {
                continue;
            }
            Query partQuery = _parse(field, q);
            if (partQuery != null && (!(partQuery instanceof BooleanQuery)
                    || ((BooleanQuery) partQuery).getClauses().length > 0)) {
                resultQuery.add(partQuery, Occur.SHOULD);
            }
        }
        return resultQuery;
    } else {
        return _parse(field, query);
    }
}

From source file:com.ewcms.content.document.util.analyzer.lucene.IKQueryParser.java

License:Open Source License

/**
 * Field,???/*from  ww w.ja  v a2 s  . c  om*/
 * @param fields -- Document fields name
 * @param query   -- keyword
 * @return Query 
 * @throws IOException
 */
public static Query parseMultiField(String[] fields, String query) throws IOException {
    if (fields == null) {
        throw new IllegalArgumentException("parameter \"fields\" is null");
    }
    BooleanQuery resultQuery = new BooleanQuery();
    for (String field : fields) {
        if (field != null) {
            Query partQuery = parse(field, query);
            if (partQuery != null && (!(partQuery instanceof BooleanQuery)
                    || ((BooleanQuery) partQuery).getClauses().length > 0)) {
                resultQuery.add(partQuery, Occur.SHOULD);
            }
        }
    }
    return resultQuery;
}

From source file:com.ewcms.content.document.util.analyzer.lucene.IKQueryParser.java

License:Open Source License

/**
 * Field,??,Occur?/*from   w ww .j av a 2 s  .  c  om*/
 * @param fields -- Document fields name
 * @param query   -- keyword
 * @param flags -- BooleanClause
 * @return Query 
 * @throws IOException
 */
public static Query parseMultiField(String[] fields, String query, BooleanClause.Occur[] flags)
        throws IOException {
    if (fields == null) {
        throw new IllegalArgumentException("parameter \"fields\" is null");
    }
    if (flags == null) {
        throw new IllegalArgumentException("parameter \"flags\" is null");
    }

    if (flags.length != fields.length) {
        throw new IllegalArgumentException("flags.length != fields.length");
    }

    BooleanQuery resultQuery = new BooleanQuery();
    for (int i = 0; i < fields.length; i++) {
        if (fields[i] != null) {
            Query partQuery = parse(fields[i], query);
            if (partQuery != null && (!(partQuery instanceof BooleanQuery)
                    || ((BooleanQuery) partQuery).getClauses().length > 0)) {
                resultQuery.add(partQuery, flags[i]);
            }
        }
    }
    return resultQuery;
}

From source file:com.ewcms.content.document.util.analyzer.lucene.IKQueryParser.java

License:Open Source License

/**
 * Field??// w  ww  . j  av a2  s.com
 * @param fields
 * @param queries
 * @return Query 
 * @throws IOException 
 */
public static Query parseMultiField(String[] fields, String[] queries) throws IOException {
    if (fields == null) {
        throw new IllegalArgumentException("parameter \"fields\" is null");
    }
    if (queries == null) {
        throw new IllegalArgumentException("parameter \"queries\" is null");
    }
    if (queries.length != fields.length) {
        throw new IllegalArgumentException("queries.length != fields.length");
    }
    BooleanQuery resultQuery = new BooleanQuery();
    for (int i = 0; i < fields.length; i++) {
        if (fields[i] != null) {
            Query partQuery = parse(fields[i], queries[i]);
            if (partQuery != null && (!(partQuery instanceof BooleanQuery)
                    || ((BooleanQuery) partQuery).getClauses().length > 0)) {
                resultQuery.add(partQuery, Occur.SHOULD);
            }
        }
    }
    return resultQuery;
}

From source file:com.ewcms.content.document.util.analyzer.lucene.IKQueryParser.java

License:Open Source License

/**
 * Field,?,Occur?/*from   w  w w  .  j av  a 2 s.c  o  m*/
 * @param fields
 * @param queries
 * @param flags
 * @return Query 
 * @throws IOException
 */
public static Query parseMultiField(String[] fields, String[] queries, BooleanClause.Occur[] flags)
        throws IOException {
    if (fields == null) {
        throw new IllegalArgumentException("parameter \"fields\" is null");
    }
    if (queries == null) {
        throw new IllegalArgumentException("parameter \"queries\" is null");
    }
    if (flags == null) {
        throw new IllegalArgumentException("parameter \"flags\" is null");
    }

    if (!(queries.length == fields.length && queries.length == flags.length)) {
        throw new IllegalArgumentException("queries, fields, and flags array have have different length");
    }

    BooleanQuery resultQuery = new BooleanQuery();
    for (int i = 0; i < fields.length; i++) {
        if (fields[i] != null) {
            Query partQuery = parse(fields[i], queries[i]);
            if (partQuery != null && (!(partQuery instanceof BooleanQuery)
                    || ((BooleanQuery) partQuery).getClauses().length > 0)) {
                resultQuery.add(partQuery, flags[i]);
            }
        }
    }
    return resultQuery;
}

From source file:com.flaptor.hounder.searcher.query.AndQuery.java

License:Apache License

@Override
public org.apache.lucene.search.Query getLuceneQuery() {
    BooleanQuery bq = new BooleanQuery();
    if (leftTerm instanceof AndQuery) {
        for (BooleanClause bc : ((BooleanQuery) leftTerm.getLuceneQuery()).getClauses()) {
            bq.add(bc);/*ww  w . ja v  a 2 s  . c  o m*/
        }
    } else {
        bq.add(leftTerm.getLuceneQuery(), BooleanClause.Occur.MUST);
    }
    if (rightTerm instanceof AndQuery) {
        for (BooleanClause bc : ((BooleanQuery) rightTerm.getLuceneQuery()).getClauses()) {
            bq.add(bc);
        }
    } else {
        bq.add(rightTerm.getLuceneQuery(), BooleanClause.Occur.MUST);
    }

    bq.setBoost(boost);
    return bq;
}