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

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

Introduction

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

Prototype

public SolrQuery setRequestHandler(String qt) 

Source Link

Document

The Request Handler to use (see the solrconfig.xml), which is stored in the "qt" parameter.

Usage

From source file:nl.b3p.viewer.search.SolrSearchClient.java

License:Open Source License

@Override
public SearchResult search(String term) {
    SearchResult result = new SearchResult();
    JSONArray respDocs = new JSONArray();
    try {// ww  w  .j a  v a  2 s .  com
        if (term == null) {
            term = "";
        } else {
            term = term.replaceAll("\\:", "\\\\:");
            term += " AND (";
        }
        SolrServer server = SolrInitializer.getServerInstance();
        String extraQuery = createAttributeSourceQuery();
        if (!extraQuery.isEmpty()) {
            term += extraQuery + ")";
        } else {
            term += "searchConfig:\\-1)"; // Dummy expression to always evaluate to false and return no results
        }
        SolrQuery query = new SolrQuery();
        query.setQuery(term);
        query.setRequestHandler("/select");
        QueryResponse rsp = server.query(query);
        SolrDocumentList list = rsp.getResults();

        for (SolrDocument solrDocument : list) {
            JSONObject doc = solrDocumentToResult(solrDocument);
            if (doc != null) {
                respDocs.put(doc);
            }
        }
        result.setResults(respDocs);
        result.setLimitReached(list.getNumFound() > list.size());

    } catch (SolrServerException ex) {
        Logger.getLogger(SolrSearchClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(SolrSearchClient.class.getName()).log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:nl.b3p.viewer.search.SolrSearchClient.java

License:Open Source License

@Override
public JSONArray autosuggest(String term) throws JSONException {
    JSONObject obj = new JSONObject();
    JSONArray respDocs = new JSONArray();
    try {/*from  ww  w.  ja  v a2  s.  c o m*/
        SolrServer server = SolrInitializer.getServerInstance();

        JSONObject response = new JSONObject();
        response.put("docs", respDocs);
        obj.put("response", response);
        String extraQuery = createAttributeSourceQuery();
        term += " AND (";
        if (!extraQuery.isEmpty()) {
            term += extraQuery + ")";
        } else {
            term += "searchConfig:\\-1)"; // Dummy expression to always evaluate to false and return no results
        }
        SolrQuery query = new SolrQuery();
        query.setQuery(term);
        query.setRequestHandler("/select");
        QueryResponse rsp = server.query(query);
        SolrDocumentList list = rsp.getResults();

        for (SolrDocument solrDocument : list) {
            JSONObject doc = solrDocumentToAutosuggest(solrDocument);
            if (doc != null) {
                respDocs.put(doc);
            }
        }
        response.put("docs", respDocs);
        return respDocs;
    } catch (SolrServerException ex) {
        Logger.getLogger(SolrSearchClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    return respDocs;
}

From source file:org.apache.jackrabbit.oak.plugins.index.solr.query.FilterQueryParser.java

License:Apache License

static SolrQuery getQuery(Filter filter, QueryIndex.IndexPlan plan, OakSolrConfiguration configuration) {

    SolrQuery solrQuery = new SolrQuery();
    setDefaults(solrQuery, configuration);

    StringBuilder queryBuilder = new StringBuilder();

    FullTextExpression ft = filter.getFullTextConstraint();
    if (ft != null) {
        queryBuilder.append(parseFullTextExpression(ft, configuration));
        queryBuilder.append(' ');
    } else if (filter.getFulltextConditions() != null) {
        Collection<String> fulltextConditions = filter.getFulltextConditions();
        for (String fulltextCondition : fulltextConditions) {
            queryBuilder.append(fulltextCondition).append(" ");
        }/*ww  w .  j  av  a  2 s  .c o  m*/
    }

    List<QueryIndex.OrderEntry> sortOrder = plan.getSortOrder();
    if (sortOrder != null) {
        for (QueryIndex.OrderEntry orderEntry : sortOrder) {
            SolrQuery.ORDER order;
            if (QueryIndex.OrderEntry.Order.ASCENDING.equals(orderEntry.getOrder())) {
                order = SolrQuery.ORDER.asc;
            } else {
                order = SolrQuery.ORDER.desc;
            }
            String sortingField;
            if (JcrConstants.JCR_PATH.equals(orderEntry.getPropertyName())) {
                sortingField = partialEscape(configuration.getPathField()).toString();
            } else if (JcrConstants.JCR_SCORE.equals(orderEntry.getPropertyName())) {
                sortingField = "score";
            } else {
                if (orderEntry.getPropertyName().indexOf('/') >= 0) {
                    log.warn("cannot sort on relative properties, ignoring {} clause", orderEntry);
                    continue; // sorting by relative properties not supported until index time aggregation is supported
                }
                sortingField = partialEscape(
                        getSortingField(orderEntry.getPropertyType().tag(), orderEntry.getPropertyName()))
                                .toString();
            }
            solrQuery.addOrUpdateSort(sortingField, order);
        }
    }

    Collection<Filter.PropertyRestriction> propertyRestrictions = filter.getPropertyRestrictions();
    if (propertyRestrictions != null && !propertyRestrictions.isEmpty()) {
        for (Filter.PropertyRestriction pr : propertyRestrictions) {
            if (pr.isNullRestriction()) {
                // can not use full "x is null"
                continue;
            }
            // facets
            if (QueryImpl.REP_FACET.equals(pr.propertyName)) {
                solrQuery.setFacetMinCount(1);
                solrQuery.setFacet(true);
                String value = pr.first.getValue(Type.STRING);
                solrQuery.addFacetField(
                        value.substring(QueryImpl.REP_FACET.length() + 1, value.length() - 1) + "_facet");
            }

            // native query support
            if (SolrQueryIndex.NATIVE_SOLR_QUERY.equals(pr.propertyName)
                    || SolrQueryIndex.NATIVE_LUCENE_QUERY.equals(pr.propertyName)) {
                String nativeQueryString = String.valueOf(pr.first.getValue(pr.first.getType()));
                if (isSupportedHttpRequest(nativeQueryString)) {
                    // pass through the native HTTP Solr request
                    String requestHandlerString = nativeQueryString.substring(0,
                            nativeQueryString.indexOf('?'));
                    if (!"select".equals(requestHandlerString)) {
                        if (requestHandlerString.charAt(0) != '/') {
                            requestHandlerString = "/" + requestHandlerString;
                        }
                        solrQuery.setRequestHandler(requestHandlerString);
                    }
                    String parameterString = nativeQueryString.substring(nativeQueryString.indexOf('?') + 1);
                    for (String param : parameterString.split("&")) {
                        String[] kv = param.split("=");
                        if (kv.length != 2) {
                            throw new RuntimeException("Unparsable native HTTP Solr query");
                        } else {
                            // more like this
                            if ("/mlt".equals(requestHandlerString)) {
                                if ("stream.body".equals(kv[0])) {
                                    kv[0] = "q";
                                    String mltFlString = "mlt.fl=";
                                    int mltFlIndex = parameterString.indexOf(mltFlString);
                                    if (mltFlIndex > -1) {
                                        int beginIndex = mltFlIndex + mltFlString.length();
                                        int endIndex = parameterString.indexOf('&', beginIndex);
                                        String fields;
                                        if (endIndex > beginIndex) {
                                            fields = parameterString.substring(beginIndex, endIndex);
                                        } else {
                                            fields = parameterString.substring(beginIndex);
                                        }
                                        kv[1] = "_query_:\"{!dismax qf=" + fields + " q.op=OR}" + kv[1] + "\"";
                                    }
                                }
                                if ("mlt.fl".equals(kv[0]) && ":path".equals(kv[1])) {
                                    // rep:similar passes the path of the node to find similar documents for in the :path
                                    // but needs its indexed content to find similar documents
                                    kv[1] = configuration.getCatchAllField();
                                }
                            }
                            if ("/spellcheck".equals(requestHandlerString)) {
                                if ("term".equals(kv[0])) {
                                    kv[0] = "spellcheck.q";
                                }
                                solrQuery.setParam("spellcheck", true);
                            }
                            if ("/suggest".equals(requestHandlerString)) {
                                if ("term".equals(kv[0])) {
                                    kv[0] = "suggest.q";
                                }
                                solrQuery.setParam("suggest", true);
                            }
                            solrQuery.setParam(kv[0], kv[1]);
                        }
                    }
                    return solrQuery;
                } else {
                    queryBuilder.append(nativeQueryString);
                }
            } else {
                if (SolrQueryIndex.isIgnoredProperty(pr, configuration)) {
                    continue;
                }

                String first = null;
                if (pr.first != null) {
                    first = partialEscape(String.valueOf(pr.first.getValue(pr.first.getType()))).toString();
                }
                String last = null;
                if (pr.last != null) {
                    last = partialEscape(String.valueOf(pr.last.getValue(pr.last.getType()))).toString();
                }

                String prField = configuration.getFieldForPropertyRestriction(pr);
                CharSequence fieldName = partialEscape(prField != null ? prField : pr.propertyName);
                if ("jcr\\:path".equals(fieldName.toString())) {
                    queryBuilder.append(configuration.getPathField());
                    queryBuilder.append(':');
                    queryBuilder.append(first);
                } else {
                    if (pr.first != null && pr.last != null && pr.first.equals(pr.last)) {
                        queryBuilder.append(fieldName).append(':');
                        queryBuilder.append(first);
                    } else if (pr.first == null && pr.last == null) {
                        if (!queryBuilder.toString().contains(fieldName + ":")) {
                            queryBuilder.append(fieldName).append(':');
                            queryBuilder.append('*');
                        }
                    } else if ((pr.first != null && pr.last == null) || (pr.last != null && pr.first == null)
                            || (!pr.first.equals(pr.last))) {
                        // TODO : need to check if this works for all field types (most likely not!)
                        queryBuilder.append(fieldName).append(':');
                        queryBuilder.append(createRangeQuery(first, last, pr.firstIncluding, pr.lastIncluding));
                    } else if (pr.isLike) {
                        // TODO : the current parameter substitution is not expected to work well
                        queryBuilder.append(fieldName).append(':');
                        queryBuilder.append(partialEscape(String.valueOf(pr.first.getValue(pr.first.getType()))
                                .replace('%', '*').replace('_', '?')));
                    } else {
                        throw new RuntimeException("[unexpected!] not handled case");
                    }
                }
            }
            queryBuilder.append(" ");
        }
    }

    if (configuration.useForPrimaryTypes()) {
        String[] pts = filter.getPrimaryTypes().toArray(new String[filter.getPrimaryTypes().size()]);
        StringBuilder ptQueryBuilder = new StringBuilder();
        for (int i = 0; i < pts.length; i++) {
            String pt = pts[i];
            if (i == 0) {
                ptQueryBuilder.append("(");
            }
            if (i > 0 && i < pts.length) {
                ptQueryBuilder.append("OR ");
            }
            ptQueryBuilder.append("jcr\\:primaryType").append(':').append(partialEscape(pt)).append(" ");
            if (i == pts.length - 1) {
                ptQueryBuilder.append(")");
                ptQueryBuilder.append(' ');
            }
        }
        solrQuery.addFilterQuery(ptQueryBuilder.toString());
    }

    if (filter.getQueryStatement() != null && filter.getQueryStatement().contains(QueryImpl.REP_EXCERPT)) {
        if (!solrQuery.getHighlight()) {
            // enable highlighting
            solrQuery.setHighlight(true);
            // defaults
            solrQuery.set("hl.fl", "*");
            solrQuery.set("hl.encoder", "html");
            solrQuery.set("hl.mergeContiguous", true);
            solrQuery.setHighlightSimplePre("<strong>");
            solrQuery.setHighlightSimplePost("</strong>");
        }
    }

    if (configuration.useForPathRestrictions()) {
        Filter.PathRestriction pathRestriction = filter.getPathRestriction();
        if (pathRestriction != null) {
            String path = purgePath(filter, plan.getPathPrefix());
            String fieldName = configuration.getFieldForPathRestriction(pathRestriction);
            if (fieldName != null) {
                if (pathRestriction.equals(Filter.PathRestriction.ALL_CHILDREN)) {
                    solrQuery.addFilterQuery(fieldName + ':' + path);
                } else {
                    queryBuilder.append(fieldName);
                    queryBuilder.append(':');
                    queryBuilder.append(path);
                }
            }
        }
    }

    if (configuration.collapseJcrContentNodes()) {
        solrQuery.addFilterQuery("{!collapse field=" + configuration.getCollapsedPathField() + " min="
                + configuration.getPathDepthField() + " hint=top_fc nullPolicy=expand}");
    }

    if (queryBuilder.length() == 0) {
        queryBuilder.append("*:*");
    }
    String escapedQuery = queryBuilder.toString();
    solrQuery.setQuery(escapedQuery);

    if (log.isDebugEnabled()) {
        log.debug("JCR query {} has been converted to Solr query {}", filter.getQueryStatement(),
                solrQuery.toString());
    }

    return solrQuery;
}

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

License:Apache License

private String getFieldNameOfUniqueKey() {
    final SolrQuery solrQuery = new SolrQuery();
    try {//from www.j a v a2 s . c o m
        solrQuery.setRequestHandler("/schema/uniquekey");
        final QueryRequest req = new QueryRequest(solrQuery);
        if (isBasicAuthEnabled()) {
            req.setBasicAuthCredentials(getUsername(), getPassword());
        }

        return (req.process(getSolrClient()).getResponse().get("uniqueKey").toString());
    } catch (SolrServerException | IOException e) {
        getLogger().error("Solr query to retrieve uniqueKey-field failed due to {}",
                new Object[] { solrQuery.toString(), e }, e);
        throw new ProcessException(e);
    }
}

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 ww  w .  j  a v  a 2s .c  om

    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.apache.ranger.services.solr.client.ServiceSolrClient.java

License:Apache License

public List<String> getFieldList(String collection, List<String> ignoreFieldList) throws Exception {
    // TODO: Best is to get the collections based on the collection value
    // which could contain wild cards
    String queryStr = "";
    if (collection != null && !collection.isEmpty()) {
        queryStr += "/" + collection;
    }/*from w ww  . java 2 s .c  om*/
    queryStr += "/schema/fields";
    SolrQuery query = new SolrQuery();
    query.setRequestHandler(queryStr);
    QueryResponse response = solrClient.query(query);

    List<String> fieldList = new ArrayList<String>();
    if (response != null && response.getStatus() == 0) {
        @SuppressWarnings("unchecked")
        List<SimpleOrderedMap<String>> fields = (ArrayList<SimpleOrderedMap<String>>) response.getResponse()
                .get("fields");
        for (SimpleOrderedMap<String> fmap : fields) {
            String fieldName = fmap.get("name");
            if (ignoreFieldList == null || !ignoreFieldList.contains(fieldName)) {
                fieldList.add(fieldName);
            }
        }
    } else {
        LOG.error("Error getting fields for collection=" + collection + ", response=" + response);
    }
    return fieldList;
}

From source file:org.intermine.web.autocompletion.AutoCompleter.java

License:GNU General Public License

/**
 * Returns n search results/*from   www.  jav  a2  s  .c  o  m*/
 * @param query is the string used for search
 * @param field is the field in which you like to search (e.g. name)
 * @param className is the class in which you like to search (e.g. SOTerm)
 * @param n number of the first n search results
 * @return string array with search results and an error flag at position 0
 */
public String[] getFastList(String query, String field, String className, int n) {

    String status = "true";
    String[] stringResults = null;

    SolrClient solrClient = SolrClientHandler.getClientInstance(this.propertiesManager.getSolrUrl());

    QueryResponse resp = null;

    if (!"".equals(query) && !query.trim().startsWith("*")) {

        if (query.endsWith(" ")) {
            query = query.substring(0, query.length() - 1);
        }

        String[] tmp;
        if (query.contains(" ")) {
            tmp = query.replaceAll(" +", " ").trim().split(" ");
            query = new String();

            for (int i = 0; i < tmp.length; i++) {
                query += tmp[i];
                if (i < tmp.length - 1) {
                    query += "* AND " + field + ":";
                }
            }
        }

        try {

            SolrQuery newQuery = new SolrQuery();
            newQuery.setQuery(field + ":" + query + "*"); //adding a wildcard in the end
            newQuery.setRequestHandler("select");
            newQuery.setRows(n); // FIXME: hardcoded maximum
            newQuery.setFilterQueries(CLASSNAME_FIELD + ":" + className);

            resp = solrClient.query(newQuery);

            SolrDocumentList results = resp.getResults();

            stringResults = new String[results.size() + 1];

            for (int i = 1; i < results.size() + 1; i++) {

                try {
                    SolrDocument document = results.get(i - 1);

                    stringResults[i] = ((ArrayList<String>) document.getFieldValue(field)).get(0);

                } catch (Exception e) {
                    status = "No results! Please try again.";
                }
            }

            stringResults[0] = status;

            return stringResults;

        } catch (SolrServerException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
            status = "Please type in more characters to get results.";
            stringResults = new String[1];
            stringResults[0] = status;
        }

        return stringResults;
    }

    return null;
}

From source file:org.mousephenotype.cda.indexers.AbstractIndexer.java

License:Apache License

public long getImitsDocumentCount(SolrClient solrClient) throws IndexerException {
    Long numFound = getDocumentCount(solrClient);
    SolrQuery query = new SolrQuery().setQuery("*:*").setRows(0);
    query.setRequestHandler("selectCre");
    try {/*from w ww.  j av  a  2s  . co  m*/
        numFound += solrClient.query(query).getResults().getNumFound();
    } catch (SolrServerException | IOException e) {
        throw new IndexerException(e);
    }
    logger.debug("number found = " + numFound);
    return numFound;
}

From source file:org.opencms.search.solr.spellchecking.CmsSolrSpellchecker.java

License:Open Source License

/**
 * Performs the actual spell check query using Solr.
 *
 * @param request the spell check request
 *
 * @return Results of the Solr spell check of type SpellCheckResponse or null if something goes wrong.
 *//*from  w ww . ja  v a  2 s .co m*/
private SpellCheckResponse performSpellcheckQuery(CmsSpellcheckingRequest request) {

    if ((null == request) || !request.isInitialized()) {
        return null;
    }

    final String[] wordsToCheck = request.m_wordsToCheck;

    final ModifiableSolrParams params = new ModifiableSolrParams();
    params.set("spellcheck", "true");
    params.set("spellcheck.dictionary", request.m_dictionaryToUse);
    params.set("spellcheck.extendedResults", "true");

    // Build one string from array of words and use it as query.
    final StringBuilder builder = new StringBuilder();
    for (int i = 0; i < wordsToCheck.length; i++) {
        builder.append(wordsToCheck[i] + " ");
    }

    params.set("spellcheck.q", builder.toString());

    final SolrQuery query = new SolrQuery();
    query.setRequestHandler("/spell");
    query.add(params);

    try {
        QueryResponse qres = m_solrClient.query(query);
        return qres.getSpellCheckResponse();
    } catch (Exception e) {
        LOG.debug("Exception while performing spellcheck query...", e);
    }

    return null;
}

From source file:org.opencommercesearch.AbstractSearchServer.java

License:Apache License

@Override
public SearchResponse termVector(String query, Locale locale, String... fields) throws SearchServerException {
    SolrQuery solrQuery = new SolrQuery(query);
    solrQuery.setRequestHandler("/tvrh");
    solrQuery.setFields(fields);//from  ww w.ja v  a 2 s .c  o  m
    solrQuery.setParam("tv.fl", "categoryName");

    try {
        QueryResponse queryResponse = getCatalogSolrServer(locale).query(solrQuery);
        return new SearchResponse(solrQuery, queryResponse, null, null, null, null, true);
    } catch (SolrServerException ex) {
        throw create(TERMS_EXCEPTION, ex);
    }
}