Example usage for org.apache.solr.client.solrj SolrQuery getStart

List of usage examples for org.apache.solr.client.solrj SolrQuery getStart

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj SolrQuery getStart.

Prototype

public Integer getStart() 

Source Link

Usage

From source file:fr.gael.dhus.service.SearchService.java

License:Open Source License

/**
 * Integrity check./*from www . ja  v a 2  s.com*/
 */
public void checkIndex() {
    try {
        SolrQuery query = new SolrQuery("*:*");
        query.setFilterQueries("*");
        query.setStart(0);
        Iterator<SolrDocument> it = solrDao.scroll(query);
        while (it.hasNext()) {
            SolrDocument doc = it.next();
            Long pid = (Long) doc.get("id");
            Product product = productService.systemGetProduct(pid);
            if (product == null) {
                Long id = (Long) doc.getFieldValue("id");
                LOGGER.warn("Removing unknown product " + id + " from solr index");
                try {
                    solrDao.remove(id);
                    // decrease the offset, because a product has been removed
                    query.setStart(query.getStart() - 1);
                } catch (IOException e) {
                    LOGGER.error("Cannot remove Solr entry " + id, e);
                }
            }
        }
    } catch (IOException | SolrServerException ex) {
        LOGGER.error("Cannot check the index", ex);
    }
}

From source file:nl.knaw.huygens.timbuctoo.index.solr.SolrQueryMatcher.java

License:Open Source License

public SolrQueryMatcher withStart(int start) {
    this.addMatcher(new PropertyEqualityMatcher<SolrQuery, Integer>("start", start) {
        @Override//  w  w  w . j a  v  a  2s .c o  m
        protected Integer getItemValue(SolrQuery item) {
            return item.getStart();
        }
    });
    return this;
}

From source file:org.apache.metron.solr.matcher.SolrQueryMatcher.java

License:Apache License

@Override
public boolean matches(Object o) {
    SolrQuery solrQuery = (SolrQuery) o;
    return Objects.equals(solrQuery.getStart(), expectedSolrQuery.getStart())
            && Objects.equals(solrQuery.getRows(), expectedSolrQuery.getRows())
            && Objects.equals(solrQuery.getQuery(), expectedSolrQuery.getQuery())
            && Objects.equals(solrQuery.getSorts(), expectedSolrQuery.getSorts())
            && Objects.equals(solrQuery.getFields(), expectedSolrQuery.getFields())
            && Arrays.equals(solrQuery.getFacetFields(), expectedSolrQuery.getFacetFields())
            && Objects.equals(solrQuery.get("collection"), expectedSolrQuery.get("collection"))
            && Objects.equals(solrQuery.get("stats"), expectedSolrQuery.get("stats"))
            && Objects.equals(solrQuery.get("stats.field"), expectedSolrQuery.get("stats.field"))
            && Objects.equals(solrQuery.get("facet"), expectedSolrQuery.get("facet"))
            && Objects.equals(solrQuery.get("facet.pivot"), expectedSolrQuery.get("facet.pivot"));
}

From source file:org.apache.nifi.processors.solr.QuerySolr.java

License:Apache License

@Override
public void doOnTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ComponentLog logger = getLogger();

    FlowFile flowFileOriginal = session.get();
    FlowFile flowFileResponse;/*from   w  w w  . ja v  a2 s .  c o  m*/

    if (flowFileOriginal == null) {
        if (context.hasNonLoopConnection()) {
            return;
        }
        flowFileResponse = session.create();
    } else {
        flowFileResponse = session.create(flowFileOriginal);
    }

    final SolrQuery solrQuery = new SolrQuery();
    final boolean isSolrCloud = SOLR_TYPE_CLOUD.equals(context.getProperty(SOLR_TYPE).getValue());
    final String collection = context.getProperty(COLLECTION).evaluateAttributeExpressions(flowFileResponse)
            .getValue();

    final StringBuilder transitUri = new StringBuilder("solr://");
    transitUri.append(getSolrLocation());
    if (isSolrCloud) {
        transitUri.append(":").append(collection);
    }
    final StopWatch timer = new StopWatch(false);

    try {
        solrQuery.setQuery(context.getProperty(SOLR_PARAM_QUERY).evaluateAttributeExpressions(flowFileResponse)
                .getValue());
        solrQuery.setRequestHandler(context.getProperty(SOLR_PARAM_REQUEST_HANDLER)
                .evaluateAttributeExpressions(flowFileResponse).getValue());

        if (context.getProperty(SOLR_PARAM_FIELD_LIST).isSet()) {
            for (final String field : context.getProperty(SOLR_PARAM_FIELD_LIST)
                    .evaluateAttributeExpressions(flowFileResponse).getValue().split(",")) {
                solrQuery.addField(field.trim());
            }
        }

        // Avoid ArrayIndexOutOfBoundsException due to incorrectly configured sorting
        try {
            if (context.getProperty(SOLR_PARAM_SORT).isSet()) {
                final List<SolrQuery.SortClause> sortings = new ArrayList<>();
                for (final String sorting : context.getProperty(SOLR_PARAM_SORT)
                        .evaluateAttributeExpressions(flowFileResponse).getValue().split(",")) {
                    final String[] sortEntry = sorting.trim().split(" ");
                    sortings.add(new SolrQuery.SortClause(sortEntry[0], sortEntry[1]));
                }
                solrQuery.setSorts(sortings);
            }
        } catch (Exception e) {
            throw new ProcessException("Error while parsing the sort clauses for the Solr query");
        }

        final Integer startParam = context.getProperty(SOLR_PARAM_START).isSet()
                ? Integer.parseInt(context.getProperty(SOLR_PARAM_START)
                        .evaluateAttributeExpressions(flowFileResponse).getValue())
                : CommonParams.START_DEFAULT;

        solrQuery.setStart(startParam);

        final Integer rowParam = context.getProperty(SOLR_PARAM_ROWS).isSet()
                ? Integer.parseInt(context.getProperty(SOLR_PARAM_ROWS)
                        .evaluateAttributeExpressions(flowFileResponse).getValue())
                : CommonParams.ROWS_DEFAULT;

        solrQuery.setRows(rowParam);

        final Map<String, String[]> additionalSolrParams = SolrUtils.getRequestParams(context,
                flowFileResponse);

        final Set<String> searchComponents = extractSearchComponents(additionalSolrParams);
        solrQuery.add(new MultiMapSolrParams(additionalSolrParams));

        final Map<String, String> attributes = new HashMap<>();
        attributes.put(ATTRIBUTE_SOLR_CONNECT, getSolrLocation());
        if (isSolrCloud) {
            attributes.put(ATTRIBUTE_SOLR_COLLECTION, collection);
        }
        attributes.put(ATTRIBUTE_SOLR_QUERY, solrQuery.toString());
        if (flowFileOriginal != null) {
            flowFileOriginal = session.putAllAttributes(flowFileOriginal, attributes);
        }

        flowFileResponse = session.putAllAttributes(flowFileResponse, attributes);

        final boolean getEntireResults = RETURN_ALL_RESULTS
                .equals(context.getProperty(AMOUNT_DOCUMENTS_TO_RETURN).getValue());
        boolean processFacetsAndStats = true;
        boolean continuePaging = true;

        while (continuePaging) {

            timer.start();

            Map<String, String> responseAttributes = new HashMap<>();
            responseAttributes.put(ATTRIBUTE_SOLR_START, solrQuery.getStart().toString());
            responseAttributes.put(ATTRIBUTE_SOLR_ROWS, solrQuery.getRows().toString());

            if (solrQuery.getStart() > UPPER_LIMIT_START_PARAM) {
                logger.warn(
                        "The start parameter of Solr query {} exceeded the upper limit of {}. The query will not be processed "
                                + "to avoid performance or memory issues on the part of Solr.",
                        new Object[] { solrQuery.toString(), UPPER_LIMIT_START_PARAM });
                flowFileResponse = session.putAllAttributes(flowFileResponse, responseAttributes);
                timer.stop();
                break;
            }

            final QueryRequest req = new QueryRequest(solrQuery);
            if (isBasicAuthEnabled()) {
                req.setBasicAuthCredentials(getUsername(), getPassword());
            }

            final QueryResponse response = req.process(getSolrClient());
            timer.stop();

            final Long totalNumberOfResults = response.getResults().getNumFound();

            responseAttributes.put(ATTRIBUTE_SOLR_NUMBER_RESULTS, totalNumberOfResults.toString());
            responseAttributes.put(ATTRIBUTE_CURSOR_MARK, response.getNextCursorMark());
            responseAttributes.put(ATTRIBUTE_SOLR_STATUS, String.valueOf(response.getStatus()));
            responseAttributes.put(ATTRIBUTE_QUERY_TIME, String.valueOf(response.getQTime()));
            flowFileResponse = session.putAllAttributes(flowFileResponse, responseAttributes);

            if (response.getResults().size() > 0) {

                if (context.getProperty(RETURN_TYPE).getValue().equals(MODE_XML.getValue())) {
                    flowFileResponse = session.write(flowFileResponse,
                            SolrUtils.getOutputStreamCallbackToTransformSolrResponseToXml(response));
                    flowFileResponse = session.putAttribute(flowFileResponse, CoreAttributes.MIME_TYPE.key(),
                            MIME_TYPE_XML);
                } else {
                    final RecordSetWriterFactory writerFactory = context.getProperty(RECORD_WRITER)
                            .evaluateAttributeExpressions(flowFileResponse)
                            .asControllerService(RecordSetWriterFactory.class);
                    final RecordSchema schema = writerFactory.getSchema(flowFileResponse.getAttributes(), null);
                    final RecordSet recordSet = SolrUtils.solrDocumentsToRecordSet(response.getResults(),
                            schema);
                    final StringBuffer mimeType = new StringBuffer();
                    final FlowFile flowFileResponseRef = flowFileResponse;
                    flowFileResponse = session.write(flowFileResponse, out -> {
                        try (final RecordSetWriter writer = writerFactory.createWriter(getLogger(), schema, out,
                                flowFileResponseRef)) {
                            writer.write(recordSet);
                            writer.flush();
                            mimeType.append(writer.getMimeType());
                        } catch (SchemaNotFoundException e) {
                            throw new ProcessException("Could not parse Solr response", e);
                        }
                    });
                    flowFileResponse = session.putAttribute(flowFileResponse, CoreAttributes.MIME_TYPE.key(),
                            mimeType.toString());
                }

                if (processFacetsAndStats) {
                    if (searchComponents.contains(FacetParams.FACET)) {
                        FlowFile flowFileFacets = session.create(flowFileResponse);
                        flowFileFacets = session.write(flowFileFacets, out -> {
                            try (final OutputStreamWriter osw = new OutputStreamWriter(out);
                                    final JsonWriter writer = new JsonWriter(osw)) {
                                addFacetsFromSolrResponseToJsonWriter(response, writer);
                            }
                        });
                        flowFileFacets = session.putAttribute(flowFileFacets, CoreAttributes.MIME_TYPE.key(),
                                MIME_TYPE_JSON);
                        session.getProvenanceReporter().receive(flowFileFacets, transitUri.toString(),
                                timer.getDuration(TimeUnit.MILLISECONDS));
                        session.transfer(flowFileFacets, FACETS);
                    }

                    if (searchComponents.contains(StatsParams.STATS)) {
                        FlowFile flowFileStats = session.create(flowFileResponse);
                        flowFileStats = session.write(flowFileStats, out -> {
                            try (final OutputStreamWriter osw = new OutputStreamWriter(out);
                                    final JsonWriter writer = new JsonWriter(osw)) {
                                addStatsFromSolrResponseToJsonWriter(response, writer);
                            }
                        });
                        flowFileStats = session.putAttribute(flowFileStats, CoreAttributes.MIME_TYPE.key(),
                                MIME_TYPE_JSON);
                        session.getProvenanceReporter().receive(flowFileStats, transitUri.toString(),
                                timer.getDuration(TimeUnit.MILLISECONDS));
                        session.transfer(flowFileStats, STATS);
                    }
                    processFacetsAndStats = false;
                }
            }

            if (getEntireResults) {
                final Integer totalDocumentsReturned = solrQuery.getStart() + solrQuery.getRows();
                if (totalDocumentsReturned < totalNumberOfResults) {
                    solrQuery.setStart(totalDocumentsReturned);
                    session.getProvenanceReporter().receive(flowFileResponse, transitUri.toString(),
                            timer.getDuration(TimeUnit.MILLISECONDS));
                    session.transfer(flowFileResponse, RESULTS);
                    flowFileResponse = session.create(flowFileResponse);
                } else {
                    continuePaging = false;
                }
            } else {
                continuePaging = false;
            }
        }

    } catch (Exception e) {
        flowFileResponse = session.penalize(flowFileResponse);
        flowFileResponse = session.putAttribute(flowFileResponse, EXCEPTION, e.getClass().getName());
        flowFileResponse = session.putAttribute(flowFileResponse, EXCEPTION_MESSAGE, e.getMessage());
        session.transfer(flowFileResponse, FAILURE);
        logger.error("Failed to execute query {} due to {}. FlowFile will be routed to relationship failure",
                new Object[] { solrQuery.toString(), e }, e);
        if (flowFileOriginal != null) {
            flowFileOriginal = session.penalize(flowFileOriginal);
        }
    }

    if (!flowFileResponse.isPenalized()) {
        session.getProvenanceReporter().receive(flowFileResponse, transitUri.toString(),
                timer.getDuration(TimeUnit.MILLISECONDS));
        session.transfer(flowFileResponse, RESULTS);
    }

    if (flowFileOriginal != null) {
        if (!flowFileOriginal.isPenalized()) {
            session.transfer(flowFileOriginal, ORIGINAL);
        } else {
            session.remove(flowFileOriginal);
        }
    }
}

From source file:org.entrystore.repository.util.SolrSupport.java

License:Apache License

public QueryResult sendQuery(SolrQuery query) {
    Set<URI> entries = new LinkedHashSet<URI>();
    Set<Entry> result = new LinkedHashSet<Entry>();
    long hits = -1;
    int limit = query.getRows();
    int offset = query.getStart();
    query.setIncludeScore(true);//from w  w  w .j  av a2  s. c o m
    int resultFillIteration = 0;
    do {
        if (resultFillIteration++ > 0) {
            if (resultFillIteration > 10) {
                log.warn("Breaking after 10 result fill interations to prevent too many loops");
                break;
            }
            offset += 10;
            log.warn("Increasing offset to fill the result limit");
        }
        hits = sendQueryForEntryURIs(query, entries, solrServer, offset, -1);
        Date before = new Date();
        for (URI uri : entries) {
            try {
                Entry entry = rm.getContextManager().getEntry(uri);
                if (entry != null) {
                    PrincipalManager pm = entry.getRepositoryManager().getPrincipalManager();
                    // If linkReference or reference to a entry in the same
                    // repository
                    // check that the referenced metadata is accessible.
                    if ((entry.getEntryType() == EntryType.Reference
                            || entry.getEntryType() == EntryType.LinkReference)
                            && entry.getCachedExternalMetadata() instanceof LocalMetadataWrapper) {
                        Entry refEntry = entry.getRepositoryManager().getContextManager()
                                .getEntry(entry.getExternalMetadataURI());
                        pm.checkAuthenticatedUserAuthorized(refEntry, AccessProperty.ReadMetadata);
                    } else {
                        // Check that the local metadata is accessible.
                        pm.checkAuthenticatedUserAuthorized(entry, AccessProperty.ReadMetadata);
                    }
                    result.add(entry);
                    if (result.size() == limit) {
                        // we have enough results
                        break;
                    }
                }
            } catch (AuthorizationException ae) {
                hits--;
                continue;
            }
        }
        log.info("Entry fetching took " + (new Date().getTime() - before.getTime()) + " ms");
    } while ((limit > result.size()) && (hits > (offset + limit)));

    return new QueryResult(result, hits);
}

From source file:org.geotools.data.solr.SolrFeatureReader.java

License:Open Source License

/**
 * Creates the feature reader for SOLR store <br>
 * The feature reader use SOLR CURSOR to paginate request, so multiple SOLR query will be
 * executed//from  w ww. ja v  a 2  s.  c o m
 * 
 * @param featureType the feature type to query
 * @param solrUrl the URL of SOLR server
 * @param solrQuery the SOLR query to execute
 * @param solrDataStore the SOLR store
 * @throws SolrServerException
 */
public SolrFeatureReader(SimpleFeatureType featureType, HttpSolrServer server, SolrQuery solrQuery,
        SolrDataStore solrDataStore) throws SolrServerException {
    this.featureType = featureType;
    this.solrQuery = solrQuery;
    this.wktReader = new WKTReader();
    this.solrDataStore = solrDataStore;
    this.pkey = solrDataStore.getPrimaryKey(featureType.getTypeName());

    this.builder = new SimpleFeatureBuilder(featureType);

    this.server = server;

    // Add always pk as field if not already present
    if (solrQuery.getFields() != null && !solrQuery.getFields().contains(pkey.getName())) {
        solrQuery.addField(pkey.getName());
    }

    // Can't use pagination with start, then first query for cursor mark of start
    if (solrQuery.getStart() != null && solrQuery.getStart() > 0) {
        cursorMark = getCursorMarkForStart(server, solrQuery);
    } else {
        cursorMark = CursorMarkParams.CURSOR_MARK_START;
    }
    solrQuery.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
    QueryResponse rsp = server.query(solrQuery);
    if (this.solrDataStore.getLogger().isLoggable(Level.FINE)) {
        this.solrDataStore.getLogger().log(Level.FINE, "SOLR query done: " + solrQuery.toString());
    }
    this.solrDocIterator = rsp.getResults().iterator();
    nextCursorMark = rsp.getNextCursorMark();
    counter = 0;
}

From source file:org.geotools.data.solr.SolrFeatureReader.java

License:Open Source License

private String getCursorMarkForStart(HttpSolrServer server, SolrQuery solrQuery) throws SolrServerException {
    Integer prevRows = solrQuery.getRows();
    solrQuery.setRows(solrQuery.getStart());
    solrQuery.setStart(0);//from www . j  a v a  2s .  c o m
    solrQuery.set(CursorMarkParams.CURSOR_MARK_PARAM, CursorMarkParams.CURSOR_MARK_START);
    QueryResponse rsp = server.query(solrQuery);
    if (this.solrDataStore.getLogger().isLoggable(Level.FINE)) {
        this.solrDataStore.getLogger().log(Level.FINE, "SOLR query done: " + solrQuery.toString());
    }
    String nextC = rsp.getNextCursorMark();
    solrQuery.setRows(prevRows);
    return nextC;
}

From source file:org.zenoss.zep.index.impl.solr.SolrEventIndexBackend.java

License:Open Source License

private EventSummaryResult execute(final SolrQuery query, boolean justUuids) throws ZepException {
    EventSummaryResult.Builder result = EventSummaryResult.newBuilder();

    logger.debug("Searching SOLR for events matching: {}", query.getQuery());
    final long now = logger.isDebugEnabled() ? System.currentTimeMillis() : 0;
    final QueryResponse response;
    try {/*w w w .j  ava 2  s  . c  om*/
        response = queryServer.query(query);
        final int numFound = (int) response.getResults().getNumFound();
        result.setTotal(numFound);
        if (query.getRows() != null) {
            final int limit = query.getRows();
            final int offset = (query.getStart() == null) ? 0 : query.getStart();
            result.setLimit(limit);
            if (numFound > offset + limit)
                result.setNextOffset(offset + limit);
        }

        logger.debug("Found {} results in SOLR", numFound);

        if (justUuids) {
            for (SolrDocument doc : response.getResults())
                result.addEvents(SolrEventIndexMapper.toEventSummary(doc));
        } else {
            Map<String, EventSummary> sortedResults = Maps.newLinkedHashMap();
            Set<EventSummary> toLookup = Sets.newHashSet();
            for (SolrDocument doc : response.getResults()) {
                EventSummary event = SolrEventIndexMapper.toEventSummary(doc);
                if (event.hasFirstSeenTime()) {
                    sortedResults.put(event.getUuid(), event);
                } else {
                    // We only store keys in the index for archived events. This must be one of those.
                    // Set a place-holder now. We'll find it in the database shortly.
                    sortedResults.put(event.getUuid(), null);
                    toLookup.add(event);
                }
            }
            if (!toLookup.isEmpty()) {
                final long beforeLookup = System.currentTimeMillis();
                logger.debug("Looking up {} events by UUID", toLookup.size());
                List<EventSummary> events = archiveDao.findByKey(toLookup);
                if (events.size() != toLookup.size()) {
                    int missing = toLookup.size() - events.size();
                    logger.info(
                            "Event archive index out of sync - {} of {} event UUIDs are in Solr index, but not in database.",
                            missing, toLookup.size());
                }
                for (EventSummary event : events)
                    sortedResults.put(event.getUuid(), event); // a re-insertion -- solr sort is preserved.
                logger.debug("Query spent {} milliseconds to lookup {} events by UUID.",
                        System.currentTimeMillis() - beforeLookup, toLookup.size());
            } else {
                logger.debug("Query did not have to lookup any events by UUID");
            }
            for (EventSummary event : sortedResults.values())
                if (event != null)
                    result.addEvents(event);
        }
    } catch (SolrServerException e) {
        throw new ZepException(e);
    } finally {
        if (logger.isDebugEnabled())
            logger.debug("Query {} finished in {} milliseconds", query, System.currentTimeMillis() - now);
    }
    return result.build();
}

From source file:uk.ac.ebi.intact.dataexchange.psimi.solr.params.UrlSolrParamsTest.java

License:Apache License

@Test
public void params1() throws Exception {
    String params = "q=*:*&sort=rigid asc&rows=30&fq=+dataset:(\"Cancer\")&fq=+go_expanded_id:(\"GO:0048511\")&start=0";

    UrlSolrParams solrParams = new UrlSolrParams(params);

    SolrQuery solrQuery = new SolrQuery();
    solrQuery.add(solrParams);//from ww  w.  java 2  s. c o  m

    Assert.assertEquals("*:*", solrQuery.getQuery());
    Assert.assertEquals("rigid asc", solrQuery.getSortField());
    Assert.assertEquals(Integer.valueOf(30), solrQuery.getRows());
    Assert.assertEquals(Integer.valueOf(0), solrQuery.getStart());

    Assert.assertTrue(Arrays.asList(solrQuery.getFilterQueries()).contains("+go_expanded_id:(\"GO:0048511\")"));
    Assert.assertTrue(Arrays.asList(solrQuery.getFilterQueries()).contains("+dataset:(\"Cancer\")"));
}

From source file:uk.co.flax.ukmp.search.solr.SolrSearchEngine.java

License:Apache License

@Override
public SearchResults getTextBatch(int batchNum) throws SearchEngineException {
    SearchResults results;//from   w  w w.  j  a v  a2s.c  o m
    TermsConfiguration termsConfig = config.getTermsConfiguration();

    SolrQuery query = new SolrQuery("*:*");
    query.setRequestHandler(termsConfig.getHandler());
    query.setFields(termsConfig.getField());
    query.setRows(termsConfig.getBatchSize());
    query.setStart(batchNum * termsConfig.getBatchSize());
    query.addFilterQuery(termsConfig.getFilters().toArray(new String[0]));

    try {
        QueryResponse response = server.query(query);
        SolrDocumentList docs = response.getResults();

        // Attempt to ensure we always return at least one batch of results
        if (docs.getNumFound() == 0) {
            LOGGER.debug("No tweets found in text batch - running again without filters");
            docs = runQueryWithoutFilters(query, termsConfig.getFilters());
        }

        List<Tweet> tweets = new ArrayList<Tweet>(docs.size());
        for (SolrDocument doc : docs) {
            Tweet tweet = new Tweet();
            tweet.setText((String) doc.getFieldValue(termsConfig.getField()));
            tweets.add(tweet);
        }

        results = new SearchResults(query.getStart(), docs.getNumFound(), query.getRows(), tweets, null);
    } catch (SolrServerException e) {
        LOGGER.error("Server exception caught getting text batch {}: {}", batchNum, e.getMessage());
        throw new SearchEngineException(e);
    }

    return results;
}