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

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

Introduction

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

Prototype

public SolrQuery addField(String field) 

Source Link

Usage

From source file:au.org.ala.biocache.dao.SearchDAOImpl.java

License:Open Source License

/**
 * Writes the index fields to the supplied output stream in CSV format.
 * <p>/*w w w.  j  ava  2  s.co  m*/
 * DM: refactored to split the query by month to improve performance.
 * Further enhancements possible:
 * 1) Multi threaded
 * 2) More filtering, by year or decade..
 *
 * @param downloadParams
 * @param out
 * @param includeSensitive
 * @param dd               The details of the download
 * @param checkLimit
 * @param nextExecutor     The ExecutorService to use to process results on different threads
 * @throws Exception
 */
@Override
public ConcurrentMap<String, AtomicInteger> writeResultsFromIndexToStream(
        final DownloadRequestParams downloadParams, final OutputStream out, final boolean includeSensitive,
        final DownloadDetailsDTO dd, boolean checkLimit, final ExecutorService nextExecutor) throws Exception {
    expandRequestedFields(downloadParams, true);

    if (dd != null) {
        dd.resetCounts();
    }

    long start = System.currentTimeMillis();
    final ConcurrentMap<String, AtomicInteger> uidStats = new ConcurrentHashMap<>();
    getServer();

    try {
        SolrQuery solrQuery = new SolrQuery();
        queryFormatUtils.formatSearchQuery(downloadParams);

        String dFields = downloadParams.getFields();

        if (includeSensitive) {
            //include raw latitude and longitudes
            if (dFields.contains("decimalLatitude.p")) {
                dFields = dFields.replaceFirst("decimalLatitude.p",
                        "sensitive_latitude,sensitive_longitude,decimalLatitude.p");
            } else if (dFields.contains("decimalLatitude")) {
                dFields = dFields.replaceFirst("decimalLatitude",
                        "sensitive_latitude,sensitive_longitude,decimalLatitude");
            }
            if (dFields.contains(",locality,")) {
                dFields = dFields.replaceFirst(",locality,", ",locality,sensitive_locality,");
            }
            if (dFields.contains(",locality.p,")) {
                dFields = dFields.replaceFirst(",locality.p,", ",locality.p,sensitive_locality,");
            }
        }

        StringBuilder sb = new StringBuilder(dFields);
        if (!downloadParams.getExtra().isEmpty()) {
            sb.append(",").append(downloadParams.getExtra());
        }

        String[] requestedFields = sb.toString().split(",");
        List<String>[] indexedFields;
        if (downloadFields == null) {
            //default to include everything
            java.util.List<String> mappedNames = new java.util.LinkedList<String>();
            for (int i = 0; i < requestedFields.length; i++)
                mappedNames.add(requestedFields[i]);

            indexedFields = new List[] { mappedNames, new java.util.LinkedList<String>(), mappedNames,
                    mappedNames, new ArrayList(), new ArrayList() };
        } else {
            indexedFields = downloadFields.getIndexFields(requestedFields, downloadParams.getDwcHeaders(),
                    downloadParams.getLayersServiceUrl());
        }
        //apply custom header
        String[] customHeader = dd.getRequestParams().getCustomHeader().split(",");
        for (int i = 0; i + 1 < customHeader.length; i += 2) {
            for (int j = 0; j < indexedFields[0].size(); j++) {
                if (customHeader[i].equals(indexedFields[0].get(j))) {
                    indexedFields[2].set(j, customHeader[i + 1]);
                }
            }
            for (int j = 0; j < indexedFields[4].size(); j++) {
                if (customHeader[i].equals(indexedFields[5].get(j))) {
                    indexedFields[4].set(j, customHeader[i + 1]);
                }
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Fields included in download: " + indexedFields[0]);
            logger.debug("Fields excluded from download: " + indexedFields[1]);
            logger.debug("The headers in downloads: " + indexedFields[2]);
            logger.debug("Analysis headers: " + indexedFields[4]);
            logger.debug("Analysis fields: " + indexedFields[5]);
        }

        //set the fields to the ones that are available in the index
        String[] fields = indexedFields[0].toArray(new String[] {});
        solrQuery.setFields(fields);
        StringBuilder qasb = new StringBuilder();
        if (!"none".equals(downloadParams.getQa())) {
            solrQuery.addField("assertions");
            if (!"all".equals(downloadParams.getQa()) && !"includeall".equals(downloadParams.getQa())) {
                //add all the qa fields
                qasb.append(downloadParams.getQa());
            }
        }
        solrQuery.addField("institution_uid").addField("collection_uid").addField("data_resource_uid")
                .addField("data_provider_uid");

        solrQuery.setQuery(downloadParams.getFormattedQuery());
        solrQuery.setFacetMinCount(1);
        solrQuery.setFacetLimit(-1);

        //get the assertion facets to add them to the download fields
        boolean getAssertionsFromFacets = "all".equals(downloadParams.getQa())
                || "includeall".equals(downloadParams.getQa());
        SolrQuery monthAssertionsQuery = getAssertionsFromFacets
                ? solrQuery.getCopy().addFacetField("month", "assertions")
                : solrQuery.getCopy().addFacetField("month");
        if (getAssertionsFromFacets) {
            //set the order for the facet to be based on the index - this will force the assertions to be returned in the same order each time
            //based on alphabetical sort.  The number of QA's may change between searches so we can't guarantee that the order won't change
            monthAssertionsQuery.add("f.assertions.facet.sort", "index");
        }
        QueryResponse facetQuery = runSolrQuery(monthAssertionsQuery, downloadParams.getFormattedFq(), 0, 0,
                "score", "asc");

        //set the totalrecords for the download details
        dd.setTotalRecords(facetQuery.getResults().getNumFound());

        //use a separately configured and smaller limit when output will be unzipped
        final long maxDownloadSize;
        if (MAX_DOWNLOAD_SIZE > unzippedLimit && out instanceof OptionalZipOutputStream
                && ((OptionalZipOutputStream) out).getType() == OptionalZipOutputStream.Type.unzipped) {
            maxDownloadSize = unzippedLimit;
        } else {
            maxDownloadSize = MAX_DOWNLOAD_SIZE;
        }

        if (checkLimit && dd.getTotalRecords() < maxDownloadSize) {
            checkLimit = false;
        }

        //get the month facets to add them to the download fields get the assertion facets.
        List<Count> splitByFacet = null;

        for (FacetField facet : facetQuery.getFacetFields()) {
            if (facet.getName().equals("assertions") && facet.getValueCount() > 0) {
                qasb.append(getQAFromFacet(facet));
            }
            if (facet.getName().equals("month") && facet.getValueCount() > 0) {
                splitByFacet = facet.getValues();
            }
        }

        if ("includeall".equals(downloadParams.getQa())) {
            qasb = getAllQAFields();
        }

        String qas = qasb.toString();

        //include sensitive fields in the header when the output will be partially sensitive
        final String[] sensitiveFields;
        final String[] notSensitiveFields;
        if (dd.getSensitiveFq() != null) {
            List<String>[] sensitiveHdr = downloadFields.getIndexFields(sensitiveSOLRHdr,
                    downloadParams.getDwcHeaders(), downloadParams.getLayersServiceUrl());

            //header for the output file
            indexedFields[2].addAll(sensitiveHdr[2]);

            //lookup for fields from sensitive queries
            sensitiveFields = org.apache.commons.lang3.ArrayUtils.addAll(
                    indexedFields[0].toArray(new String[] {}), sensitiveHdr[0].toArray(new String[] {}));

            //use general fields when sensitive data is not permitted
            notSensitiveFields = org.apache.commons.lang3.ArrayUtils
                    .addAll(indexedFields[0].toArray(new String[] {}), notSensitiveSOLRHdr);
        } else {
            sensitiveFields = new String[0];
            notSensitiveFields = fields;
        }

        //add analysis headers
        indexedFields[2].addAll(indexedFields[4]);
        final String[] analysisFields = indexedFields[5].toArray(new String[0]);

        final String[] qaFields = qas.equals("") ? new String[] {} : qas.split(",");
        String[] qaTitles = downloadFields.getHeader(qaFields, false, false);

        String[] header = org.apache.commons.lang3.ArrayUtils.addAll(indexedFields[2].toArray(new String[] {}),
                qaTitles);

        //retain output header fields and field names for inclusion of header info in the download
        StringBuilder infoFields = new StringBuilder("infoFields");
        for (String h : indexedFields[3])
            infoFields.append(",").append(h);
        for (String h : qaFields)
            infoFields.append(",").append(h);

        StringBuilder infoHeader = new StringBuilder("infoHeaders");
        for (String h : header)
            infoHeader.append(",").append(h);

        String info = infoFields.toString();
        while (info.contains(",,"))
            info = info.replace(",,", ",");
        uidStats.put(info, new AtomicInteger(-1));
        String hdr = infoHeader.toString();
        while (hdr.contains(",,"))
            hdr = hdr.replace(",,", ",");
        uidStats.put(hdr, new AtomicInteger(-2));

        //construct correct RecordWriter based on the supplied fileType
        final RecordWriterError rw = downloadParams.getFileType().equals("csv")
                ? new CSVRecordWriter(out, header, downloadParams.getSep(), downloadParams.getEsc())
                : (downloadParams.getFileType().equals("tsv") ? new TSVRecordWriter(out, header)
                        : new ShapeFileRecordWriter(tmpShapefileDir, downloadParams.getFile(), out,
                                (String[]) ArrayUtils.addAll(fields, qaFields)));

        // Requirement to be able to propagate interruptions to all other threads for this execution
        // Doing this via this variable
        final AtomicBoolean interruptFound = dd != null ? dd.getInterrupt() : new AtomicBoolean(false);

        // Create a fixed length blocking queue for buffering results before they are written
        // This also creates a push-back effect to throttle the results generating threads
        // when it fills and offers to it are delayed until the writer consumes elements from the queue
        final BlockingQueue<String[]> queue = new ArrayBlockingQueue<>(resultsQueueLength);
        // Create a sentinel that we can check for reference equality to signal the end of the queue
        final String[] sentinel = new String[0];
        // An implementation of RecordWriter that adds to an in-memory queue
        final RecordWriter concurrentWrapper = new RecordWriter() {
            private AtomicBoolean finalised = new AtomicBoolean(false);
            private AtomicBoolean finalisedComplete = new AtomicBoolean(false);

            @Override
            public void write(String[] nextLine) {
                try {
                    if (Thread.currentThread().isInterrupted() || interruptFound.get() || finalised.get()) {
                        finalise();
                        return;
                    }
                    while (!queue.offer(nextLine, writerTimeoutWaitMillis, TimeUnit.MILLISECONDS)) {
                        if (Thread.currentThread().isInterrupted() || interruptFound.get() || finalised.get()) {
                            finalise();
                            break;
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    interruptFound.set(true);
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "Queue failed to accept the next record due to a thread interrupt, calling finalise the cleanup: ",
                                e);
                    }
                    // If we were interrupted then we should call finalise to cleanup
                    finalise();
                }
            }

            @Override
            public void finalise() {
                if (finalised.compareAndSet(false, true)) {
                    try {
                        // Offer the sentinel at least once, even when the thread is interrupted
                        while (!queue.offer(sentinel, writerTimeoutWaitMillis, TimeUnit.MILLISECONDS)) {
                            // If the thread is interrupted then the queue may not have any active consumers,
                            // so don't loop forever waiting for capacity in this case
                            // The hard shutdown phase will use queue.clear to ensure that the
                            // sentinel gets onto the queue at least once
                            if (Thread.currentThread().isInterrupted() || interruptFound.get()) {
                                break;
                            }
                        }
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        interruptFound.set(true);
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Queue failed to accept the sentinel in finalise due to a thread interrupt: ",
                                    e);
                        }
                    } finally {
                        finalisedComplete.set(true);
                    }
                }
            }

            @Override
            public boolean finalised() {
                return finalisedComplete.get();
            }

        };

        // A single thread that consumes elements put onto the queue until it sees the sentinel, finalising after the sentinel or an interrupt
        Runnable writerRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    long counter = 0;
                    while (true) {
                        counter = counter + 1;

                        if (Thread.currentThread().isInterrupted() || interruptFound.get()) {
                            break;
                        }

                        String[] take = queue.take();
                        // Sentinel object equality check to see if we are done
                        if (take == sentinel || Thread.currentThread().isInterrupted()
                                || interruptFound.get()) {
                            break;
                        }
                        // Otherwise write to the wrapped record writer
                        rw.write(take);

                        //test for errors. This can contain a flush so only test occasionally
                        if (counter % resultsQueueLength == 0 && rw.hasError()) {
                            throw RecordWriterException.newRecordWriterException(dd, downloadParams, true, rw);
                        }

                    }
                } catch (RecordWriterException e) {
                    //no trace information is available to print for these errors
                    logger.error(e.getMessage());
                    interruptFound.set(true);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    interruptFound.set(true);
                } catch (Exception e) {
                    // Reuse interruptFound variable to signal that the writer had issues
                    interruptFound.set(true);
                    logger.error("Download writer failed.", e);
                } finally {
                    rw.finalise();
                }
            }
        };
        Thread writerThread = new Thread(writerRunnable);
        writerThread.start();

        try {
            if (rw instanceof ShapeFileRecordWriter) {
                dd.setHeaderMap(((ShapeFileRecordWriter) rw).getHeaderMappings());
            }

            //order the query by _docid_ for faster paging
            solrQuery.addSortField("_docid_", ORDER.asc);

            //for each month create a separate query that pages through 500 records per page
            List<SolrQuery> queries = new ArrayList<SolrQuery>();
            if (splitByFacet != null) {
                for (Count facet : splitByFacet) {
                    if (facet.getCount() > 0) {
                        SolrQuery splitByFacetQuery;
                        //do not add remainderQuery here
                        if (facet.getName() != null) {
                            splitByFacetQuery = solrQuery.getCopy()
                                    .addFilterQuery(facet.getFacetField().getName() + ":" + facet.getName());
                            splitByFacetQuery.setFacet(false);
                            queries.add(splitByFacetQuery);
                        }

                    }
                }
                if (splitByFacet.size() > 0) {
                    SolrQuery remainderQuery = solrQuery.getCopy()
                            .addFilterQuery("-" + splitByFacet.get(0).getFacetField().getName() + ":[* TO *]");
                    queries.add(0, remainderQuery);
                }
            } else {
                queries.add(0, solrQuery);
            }

            //split into sensitive and non-sensitive queries when
            // - not including all sensitive values
            // - there is a sensitive fq
            final List<SolrQuery> sensitiveQ = new ArrayList<SolrQuery>();
            if (!includeSensitive && dd.getSensitiveFq() != null) {
                sensitiveQ.addAll(
                        splitQueries(queries, dd.getSensitiveFq(), sensitiveSOLRHdr, notSensitiveSOLRHdr));
            }

            //Set<Future<Integer>> futures = new HashSet<Future<Integer>>();
            final AtomicInteger resultsCount = new AtomicInteger(0);
            final boolean threadCheckLimit = checkLimit;

            List<Callable<Integer>> solrCallables = new ArrayList<>(queries.size());
            // execute each query, writing the results to stream
            for (final SolrQuery splitByFacetQuery : queries) {
                // define a thread
                Callable<Integer> solrCallable = new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        int startIndex = 0;
                        // Randomise the wakeup time so they don't all wakeup on a periodic cycle
                        long localThrottle = throttle + Math.round(Math.random() * throttle);

                        String[] fq = downloadParams.getFormattedFq();
                        if (splitByFacetQuery.getFilterQueries() != null
                                && splitByFacetQuery.getFilterQueries().length > 0) {
                            if (fq == null) {
                                fq = new String[0];
                            }
                            fq = org.apache.commons.lang3.ArrayUtils.addAll(fq,
                                    splitByFacetQuery.getFilterQueries());
                        }

                        QueryResponse qr = runSolrQuery(splitByFacetQuery, fq, downloadBatchSize, startIndex,
                                "_docid_", "asc");
                        AtomicInteger recordsForThread = new AtomicInteger(0);
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    splitByFacetQuery.getQuery() + " - results: " + qr.getResults().size());
                        }

                        while (qr != null && !qr.getResults().isEmpty() && !interruptFound.get()) {
                            if (logger.isDebugEnabled()) {
                                logger.debug(
                                        "Start index: " + startIndex + ", " + splitByFacetQuery.getQuery());
                            }
                            int count = 0;
                            if (sensitiveQ.contains(splitByFacetQuery)) {
                                count = processQueryResults(uidStats, sensitiveFields, qaFields,
                                        concurrentWrapper, qr, dd, threadCheckLimit, resultsCount,
                                        maxDownloadSize, analysisFields);
                            } else {
                                // write non-sensitive values into sensitive fields when not authorised for their sensitive values
                                count = processQueryResults(uidStats, notSensitiveFields, qaFields,
                                        concurrentWrapper, qr, dd, threadCheckLimit, resultsCount,
                                        maxDownloadSize, analysisFields);
                            }
                            recordsForThread.addAndGet(count);
                            startIndex += downloadBatchSize;
                            // we have already set the Filter query the first time the query was constructed
                            // rerun with the same params but different startIndex
                            if (!threadCheckLimit || resultsCount.get() < maxDownloadSize) {
                                if (!threadCheckLimit) {
                                    // throttle the download by sleeping
                                    Thread.sleep(localThrottle);
                                }
                                qr = runSolrQuery(splitByFacetQuery, null, downloadBatchSize, startIndex,
                                        "_docid_", "asc");
                            } else {
                                qr = null;
                            }
                        }
                        return recordsForThread.get();
                    }
                };
                solrCallables.add(solrCallable);
            }

            List<Future<Integer>> futures = new ArrayList<>(solrCallables.size());
            for (Callable<Integer> nextCallable : solrCallables) {
                futures.add(nextExecutor.submit(nextCallable));
            }

            // Busy wait because we need to be able to respond to an interrupt on any callable
            // and propagate it to all of the others for this particular query
            // Because the executor service is shared to prevent too many concurrent threads being run,
            // this requires a busy wait loop on the main thread to monitor state
            boolean waitAgain = false;
            do {
                waitAgain = false;
                for (Future<Integer> future : futures) {
                    if (!future.isDone()) {
                        // Wait again even if an interrupt flag is set, as it may have been set partway through the iteration
                        // The calls to future.cancel will occur next time if the interrupt is setup partway through an iteration
                        waitAgain = true;
                        // If one thread finds an interrupt it is propagated to others using the interruptFound AtomicBoolean
                        if (interruptFound.get()) {
                            future.cancel(true);
                        }
                    }
                }
                // Don't trigger the timeout interrupt if we don't have to wait again as we are already done at this point
                if (waitAgain && (System.currentTimeMillis() - start) > downloadMaxTime) {
                    interruptFound.set(true);
                    break;
                }

                if (waitAgain) {
                    Thread.sleep(downloadCheckBusyWaitSleep);
                }
            } while (waitAgain);

            AtomicInteger totalDownload = new AtomicInteger(0);
            for (Future<Integer> future : futures) {
                if (future.isDone()) {
                    totalDownload.addAndGet(future.get());
                } else {
                    // All incomplete futures that survived the loop above are cancelled here
                    future.cancel(true);
                }
            }

            long finish = System.currentTimeMillis();
            long timeTakenInSecs = (finish - start) / 1000;
            if (timeTakenInSecs <= 0)
                timeTakenInSecs = 1;
            if (logger.isInfoEnabled()) {
                logger.info("Download of " + resultsCount + " records in " + timeTakenInSecs
                        + " seconds. Record/sec: " + resultsCount.intValue() / timeTakenInSecs);
            }

        } finally {
            try {
                // Once we get here, we need to finalise starting at the concurrent wrapper,
                // as there are no more non-sentinel records to be added to the queue
                // This eventually triggers finalisation of the underlying writer when the queue empties
                // This is a soft shutdown, and hence we wait below for this stage to complete in normal circumstances
                // Note, this blocks for writerTimeoutWaitMillis trying to legitimately add the sentinel to the end of the queue
                // We force the sentinel to be added in the hard shutdown phase below
                concurrentWrapper.finalise();
            } finally {
                try {
                    // Track the current time right now so we can abort after downloadMaxCompletionTime milliseconds in this phase
                    final long completionStartTime = System.currentTimeMillis();
                    // Busy wait check for finalised to be called in the RecordWriter or something is interrupted
                    // By this stage, there are at maximum download.internal.queue.size items remaining (default 1000)
                    while (writerThread.isAlive() && !writerThread.isInterrupted() && !interruptFound.get()
                            && !Thread.currentThread().isInterrupted() && !rw.finalised()
                            && !((System.currentTimeMillis()
                                    - completionStartTime) > downloadMaxCompletionTime)) {
                        Thread.sleep(downloadCheckBusyWaitSleep);
                    }
                } finally {
                    try {
                        // Attempt all actions that could trigger the writer thread to finalise, as by this stage we are in hard shutdown mode

                        // Signal that we are in hard shutdown mode
                        interruptFound.set(true);

                        // Add the sentinel or clear the queue and try again until it gets onto the queue
                        // We are in hard shutdown mode, so only priority is that the queue either
                        // gets the sentinel or the thread is interrupted to clean up resources
                        while (!queue.offer(sentinel)) {
                            queue.clear();
                        }

                        // Interrupt the single writer thread
                        writerThread.interrupt();

                        // Explicitly call finalise on the RecordWriter as a backup
                        // In normal circumstances it is called via the sentinel or the interrupt
                        // This will not block if finalise has been called previously in the current three implementations
                        rw.finalise();
                    } finally {
                        if (rw != null && rw.hasError()) {
                            throw RecordWriterException.newRecordWriterException(dd, downloadParams, true, rw);
                        } else {
                            // Flush whatever output was still pending for more deterministic debugging
                            out.flush();
                        }
                    }
                }
            }
        }
    } catch (SolrServerException ex) {
        logger.error("Problem communicating with SOLR server while processing download. " + ex.getMessage(),
                ex);
    }
    return uidStats;
}

From source file:au.org.ala.biocache.dao.SearchDAOImpl.java

License:Open Source License

/**
 * Downloads the records for the supplied query. Used to break up the download into components
 * 1) 1 call for each data resource that has a download limit (supply the data resource uid as the argument dataResource)
 * 2) 1 call for the remaining records/*from  www .j  av a2  s . c o m*/
 *
 * @param downloadParams
 * @param downloadLimit
 * @param uidStats
 * @param fields
 * @param qaFields
 * @param resultsCount
 * @param dataResource   The dataResource being download.  This should be null if multiple data resource are being downloaded.
 * @return
 * @throws Exception
 */
private int downloadRecords(DownloadRequestParams downloadParams, RecordWriterError writer,
        Map<String, Integer> downloadLimit, ConcurrentMap<String, AtomicInteger> uidStats, String[] fields,
        String[] qaFields, int resultsCount, String dataResource, boolean includeSensitive,
        DownloadDetailsDTO dd, boolean limit, String[] analysisLayers) throws Exception {
    if (logger.isInfoEnabled()) {
        logger.info("download query: " + downloadParams.getQ());
    }
    SolrQuery solrQuery = initSolrQuery(downloadParams, false, null);
    solrQuery.setRows(limit ? MAX_DOWNLOAD_SIZE : -1);
    queryFormatUtils.formatSearchQuery(downloadParams);
    solrQuery.setQuery(downloadParams.getFormattedQuery());
    //Only the fields specified below will be included in the results from the SOLR Query
    solrQuery.setFields("row_key", "institution_uid", "collection_uid", "data_resource_uid",
            "data_provider_uid");

    if (dd != null) {
        dd.resetCounts();
    }

    //get coordinates for analysis layer intersection
    if (analysisLayers.length > 0) {

        if (!includeSensitive && dd.getSensitiveFq() != null) {
            for (String s : sensitiveSOLRHdr)
                solrQuery.addField(s);
        } else {
            for (String s : notSensitiveSOLRHdr)
                solrQuery.addField(s);
        }
    }

    int pageSize = downloadBatchSize;
    StringBuilder sb = new StringBuilder(downloadParams.getFields());
    if (downloadParams.getExtra().length() > 0) {
        sb.append(",").append(downloadParams.getExtra());
    }

    List<SolrQuery> queries = new ArrayList<SolrQuery>();
    queries.add(solrQuery);

    //split into sensitive and non-sensitive queries when
    // - not including all sensitive values
    // - there is a sensitive fq
    List<SolrQuery> sensitiveQ = new ArrayList<SolrQuery>();
    if (!includeSensitive && dd.getSensitiveFq() != null) {
        sensitiveQ = splitQueries(queries, dd.getSensitiveFq(), null, null);
    }

    final String[] sensitiveFields;
    final String[] notSensitiveFields;
    if (!includeSensitive && dd.getSensitiveFq() != null) {
        //lookup for fields from sensitive queries
        sensitiveFields = org.apache.commons.lang3.ArrayUtils.addAll(fields, sensitiveCassandraHdr);

        //use general fields when sensitive data is not permitted
        notSensitiveFields = org.apache.commons.lang3.ArrayUtils.addAll(fields, notSensitiveCassandraHdr);
    } else {
        sensitiveFields = new String[0];
        notSensitiveFields = fields;
    }

    for (SolrQuery q : queries) {
        int startIndex = 0;

        String[] fq = downloadParams.getFormattedFq();
        if (q.getFilterQueries() != null && q.getFilterQueries().length > 0) {
            if (fq == null) {
                fq = new String[0];
            }
            fq = org.apache.commons.lang3.ArrayUtils.addAll(fq, q.getFilterQueries());
        }

        QueryResponse qr = runSolrQuery(q, fq, pageSize, startIndex, "_docid_", "asc");
        List<String> uuids = new ArrayList<String>();

        List<String[]> intersectionAll = intersectResults(dd.getRequestParams().getLayersServiceUrl(),
                analysisLayers, qr.getResults());

        while (qr.getResults().size() > 0 && (!limit || resultsCount < MAX_DOWNLOAD_SIZE)
                && shouldDownload(dataResource, downloadLimit, false)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Start index: " + startIndex);
            }

            Map<String, String[]> dataToInsert = new HashMap<String, String[]>();

            //cycle through the results adding them to the list that will be sent to cassandra
            int row = 0;
            for (SolrDocument sd : qr.getResults()) {
                if (sd.getFieldValue("data_resource_uid") != null) {
                    String druid = sd.getFieldValue("data_resource_uid").toString();
                    if (shouldDownload(druid, downloadLimit, true)
                            && (!limit || resultsCount < MAX_DOWNLOAD_SIZE)) {
                        resultsCount++;
                        uuids.add(sd.getFieldValue("row_key").toString());

                        //include analysis layer intersections
                        if (intersectionAll.size() > row + 1)
                            dataToInsert.put(sd.getFieldValue("row_key").toString(),
                                    (String[]) ArrayUtils.subarray(intersectionAll.get(row + 1), 2,
                                            intersectionAll.get(row + 1).length));

                        //increment the counters....
                        incrementCount(uidStats, sd.getFieldValue("institution_uid"));
                        incrementCount(uidStats, sd.getFieldValue("collection_uid"));
                        incrementCount(uidStats, sd.getFieldValue("data_provider_uid"));
                        incrementCount(uidStats, druid);
                    }
                }
                row++;
            }

            String[] newMiscFields;
            if (sensitiveQ.contains(q)) {
                newMiscFields = au.org.ala.biocache.Store.writeToWriter(writer, uuids.toArray(new String[] {}),
                        sensitiveFields, qaFields, true,
                        (dd.getRequestParams() != null ? dd.getRequestParams().getIncludeMisc() : false),
                        dd.getMiscFields(), dataToInsert);
            } else {
                newMiscFields = au.org.ala.biocache.Store.writeToWriter(writer, uuids.toArray(new String[] {}),
                        notSensitiveFields, qaFields, includeSensitive,
                        (dd.getRequestParams() != null ? dd.getRequestParams().getIncludeMisc() : false),
                        dd.getMiscFields(), dataToInsert);
            }

            //test for errors
            if (writer.hasError()) {
                throw RecordWriterException.newRecordWriterException(dd, downloadParams, false, writer);
            }

            dd.setMiscFields(newMiscFields);
            startIndex += pageSize;
            uuids.clear();
            dd.updateCounts(qr.getResults().size());
            if (!limit || resultsCount < MAX_DOWNLOAD_SIZE) {
                //we have already set the Filter query the first time the query was constructed rerun with he same params but different startIndex
                qr = runSolrQuery(q, null, pageSize, startIndex, "_docid_", "asc");
            }
        }
    }
    return resultsCount;
}

From source file:au.org.ala.biocache.dao.SearchDAOImpl.java

License:Open Source License

/**
 * Split a list of queries by a fq./*from w  w  w . j a v  a2 s  .  c om*/
 */
private List<SolrQuery> splitQueries(List<SolrQuery> queries, String fq, String[] fqFields,
        String[] notFqFields) {
    List<SolrQuery> notFQ = new ArrayList<SolrQuery>();
    List<SolrQuery> fQ = new ArrayList<SolrQuery>();

    for (SolrQuery query : queries) {
        SolrQuery nsq = query.getCopy().addFilterQuery("-(" + fq + ")");
        if (notFqFields != null) {
            for (String field : notFqFields)
                nsq.addField(field);
        }
        notFQ.add(nsq);

        SolrQuery sq = query.getCopy().addFilterQuery(fq);
        if (fqFields != null) {
            for (String field : fqFields)
                sq.addField(field);
        }
        fQ.add(sq);
    }

    queries.clear();
    queries.addAll(notFQ);
    queries.addAll(fQ);

    return fQ;
}

From source file:com.comm.sr.common.solr.SolrQueryGenerator.java

@Override
public SolrQuery generateFinalQuery(SolrCommonQuery query_) {
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setParam("collection", query_.getCollectionName());
    SubQuery query = query_.getSubQuery();
    if (query == null) {
        return solrQuery;
    }//ww w .  jav a  2s.c o m
    StringBuffer solrQueryBuffer = new StringBuffer();
    makeFinalSolrQuery(query, solrQueryBuffer);

    int pageNum = query_.getPageNum();
    if (pageNum < 1) {
        // default first page
        pageNum = 1;
    } else {
        pageNum = query_.getPageNum();
    }
    List<SortItem> sortItems = query_.getSortItems();
    if (sortItems == null) {
        sortItems = Lists.newArrayList();
    }
    for (String functionQueryString : query_.getFunctionQuerysList()) {

        solrQueryBuffer.append("_query_:\"{!func}" + functionQueryString + "\"" + " AND ");

    }
    if (solrQueryBuffer.toString().contains("AND")) {

        int and = solrQueryBuffer.lastIndexOf("AND");
        solrQueryBuffer.replace(and, and + 3, "");
    }
    if (solrQueryBuffer.toString().trim().length() == 0) {
        solrQueryBuffer.append("*:*");
    }
    for (SortItem sortItem : sortItems) {
        String fieldName = sortItem.getFieldName();
        String order = sortItem.getSort();

        if (order == null) {
            LOGGER.info("ingore sort fieldName:" + fieldName + ", please configure it.");
            continue;
        }
        if (order.trim().equals("asc")) {
            solrQuery.setSort(fieldName, SolrQuery.ORDER.asc);
        }
        if (order.trim().equals("desc")) {
            solrQuery.addSort(fieldName, SolrQuery.ORDER.desc);

        }

    }

    for (String fl : query_.getFls()) {
        solrQuery.addField(fl);

    }
    int pageSize = query_.getPageSize();
    solrQuery.add("start", String.valueOf((pageNum - 1) * pageSize));
    solrQuery.add("rows", String.valueOf(pageSize));

    // if have distance query
    // fq=_query_:%22{!geofilt}%22&sfield=location&pt=45.15,-93.85&d=50000&sort=geodist()%20asc&fl=score,geodist(),location
    String location = query_.getLocationPoint();
    Double distance = query_.getDistance();

    if (location != null && distance != null) {
        solrQuery.add("d", distance.toString());
        solrQuery.add("pt", location);
        solrQuery.add("sfield", "location");
        solrQuery.add("fq", "_query_:{!geofilt}");
        solrQuery.addSort("geodist()", SolrQuery.ORDER.asc);

    }
    LOGGER.info(solrQueryBuffer.toString());
    solrQuery.setQuery(solrQueryBuffer.toString());

    return solrQuery;
}

From source file:com.comm.sr.service.solr.SolrQueryGenerator.java

@Override
public SolrQuery generateFinalQuery(CommonQuery query) {
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder queryStr = new StringBuilder();
    StringBuilder filterQueryStr = new StringBuilder();

    int pageNum = query.getPageNum();
    if (pageNum < 1) {
        // default first page
        pageNum = 1;/*from   w w  w  .  j a  va 2  s .c  o m*/
    } else {
        pageNum = query.getPageNum();
    }
    List<QueryItem> queryItems = query.getQueryItems();
    if (queryItems == null) {
        queryItems = Lists.newArrayList();
    }

    List<SortItem> sortItems = query.getSortItems();
    if (sortItems == null) {
        sortItems = Lists.newArrayList();
    }
    for (QueryItem queryItem : queryItems) {
        if (queryItem.isIsFilterType()) {
            String temp = generateQueryStrFromQueryItem(queryItem);
            if (temp != null) {
                filterQueryStr.append(temp + " AND ");

            }
        }
        if (!queryItem.isIsFilterType()) {
            String temp = generateQueryStrFromQueryItem(queryItem);
            if (temp != null) {
                queryStr.append(temp + " AND ");

            }
        }

    }

    for (String functionQueryString : query.getFunctionQuerysList()) {

        queryStr.append("_query_:\"{!func}" + functionQueryString + "\"" + " AND ");

    }
    // check if final queryStr is empty
    if (queryStr.toString().trim().length() == 0) {
        queryStr.append("*:*");
    }

    // delete last AND
    if (queryStr.toString().contains("AND")) {

        int and = queryStr.lastIndexOf("AND");
        queryStr.replace(and, and + 3, "");
    }
    if (filterQueryStr.toString().contains("AND")) {
        int and = filterQueryStr.lastIndexOf("AND");
        filterQueryStr.replace(and, and + 3, "");
    }
    for (SortItem sortItem : sortItems) {
        String fieldName = sortItem.getFieldName();
        String order = sortItem.getSort();

        if (order == null) {
            LOGGER.info("ingore sort fieldName:" + fieldName + ", please configure it.");
            continue;
        }
        if (order.trim().equals("asc")) {
            solrQuery.setSort(fieldName, SolrQuery.ORDER.asc);
        }
        if (order.trim().equals("desc")) {
            solrQuery.addSort(fieldName, SolrQuery.ORDER.desc);

        }

    }

    solrQuery.setQuery(queryStr.toString());
    if (filterQueryStr.toString().length() != 0) {
        solrQuery.setFilterQueries(filterQueryStr.toString());

    }

    LOGGER.debug("final queryStr is:" + queryStr.toString() + "");
    LOGGER.debug("filter queryStr is:" + filterQueryStr.toString() + "");
    // //only response userID,score
    // solrQuery.setFields("userID","score");
    for (String fl : query.getFls()) {
        solrQuery.addField(fl);

    }
    int pageSize = query.getPageSize();
    solrQuery.add("start", String.valueOf((pageNum - 1) * pageSize));
    solrQuery.add("rows", String.valueOf(pageSize));
    // if have distance query
    // fq=_query_:%22{!geofilt}%22&sfield=location&pt=45.15,-93.85&d=50000&sort=geodist()%20asc&fl=score,geodist(),location
    String location = query.getLocationPoint();
    Double distance = query.getDistance();

    if (location != null && distance != null) {
        solrQuery.add("d", distance.toString());
        solrQuery.add("pt", location);
        solrQuery.add("sfield", "location");
        solrQuery.add("fq", "_query_:{!geofilt}");
        solrQuery.addSort("geodist()", SolrQuery.ORDER.asc);

    }

    return solrQuery;
}

From source file:com.eharmony.matching.seeking.executor.solr.SolrQueryExecutor.java

License:Apache License

protected <T, R> SolrQuery translate(Query<T, R> query) {
    SolrQuery solrQuery = new SolrQuery();
    // special geospatial query case
    SolrSpatialQuery spatialQuery = queryTranslator.getSpatialQuery(query);
    String translated = queryTranslator.translate(query);
    solrQuery.setQuery(translated == null || translated.isEmpty() ? "*:*" : translated);
    if (spatialQuery != null) {
        //solrQuery.addFilterQuery("{!func}geodist()"); 
        solrQuery.addFilterQuery("{!geofilt}");
        solrQuery.set("sfield", spatialQuery.getField());
        solrQuery.set("pt", spatialQuery.getX() + "," + spatialQuery.getY());
        solrQuery.set("d", spatialQuery.getDistance().toString());
    }/*from w w w . j  ava  2  s .  c  o m*/
    for (SolrOrdering ordering : queryTranslator.translateOrder(query).get()) {
        String field = ordering.getField();
        if (spatialQuery != null && field.equals(spatialQuery.getField())) {
            field = "geodist()";
        }
        solrQuery.addSortField(field, ordering.getOrder());
    }
    for (String field : queryTranslator.translateProjection(query)) {
        solrQuery.addField(field);
    }
    if (query.getMaxResults() != null) {
        solrQuery.setRows(query.getMaxResults());
    }
    return solrQuery;
}

From source file:com.mmj.app.lucene.solr.utils.BaseSolrQueryConvert.java

License:Open Source License

public static SolrQuery createSuggestQuery(SuggestQuery query) {
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder sb = new StringBuilder();
    sb.append("suggest:").append(query.getPrefix()).append("*");
    solrQuery.setQuery(sb.toString());// ww  w  . jav a  2 s  . c  o  m
    solrQuery.addField(query.getField());
    if (StringUtils.isNotEmpty(query.getSortFiled())) {
        solrQuery.addSort(query.getSortFiled(), SolrQuery.ORDER.desc);
    }
    solrQuery.setStart(0);
    solrQuery.setRows(100);
    return solrQuery;
}

From source file:com.temenos.interaction.commands.solr.SolrSearchCommand.java

License:Open Source License

private void addSelect(SolrQuery query, MultivaluedMap<String, String> queryParams) {

    // If we were passed an OData $select parse it and add to the query
    String selectOption = queryParams.getFirst(ODataParser.SELECT_KEY);
    if (null != selectOption) {
        // Its a comma separated list of fields.
        Set<FieldName> fields = ODataParser.parseSelect(selectOption);

        logger.info("Adding selects:");
        for (FieldName field : fields) {
            logger.info("    " + field.getName());
            query.addField(field.getName());
        }/*from   w w w  . j av  a2 s. c om*/
    }
    return;
}

From source file:com.tripod.solr.query.StandardSolrQueryTransformer.java

License:Apache License

@Override
public SolrQuery transform(final Q query) {
    final SolrQuery solrQuery = new SolrQuery(query.getQuery());
    solrQuery.setStart(query.getOffset());
    solrQuery.setRows(query.getRows());//  w  w w  .  j  a  v a 2 s . com
    solrQuery.setParam("q.op", query.getDefaultOperator().name());

    if (query.getReturnFields() != null) {
        query.getReturnFields().stream().forEach(f -> solrQuery.addField(f.getName()));
    }

    if (query.getHighlightFields() != null && !query.getHighlightFields().isEmpty()) {
        solrQuery.setHighlight(true);
        query.getHighlightFields().stream().forEach(hf -> solrQuery.addHighlightField(hf.getName()));
    }

    if (query.getFacetFields() != null) {
        query.getFacetFields().stream().forEach(ff -> solrQuery.addFacetField(ff.getName()));
    }

    if (query.getSorts() != null) {
        for (Sort sort : query.getSorts()) {
            SolrQuery.ORDER solrOrder = sort.getSortOrder() == SortOrder.ASC ? SolrQuery.ORDER.asc
                    : SolrQuery.ORDER.desc;
            SolrQuery.SortClause sortClause = new SolrQuery.SortClause(sort.getField().getName(), solrOrder);
            solrQuery.addSort(sortClause);
        }
    }

    if (query.getFilterQueries() != null) {
        query.getFilterQueries().stream().forEach(fq -> solrQuery.addFilterQuery(fq));
    }

    if (query.getParams() != null) {
        query.getParams().entrySet().stream().forEach(e -> solrQuery.add(e.getKey(), e.getValue()));
    }

    return solrQuery;
}

From source file:com.zb.app.external.lucene.solr.utils.BaseSolrQueryConvert.java

License:Open Source License

public static SolrQuery createSuggestQuery(SuggestQuery query) {
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder sb = new StringBuilder();
    sb.append("suggest:").append(query.getPrefix()).append("*");
    solrQuery.setQuery(sb.toString());//from  www  . j  a  va 2  s.c o m
    solrQuery.addField(query.getField());
    if (StringUtils.isNotEmpty(query.getSortFiled())) {
        solrQuery.addSort(query.getSortFiled(), SolrQuery.ORDER.desc);
    }
    solrQuery.setStart(0);
    solrQuery.setRows(100);

    // solrQuery.set("qt", "/terms");
    // solrQuery.setFacet(true);
    // solrQuery.setFacetMinCount(1);
    // solrQuery.setFacetLimit(10);
    // solrQuery.setFacetPrefix(query.getField(), query.getPrefix());
    // solrQuery.setFacetSort(query.getSortFiled());
    // solrQuery.setRows(0);
    // solrQuery.setQuery("*");

    // solrQuery.setTerms(true);
    // solrQuery.setTermsLimit(10);
    // solrQuery.setTermsMinCount(1);
    // solrQuery.setTermsPrefix(query.getPrefix());
    // solrQuery.setTermsRegexFlag(query.getField());
    // solrQuery.setTermsSortString(query.getSortFiled());
    return solrQuery;
}