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.epimorphics.registry.store.StoreBaseImpl.java

License:Apache License

@Override
public LuceneResult[] search(String query, int offset, int maxresults, String... fields) {
    if (indexer != null) {
        Analyzer analyzer = new StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_40);
        QueryParser parser = new QueryParser(org.apache.lucene.util.Version.LUCENE_40, LuceneIndex.FIELD_LABEL,
                analyzer);//from   w w w  . j a v a 2  s .c  o  m
        Query search;
        try {
            search = parser.parse(query);
        } catch (ParseException e) {
            throw new WebApiException(BAD_REQUEST, "Could not parse query: " + e.getMessage());
        }
        if (fields.length != 0) {
            BooleanQuery bq = new BooleanQuery();
            for (int i = 0; i < fields.length;) {
                String key = SearchTagname.expandKey(fields[i++]);
                if (i >= fields.length) {
                    throw new EpiException("Odd number of fields in search call");
                }
                String value = fields[i++];
                Term t = new Term(key, value);
                bq.add(new TermQuery(t), BooleanClause.Occur.MUST);
            }
            bq.add(search, BooleanClause.Occur.MUST);
            search = bq;
        }

        LuceneIndex index = (LuceneIndex) indexer;
        if (Registry.TEXT_INDEX_INCLUDES_HISTORY) {
            return SearchFilter.search(index, search, offset, maxresults);
        } else {
            return index.search(search, offset, maxresults);
        }
    } else {
        return new LuceneResult[0];
    }
}

From source file:com.esri.gpt.catalog.lucene.LogicalClauseAdapter.java

License:Apache License

/**
 * Builds a Lucene BooleanQuery by recursively traversing a
 * catalog discovery LogicalClause.//ww  w.  j av a2s . c  om
 * @param activeBooleanQuery the active Lucene boolean query
 * @param logicalClause the logical clause to adapt
 * @throws DiscoveryException if an invalid clause is encountered
 * @throws ParseException if a Lucene query parsing exception occurs
 */
protected void adaptLogicalClause(BooleanQuery activeBooleanQuery, LogicalClause logicalClause)
        throws DiscoveryException, ParseException {

    // loop the the sub clauses, recurse any logical clauses
    for (DiscoveryClause clause : logicalClause.getClauses()) {
        if (clause == null) {
            throw new DiscoveryException("A null clause was encountered.");

        } else if (clause instanceof LogicalClause) {
            BooleanQuery subQuery = new BooleanQuery();
            appendQuery(activeBooleanQuery, logicalClause, subQuery);
            adaptLogicalClause(subQuery, (LogicalClause) clause);

        } else if (clause instanceof PropertyClause) {
            PropertyClauseAdapter adapter = new PropertyClauseAdapter(getQueryAdapter());
            PropertyClause subClause = (PropertyClause) clause;
            adapter.adaptPropertyClause(activeBooleanQuery, logicalClause, subClause);

        } else if (clause instanceof SpatialClause) {
            SpatialClauseAdapter adapter = new SpatialClauseAdapter(getQueryAdapter());
            SpatialClause subClause = (SpatialClause) clause;
            adapter.adaptSpatialClause(activeBooleanQuery, logicalClause, subClause);

        } else {
            String sErr = "Unrecognized clause type:" + clause.getClass().getName();
            throw new DiscoveryException(sErr);
        }
    }

    // MUST_NOT causes a problem when there is only one MUST_NOT clause within 
    // a BooleanQuery, to get round it we add all documents as a SHOULD
    BooleanClause[] clauses = activeBooleanQuery.getClauses();
    if ((clauses == null) || (clauses.length == 0)) {
        // TODO this will result in no records being returned,
        // possible this should be fixed
    } else if (clauses.length == 1) {
        if (clauses[0].getOccur().equals(BooleanClause.Occur.MUST_NOT)) {
            LOGGER.finer("Fixing single MUST_NOT clause within a BooleanQuery...");
            appendSelectAll(activeBooleanQuery);
        }
    }
}

From source file:com.esri.gpt.catalog.lucene.LuceneQueryAdapter.java

License:Apache License

/**
 * Executes a query against a Lucene index.
 * @param discoveryQuery the query to execute
 *//*from ww  w  .j a v a 2s . c  om*/
protected void executeQuery(DiscoveryQuery discoveryQuery)
        throws DiscoveryException, ParseException, CorruptIndexException, IOException {

    IndexSearcher searcher = null;
    try {

        // initialize
        searcher = getIndexAdapter().newSearcher();
        this.maxDoc = searcher.maxDoc();
        boolean bExecuteQuery = true;
        boolean bProcessHits = true;
        RequestContext reqContext = this.getIndexAdapter().getRequestContext();
        BooleanQuery rootQuery = new BooleanQuery();
        DiscoveryFilter discoveryFilter = discoveryQuery.getFilter();
        DiscoveryResult discoveryResult = discoveryQuery.getResult();
        Discoverables returnables = discoveryQuery.getReturnables();
        if ((returnables == null) || (returnables.size() == 0) || (discoveryFilter.getMaxRecords() <= 0)) {
            bProcessHits = false;
        }

        // CSW query provider options
        boolean isDublinCoreResponse = true;
        boolean isBriefResponse = false;
        boolean isSummaryResponse = false;
        QueryOptions cswQueryOptions = (QueryOptions) reqContext.getObjectMap()
                .get("com.esri.gpt.server.csw.provider.components.QueryOptions");

        // build the query (if no query was supplied, we'll query everything)
        LogicalClauseAdapter logicalAdapter = new LogicalClauseAdapter(this);
        LogicalClause rootClause = discoveryFilter.getRootClause();
        if ((rootClause == null) || (rootClause.getClauses().size() == 0)) {
            if (discoveryFilter.getMaxRecords() <= QUERYALL_THRESHOLD) {
                LOGGER.finer("No filter was supplied, querying all...");
                logicalAdapter.appendSelectAll(rootQuery);
            } else {
                LOGGER.finer("No filter was supplied, query will not be executed.");
                bExecuteQuery = false;
            }
        } else {
            logicalAdapter.adaptLogicalClause(rootQuery, rootClause);
            if ((rootQuery.clauses() == null) && (rootQuery.clauses().size() > 0)) {
                bExecuteQuery = false;
            }
        }
        if (!bExecuteQuery)
            return;

        // execute the query and process the hits if required

        // set the sort option
        Sort sortOption = null;
        if (bProcessHits && (searcher.maxDoc() > 0)) {
            sortOption = makeSortOption(discoveryQuery);
        }

        // filters
        Filter filter = null;

        // make the access control filter
        MetadataAcl acl = new MetadataAcl(reqContext);
        AuthenticationStatus auth = reqContext.getUser().getAuthenticationStatus();
        boolean bAdmin = auth.getAuthenticatedRoles().hasRole("gptAdministrator");
        if (!bAdmin && !acl.isPolicyUnrestricted()) {
            String[] aclValues = acl.makeUserAcl();
            filter = new AclFilter(Storeables.FIELD_ACL, aclValues);
        }

        // isPartOf filter
        filter = IsPartOfFilter.make(reqContext, filter);

        // make the schema filter
        if (cswQueryOptions != null) {
            String schemaName = Val.chkStr(cswQueryOptions.getSchemaFilter());
            if (schemaName.length() > 0) {
                filter = new SchemaFilter(schemaName, filter);
                isDublinCoreResponse = cswQueryOptions.isDublinCoreResponse();
                if (!isDublinCoreResponse) {
                    String elementSetType = Val.chkStr(cswQueryOptions.getElementSetType());
                    if (elementSetType.equalsIgnoreCase("brief")) {
                        isBriefResponse = true;
                    } else if (elementSetType.equalsIgnoreCase("summary")) {
                        isSummaryResponse = true;
                    }
                }
            }
        }

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

        // execute the query 
        LOGGER.finer("Executing Lucene Query:\n" + rootQuery);
        TopDocs topDocs = null;
        if (filter != null) {
            if (sortOption != null) {
                topDocs = searcher.search(rootQuery, filter, hitsToReturn, sortOption);
            } else {
                topDocs = searcher.search(rootQuery, filter, hitsToReturn);
            }
        } else {
            if (sortOption != null) {
                topDocs = searcher.search(rootQuery, filter, hitsToReturn, sortOption);
            } else {
                topDocs = searcher.search(rootQuery, hitsToReturn);
            }
        }

        // determine the hit count
        int totalHits = topDocs.totalHits;
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        if ((scoreDocs != null) && (scoreDocs.length) > 0) {
            numDocs = scoreDocs.length;
            if (totalHits > numDocs) {
                nextRecord = numDocs + 1;
            }
        }
        discoveryResult.setNumberOfHits(totalHits);
        LOGGER.finer("Total query hits: " + totalHits);

        if (startRecord > (totalHits - 1))
            bProcessHits = false;
        if (maxRecords <= 0)
            bProcessHits = false;
        int nTotal = numDocs - startRecord;
        if (!bProcessHits)
            return;

        // warn if many records were requested
        if (nTotal >= TOOMANY_WARNING_THRESHOLD) {
            LOGGER.warning("A request to process " + nTotal
                    + " discovery records was recieved and will be exceuted.\n" + discoveryQuery.toString());
        }

        // process the hits, build the results
        LOGGER.finer("Processing " + nTotal + " records from: " + (startRecord + 1) + " to: " + numDocs);
        Storeable storeable;
        DiscoveredRecords records = discoveryResult.getRecords();
        IndexReader reader = searcher.getIndexReader();
        for (int i = startRecord; i < numDocs; i++) {
            ScoreDoc scoreDoc = scoreDocs[i];
            Document document = reader.document(scoreDoc.doc);
            DiscoveredRecord record = new DiscoveredRecord();

            // Dublin Core based responses
            if (isDublinCoreResponse) {
                for (Discoverable target : returnables) {
                    ArrayList<Object> values = new ArrayList<Object>();
                    storeable = (Storeable) target.getStorable();

                    if (storeable instanceof AnyTextProperty) {
                        values = null;

                    } else if (storeable instanceof GeometryProperty) {
                        GeometryProperty geom = (GeometryProperty) storeable;
                        values.add(geom.readEnvelope(document));

                    } else if (target.getMeaning().getMeaningType().equals(PropertyMeaningType.XMLURL)) {
                        String uuid = document.get(Storeables.FIELD_UUID);
                        uuid = URLEncoder.encode(uuid, "UTF-8");
                        values.add("?getxml=" + uuid);

                    } else {
                        DatastoreField retrievalField = storeable.getRetrievalField();
                        Field[] fields = document.getFields(retrievalField.getName());
                        if (fields != null) {
                            for (Field f : fields) {
                                Object value = retrievalField.makeValueToReturn(f.stringValue());
                                values.add(value);
                            }
                        }
                    }

                    if (values != null) {
                        Object[] oValues = null;
                        if (values.size() >= 0)
                            oValues = values.toArray();
                        record.addField(target, oValues);
                    }
                }

                // non Dublin Core based responses
            } else {
                String responseXml = null;
                if (isBriefResponse && (responseXml == null)) {
                    Field field = document.getField(Storeables.FIELD_XML_BRIEF);
                    if (field != null) {
                        responseXml = field.stringValue();
                    }
                } else if (isSummaryResponse && (responseXml == null)) {
                    Field field = document.getField(Storeables.FIELD_XML_SUMMARY);
                    if (field != null) {
                        responseXml = field.stringValue();
                    }
                } else if (responseXml == null) {
                    Field field = document.getField(Storeables.FIELD_XML);
                    if (field != null) {
                        responseXml = field.stringValue();
                    }
                }
                record.setResponseXml(responseXml);
            }

            records.add(record);
        }
        int nPopulated = records.size();
        LOGGER.finer("Populated " + nPopulated + " records.");

    } finally {
        getIndexAdapter().closeSearcher(searcher);
    }
}

From source file:com.esri.gpt.catalog.lucene.PropertyClauseAdapter.java

License:Apache License

/**
 * Appends a range query to the active boolean query.
 * @param activeBooleanQuery the active Lucene boolean query
 * @param activeLogicalClause the active discovery logical clause
 * @param propertyClause the active property clause
 * @param lowerBoundary the lower boundary
 * @param upperBoundary the upper boundary
 * @param lowerBoundaryIsInclusive (>= versus >)
 * @param upperBoundaryIsInclusive (<= versus <)
 * @throws DiscoveryException if an invalid clause is encountered
 *//*from  ww w  . j a v a  2s . c  om*/
private void appendRange(BooleanQuery activeBooleanQuery, LogicalClause activeLogicalClause,
        PropertyClause propertyClause, String lowerBoundary, String upperBoundary,
        boolean lowerBoundaryIsInclusive, boolean upperBoundaryIsInclusive) throws DiscoveryException {
    boolean standard = true;

    // there is a circumstance where a query for data valid within a range is split across 2 fields
    String fieldName = this.comparisonField.getName();
    if ((fieldName != null) && fieldName.equals("dateValidStart") && (upperBoundary != null)) {
        if (lowerBoundary == null) {
            standard = false;
            TimestampField tsEnd = new TimestampField("dateValidEnd");
            Query query = tsEnd.makeRangeQuery(lowerBoundary, upperBoundary, lowerBoundaryIsInclusive,
                    upperBoundaryIsInclusive);
            appendQuery(activeBooleanQuery, activeLogicalClause, query);
        } else if (!lowerBoundary.equals(upperBoundary)) {
            standard = false;
            TimestampField tsEnd = new TimestampField("dateValidEnd");
            Query q1 = this.comparisonField.makeRangeQuery(lowerBoundary, null, lowerBoundaryIsInclusive,
                    false);
            Query q2 = tsEnd.makeRangeQuery(null, upperBoundary, false, upperBoundaryIsInclusive);
            BooleanQuery bq = new BooleanQuery();
            bq.add(q1, BooleanClause.Occur.MUST);
            bq.add(q2, BooleanClause.Occur.MUST);
            this.appendQuery(activeBooleanQuery, activeLogicalClause, bq);
            return;
        }
    }

    // standard methodology
    if (standard) {
        Query query = this.comparisonField.makeRangeQuery(lowerBoundary, upperBoundary,
                lowerBoundaryIsInclusive, upperBoundaryIsInclusive);
        appendQuery(activeBooleanQuery, activeLogicalClause, query);
    }
}

From source file:com.esri.gpt.catalog.lucene.PropertyClauseAdapter.java

License:Apache License

/**
 * Adapts a property clause requiring an comparison field expression
 * to the Lucene model.//  w  w  w.j  av a 2  s. co m
 * @param activeBooleanQuery the active Lucene boolean query
 * @param activeLogicalClause the active discovery logical clause
 * @param propertyClause the property clause to adapt
 * @throws DiscoveryException if an invalid clause is encountered
 */
private void handleComparisonClause(BooleanQuery activeBooleanQuery, LogicalClause activeLogicalClause,
        PropertyClause propertyClause) throws DiscoveryException {
    String fieldName = this.comparisonField.getName();
    String literal = propertyClause.getLiteral();

    // handle each operation 

    if (propertyClause instanceof PropertyIsBetween) {
        PropertyIsBetween between = (PropertyIsBetween) propertyClause;
        String lower = between.getLowerBoundary();
        String upper = between.getUpperBoundary();
        appendRange(activeBooleanQuery, activeLogicalClause, propertyClause, lower, upper, true, true);

    } else if (propertyClause instanceof PropertyIsEqualTo) {
        boolean checkFID = fieldName.equalsIgnoreCase(Storeables.FIELD_UUID) && (literal != null)
                && (literal.length() > 0);
        if (checkFID) {
            String id = literal;
            Query q1 = new TermRangeQuery(fieldName, id, id, true, true);
            Query q2 = new TermRangeQuery(Storeables.FIELD_FID, id, id, true, true);
            BooleanQuery bq = new BooleanQuery();
            bq.add(q1, BooleanClause.Occur.SHOULD);
            bq.add(q2, BooleanClause.Occur.SHOULD);
            appendQuery(activeBooleanQuery, activeLogicalClause, bq);

        } else {
            appendRange(activeBooleanQuery, activeLogicalClause, propertyClause, literal, literal, true, true);
        }

    } else if (propertyClause instanceof PropertyIsGreaterThan) {
        appendRange(activeBooleanQuery, activeLogicalClause, propertyClause, literal, null, false, false);

    } else if (propertyClause instanceof PropertyIsGreaterThanOrEqualTo) {
        appendRange(activeBooleanQuery, activeLogicalClause, propertyClause, literal, null, true, false);

    } else if (propertyClause instanceof PropertyIsLessThan) {
        appendRange(activeBooleanQuery, activeLogicalClause, propertyClause, null, literal, false, false);

    } else if (propertyClause instanceof PropertyIsLessThanOrEqualTo) {
        appendRange(activeBooleanQuery, activeLogicalClause, propertyClause, null, literal, false, true);

    } else if (propertyClause instanceof PropertyIsNotEqualTo) {
        appendRange(activeBooleanQuery, new LogicalClause.LogicalNot(), propertyClause, literal, literal, true,
                true);

    } else if (propertyClause instanceof PropertyIsNull) {
        appendNullCheck(activeBooleanQuery, fieldName);

    } else {
        String sErr = "Unrecognized property clause type: ";
        throw new DiscoveryException(sErr + propertyClause.getClass().getName());
    }

}

From source file:com.esri.gpt.catalog.lucene.QueryProvider.java

License:Apache License

/**
 * Gets a simple query./*www  .  j  av  a 2 s. co  m*/
 * @param field field name
 * @param queryText query text
 * @param slop slop
 * @return query or <code>null</code> if query for the particular field is unavailable
 * @throws ParseException if error creating query
 */
protected Query getFieldQuery(String field, String queryText, int slop) throws ParseException {
    Query q = null;
    PropertyMeaning meaning = resolveMeaning(field);
    if (meaning != null) {
        PropertyComparisonType type = meaning.getComparisonType();

        if (type == PropertyComparisonType.KEYWORD) {
            q = new TermQuery(new Term(field, Val.chkStr(queryText).toLowerCase()));
        }
        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.STRING) {
            q = new TermQuery(new Term(field, queryText));
        }
        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.LONG) {
            try {
                LongField lgField = new LongField(field);
                queryText = lgField.makeValueToQuery(queryText, false, false);
                q = new TermQuery(new Term(field, queryText));
            } catch (DiscoveryException ex) {
                throw new ParseException("Error parsing expression: " + ex.getMessage());
            }
        }
        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.DOUBLE) {
            try {
                DoubleField lgField = new DoubleField(field, DoubleField.DEFAULT_PRECISION);
                queryText = lgField.makeValueToQuery(queryText, false, false);
                q = new TermQuery(new Term(field, queryText));
            } catch (DiscoveryException ex) {
                throw new ParseException("Error parsing expression: " + ex.getMessage());
            }
            q = new TermQuery(new Term(field, queryText));
        }

        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.TIMESTAMP) {
            try {
                if (isFullDate(queryText)) { // check if is this a full index date format?
                    TimestampField tsField = new TimestampField(field);
                    queryText = tsField.makeValueToQuery(queryText, true, false);
                    q = new TermQuery(new Term(field, queryText));
                } else {
                    q = (new TimestampField(field)).makeRangeQuery(queryText, queryText, true, true);
                }
            } catch (DiscoveryException ex) {
                throw new ParseException("Error parsing expression: " + ex.getMessage());
            }
        }

        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.GEOMETRY) {
            try {
                // create locator
                Locator locator = Locator.newInstance();
                // find best candidate
                Locator.Candidate bestCandidate = locator.findBestCandidate(locator.find(queryText));
                // create query if best candidate found
                if (bestCandidate != null) {
                    double dif = 0.1;
                    // create query
                    BooleanQuery rootQuery = new BooleanQuery();
                    // create spatial
                    SpatialClause spatialClause = createSpatialClause(meaning, true);
                    // parse and set boounding box
                    spatialClause.getBoundingEnvelope().setMinX(bestCandidate.getLocation()[0] - dif);
                    spatialClause.getBoundingEnvelope().setMinY(bestCandidate.getLocation()[1] - dif);
                    spatialClause.getBoundingEnvelope().setMaxX(bestCandidate.getLocation()[0] + dif);
                    spatialClause.getBoundingEnvelope().setMaxY(bestCandidate.getLocation()[1] + dif);
                    // combine all together usingspatial clause adapter
                    SpatialClauseAdapter spatialClauseAdapter = new SpatialClauseAdapter(
                            getLuceneQueryAdapter());
                    spatialClauseAdapter.adaptSpatialClause(rootQuery, new LogicalClause.LogicalAnd(),
                            spatialClause);
                    // assign output
                    q = rootQuery;
                }
            } catch (Exception ex) {
                throw new ParseException("Error parsing expression: " + ex.getMessage());
            }
        }
    }

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("QueryProvider.getFieldQuery(" + field + "," + queryText + "," + slop + ") -> " + q);
    }
    return q;
}

From source file:com.esri.gpt.catalog.lucene.QueryProvider.java

License:Apache License

/**
 * Gets range query.//from  w  w  w.j av a 2s  .c om
 * @param field field name
 * @param part1 first part of the range
 * @param part2 second part of the range
 * @param inclusive <code>true</code> for inclusive search
 * @return query or <code>null</code> if query for the particular field is unavailable
 * @throws ParseException if error creating query
 */
protected Query getRangeQuery(String field, String part1, String part2, boolean inclusive)
        throws ParseException {
    Query q = null;
    PropertyMeaning meaning = resolveMeaning(field);
    if (meaning != null) {
        PropertyComparisonType type = meaning.getComparisonType();

        if (type == PropertyComparisonType.KEYWORD) {
            q = newRangeQuery(field, Val.chkStr(part1).toLowerCase(), Val.chkStr(part2).toLowerCase(),
                    inclusive);
        }
        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.STRING) {
            q = newRangeQuery(field, part1, part2, inclusive);
        }
        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.GEOMETRY) {
            try {
                // create query
                BooleanQuery rootQuery = new BooleanQuery();
                // create spatial
                SpatialClause spatialClause = createSpatialClause(meaning, inclusive);
                // parse and set bounding box
                parseEnvelope(spatialClause.getBoundingEnvelope(), part1, part2);
                // combine all together using spatial clause adapter
                SpatialClauseAdapter spatialClauseAdapter = new SpatialClauseAdapter(getLuceneQueryAdapter());
                spatialClauseAdapter.adaptSpatialClause(rootQuery, new LogicalClause.LogicalAnd(),
                        spatialClause);
                // assign output
                q = rootQuery;
            } catch (DiscoveryException ex) {
                throw new ParseException("Error parsing expression: " + ex.getMessage());
            }
        }
        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.TIMESTAMP) {
            try {
                q = (new TimestampField(field)).makeRangeQuery(part1, part2, inclusive, inclusive);
            } catch (DiscoveryException ex) {
                throw new ParseException("Error parsing expression: " + ex.getMessage());
            }
        }
        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.LONG) {
            try {
                q = (new LongField(field)).makeRangeQuery(part1, part2, inclusive, inclusive);
            } catch (DiscoveryException ex) {
                throw new ParseException("Error parsing expression: " + ex.getMessage());
            }
        }
        if (type == PropertyComparisonType.VALUE && meaning.getValueType() == PropertyValueType.DOUBLE) {
            try {
                q = (new LongField(field)).makeRangeQuery(part1, part2, inclusive, inclusive);
            } catch (DiscoveryException ex) {
                throw new ParseException("Error parsing expression: " + ex.getMessage());
            }
        }
    } else if (field != null) {
        q = newRangeQuery(field, part1, part2, inclusive);
    }

    if (q == null) {
        List clauses = new ArrayList();
        for (int i = 0; i < getFields().length; i++) {
            clauses.add(new BooleanClause(getRangeQuery(getFields()[i], part1, part2, inclusive),
                    BooleanClause.Occur.SHOULD));
        }
        q = newBooleanQuery(clauses, true);
    }

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("QueryProvider.getRangeQuery(" + field + "," + part1 + "," + part2 + "," + inclusive
                + ") -> " + q);
    }
    return q;
}

From source file:com.esri.gpt.catalog.lucene.SpatialClauseAdapter.java

License:Apache License

/**
 * Adapts a catalog discovery SpatialClause to the Lucene model.
 * @param activeBooleanQuery the active Lucene boolean query
 * @param activeLogicalClause the active discovery logical clause
 * @param spatialClause the spatial clause to adapt
 * @throws DiscoveryException if an invalid clause is encountered
 *///from  w w w. j a v a  2s .c  om
protected void adaptSpatialClause(BooleanQuery activeBooleanQuery, LogicalClause activeLogicalClause,
        SpatialClause spatialClause) throws DiscoveryException {
    LOGGER.finer("Adapting SpatialClause...\n" + spatialClause);

    // determine the discoverable target, set names
    String sErr;
    Discoverable discoverable = spatialClause.getTarget();
    if (discoverable == null) {
        sErr = "The SpatialClause.target is null.";
        throw new DiscoveryException(sErr);
    }
    if (discoverable.getStorable() == null) {
        sErr = "The SpatialClause.target.storeable is null.";
        throw new DiscoveryException(sErr);
    } else {
        Storeable storeable = (Storeable) discoverable.getStorable();
        if (!(storeable instanceof GeometryProperty)) {
            sErr = "The SpatialClause.target.storeable is not a GeometryProperty.";
            throw new DiscoveryException(sErr);
        }
    }

    // check the envelope
    envelope = spatialClause.getBoundingEnvelope();
    if ((envelope == null) || envelope.isEmpty()) {
        sErr = "The SpatialClause.boundingEnvelope is empty.";
        throw new DiscoveryException(sErr);
    }

    // initialize the values of the input query envelope
    qryMinX = envelope.getMinX();
    qryMinY = envelope.getMinY();
    qryMaxX = envelope.getMaxX();
    qryMaxY = envelope.getMaxY();
    if (qryMinX > qryMaxX) {
        qryCrossedDateline = true;
    }

    // determine spatialRelevance parameters 
    // (original defaults were queryPower=2.0, targetPower=0.5)
    RequestContext rc = this.getQueryAdapter().getIndexAdapter().getRequestContext();
    StringAttributeMap params = rc.getCatalogConfiguration().getParameters();
    double queryPower = Val.chkDbl(params.getValue("spatialRelevance.queryPower"), 1.0);
    double targetPower = Val.chkDbl(params.getValue("spatialRelevance.targetPower"), 1.0);
    String rankingOption = Val.chkStr(params.getValue("spatialRelevance.ranking.enabled"));
    int rankingMaxDoc = Val.chkInt(params.getValue("spatialRelevance.ranking.maxDoc"), 50000);
    boolean bUseSpatialRanking = false;
    if (rankingOption.equalsIgnoreCase("true")) {
        bUseSpatialRanking = true;
    } else if (rankingOption.equalsIgnoreCase("false")) {
        bUseSpatialRanking = false;
    } else {

        // default spatialRelevance.ranking.enabled option is "auto"
        if (this.getQueryAdapter() != null) {
            int maxDoc = this.getQueryAdapter().getMaxDoc();
            if ((maxDoc > 0) && (maxDoc <= rankingMaxDoc)) {
                bUseSpatialRanking = true;
            }
        }
    }

    // Handle each operation - Beyond, Crosses, DWithin and Touches are not implemented

    if (bUseSpatialRanking) {
        Query spatialQuery = null;
        if (spatialClause instanceof SpatialClause.GeometryBBOXIntersects) {
            spatialQuery = this.makeIntersects();
        } else if (spatialClause instanceof SpatialClause.GeometryContains) {
            spatialQuery = this.makeContains();
        } else if (spatialClause instanceof SpatialClause.GeometryIntersects) {
            spatialQuery = this.makeIntersects();
        } else if (spatialClause instanceof SpatialClause.GeometryIsDisjointTo) {
            bUseSpatialRanking = false;
        } else if (spatialClause instanceof SpatialClause.GeometryIsEqualTo) {
            bUseSpatialRanking = false;
        } else if (spatialClause instanceof SpatialClause.GeometryIsWithin) {
            spatialQuery = this.makeWithin();
        } else if (spatialClause instanceof SpatialClause.GeometryOverlaps) {
            spatialQuery = this.makeIntersects();
        } else {
            sErr = "Unrecognized spatial clause type: ";
            throw new DiscoveryException(sErr + spatialClause.getClass().getName());
        }

        if (bUseSpatialRanking) {
            SpatialRankingValueSource srvs = new SpatialRankingValueSource(envelope, queryPower, targetPower);
            Query spatialRankingQuery = new ValueSourceQuery(srvs);
            BooleanQuery bq = new BooleanQuery();
            bq.add(spatialQuery, BooleanClause.Occur.MUST);
            bq.add(spatialRankingQuery, BooleanClause.Occur.MUST);
            appendQuery(activeBooleanQuery, activeLogicalClause, bq);
            this.getQueryAdapter().setHasScoredExpression(true);
        }
    }

    if (!bUseSpatialRanking) {
        if (spatialClause instanceof SpatialClause.GeometryBBOXIntersects) {
            appendQuery(activeBooleanQuery, activeLogicalClause, makeIntersects());
        } else if (spatialClause instanceof SpatialClause.GeometryContains) {
            appendQuery(activeBooleanQuery, activeLogicalClause, makeContains());
        } else if (spatialClause instanceof SpatialClause.GeometryIntersects) {
            appendQuery(activeBooleanQuery, activeLogicalClause, makeIntersects());
        } else if (spatialClause instanceof SpatialClause.GeometryIsDisjointTo) {
            appendQuery(activeBooleanQuery, activeLogicalClause, makeDisjoint());
        } else if (spatialClause instanceof SpatialClause.GeometryIsEqualTo) {
            appendQuery(activeBooleanQuery, activeLogicalClause, makeEquals());
        } else if (spatialClause instanceof SpatialClause.GeometryIsWithin) {
            appendQuery(activeBooleanQuery, activeLogicalClause, makeWithin());
        } else if (spatialClause instanceof SpatialClause.GeometryOverlaps) {
            appendQuery(activeBooleanQuery, activeLogicalClause, makeIntersects());
        } else {
            sErr = "Unrecognized spatial clause type: ";
            throw new DiscoveryException(sErr + spatialClause.getClass().getName());
        }
    }

}

From source file:com.esri.gpt.catalog.lucene.SpatialClauseAdapter.java

License:Apache License

/**
 * Constructs a query to retrieve documents that equal the input envelope.
 * @return the spatial query//  w  ww  .  j a v  a 2s . c  om
 */
private Query makeEquals() {

    // docMinX = qryMinX AND docMinY = qryMinY AND docMaxX = qryMaxX AND docMaxY = qryMaxY
    Query qMinX = NumericRangeQuery.newDoubleRange(docMinX, qryMinX, qryMinX, true, true);
    Query qMinY = NumericRangeQuery.newDoubleRange(docMinY, qryMinY, qryMinY, true, true);
    Query qMaxX = NumericRangeQuery.newDoubleRange(docMaxX, qryMaxX, qryMaxX, true, true);
    Query qMaxY = NumericRangeQuery.newDoubleRange(docMaxY, qryMaxY, qryMaxY, true, true);
    BooleanQuery bq = new BooleanQuery();
    bq.add(qMinX, BooleanClause.Occur.MUST);
    bq.add(qMinY, BooleanClause.Occur.MUST);
    bq.add(qMaxX, BooleanClause.Occur.MUST);
    bq.add(qMaxY, BooleanClause.Occur.MUST);
    return bq;
}

From source file:com.esri.gpt.catalog.lucene.SpatialClauseAdapter.java

License:Apache License

/**
 * Constructs a query to retrieve documents that intersect the input envelope.
 * @return the spatial query/*from www . j a v  a 2s.  c  o  m*/
 */
private Query makeIntersects() {

    // the original intersects query does not work for envelopes that cross the date line,
    // switch to a NOT Disjoint query

    // MUST_NOT causes a problem when it's the only clause type within a BooleanQuery,
    // to get round it we add all documents as a SHOULD

    // there must be an envelope, it must not be disjoint
    Query qDisjoint = makeDisjoint();
    Query qIsNonXDL = this.makeXDL(false);
    Query qIsXDL = this.makeXDL(true);
    Query qHasEnv = this.makeQuery(new Query[] { qIsNonXDL, qIsXDL }, BooleanClause.Occur.SHOULD);
    BooleanQuery qNotDisjoint = new BooleanQuery();
    qNotDisjoint.add(qHasEnv, BooleanClause.Occur.MUST);
    qNotDisjoint.add(qDisjoint, BooleanClause.Occur.MUST_NOT);

    //Query qDisjoint = makeDisjoint();
    //BooleanQuery qNotDisjoint = new BooleanQuery();
    //qNotDisjoint.add(new MatchAllDocsQuery(),BooleanClause.Occur.SHOULD);
    //qNotDisjoint.add(qDisjoint,BooleanClause.Occur.MUST_NOT);
    return qNotDisjoint;
}