Example usage for org.apache.solr.common.params SpellingParams SPELLCHECK_Q

List of usage examples for org.apache.solr.common.params SpellingParams SPELLCHECK_Q

Introduction

In this page you can find the example usage for org.apache.solr.common.params SpellingParams SPELLCHECK_Q.

Prototype

String SPELLCHECK_Q

To view the source code for org.apache.solr.common.params SpellingParams SPELLCHECK_Q.

Click Source Link

Document

Use the value for this parameter as the query to spell check.

Usage

From source file:org.alfresco.solr.component.QueryLoggingComponent.java

License:Open Source License

private void log(ResponseBuilder rb) throws IOException {
    boolean isShard = rb.req.getParams().getBool(ShardParams.IS_SHARD, false);
    if (!isShard) {
        CoreContainer container = rb.req.getCore().getCoreContainer();
        SolrCore logCore = container.getCore(rb.req.getCore().getName() + "_qlog");
        if (logCore != null) {
            JSONObject json = (JSONObject) rb.req.getContext().get(AbstractQParser.ALFRESCO_JSON);

            SolrQueryRequest request = null;
            UpdateRequestProcessor processor = null;
            try {
                request = new LocalSolrQueryRequest(logCore, new NamedList<>());
                processor = logCore.getUpdateProcessingChain(null).createProcessor(request,
                        new SolrQueryResponse());

                AddUpdateCommand cmd = new AddUpdateCommand(request);
                cmd.overwrite = true;//w  w w . jav a2  s. c om
                SolrInputDocument input = new SolrInputDocument();
                input.addField("id", GUID.generate());
                input.addField("_version_", "1");

                input.addField("timestamp", DateTimeFormatter.ISO_INSTANT.format(Instant.now()));

                if (json != null) {
                    try {
                        ArrayList<String> authorityList = new ArrayList<String>(1);
                        JSONArray authorities = json.getJSONArray("authorities");
                        for (int i = 0; i < authorities.length(); i++) {
                            String authorityString = authorities.getString(i);
                            authorityList.add(authorityString);
                        }

                        for (String authority : authorityList) {
                            if (AuthorityType.getAuthorityType(authority) == AuthorityType.USER) {
                                input.addField("user", authority);
                                break;
                            }
                        }
                    } catch (JSONException e) {
                        input.addField("user", "<UNKNOWN>");
                    }
                } else {
                    input.addField("user", "<UNKNOWN>");
                }

                String userQuery = rb.req.getParams().get(SpellingParams.SPELLCHECK_Q);
                if (userQuery == null) {
                    if (json != null) {
                        try {
                            userQuery = json.getString("query");
                        } catch (JSONException e) {
                        }
                    }
                }
                if (userQuery == null) {
                    userQuery = rb.req.getParams().get(CommonParams.Q);
                }

                if (userQuery != null) {
                    input.addField("user_query", userQuery);
                }

                Query query = rb.getQuery();
                input.addField("query", query.toString());

                if (rb.getResults().docList != null) {
                    input.addField("found", rb.getResults().docList.matches());
                }
                input.addField("time", rb.req.getRequestTimer().getTime());

                cmd.solrDoc = input;
                processor.processAdd(cmd);
            }

            finally {
                if (processor != null) {
                    processor.finish();
                }
                if (request != null) {
                    request.close();
                }
            }
        }
    }
}

From source file:org.dspace.discovery.SolrServiceImpl.java

License:BSD License

protected SolrQuery resolveToSolrQuery(Context context, DiscoverQuery discoveryQuery,
        boolean includeUnDiscoverable) {
    SolrQuery solrQuery = new SolrQuery();

    String query = "*:*";
    if (discoveryQuery.getQuery() != null) {
        query = discoveryQuery.getQuery();
    }/*from ww w .j  a va  2s.c  o  m*/

    solrQuery.setQuery(query);
    if (discoveryQuery.isSpellCheck()) {
        solrQuery.setParam(SpellingParams.SPELLCHECK_Q, query);
        solrQuery.setParam(SpellingParams.SPELLCHECK_COLLATE, Boolean.TRUE);
        solrQuery.setParam("spellcheck", Boolean.TRUE);
    }

    if (!includeUnDiscoverable) {
        solrQuery.addFilterQuery("NOT(withdrawn:true)");
        solrQuery.addFilterQuery("NOT(discoverable:false)");
    }

    for (int i = 0; i < discoveryQuery.getFilterQueries().size(); i++) {
        String filterQuery = discoveryQuery.getFilterQueries().get(i);
        solrQuery.addFilterQuery(filterQuery);
    }
    if (discoveryQuery.getDSpaceObjectFilter() != -1) {
        solrQuery.addFilterQuery("search.resourcetype:" + discoveryQuery.getDSpaceObjectFilter());
    }

    for (int i = 0; i < discoveryQuery.getFieldPresentQueries().size(); i++) {
        String filterQuery = discoveryQuery.getFieldPresentQueries().get(i);
        solrQuery.addFilterQuery(filterQuery + ":[* TO *]");
    }

    if (discoveryQuery.getStart() != -1) {
        solrQuery.setStart(discoveryQuery.getStart());
    }

    if (discoveryQuery.getMaxResults() != -1) {
        solrQuery.setRows(discoveryQuery.getMaxResults());
    }

    if (discoveryQuery.getSortField() != null) {
        SolrQuery.ORDER order = SolrQuery.ORDER.asc;
        if (discoveryQuery.getSortOrder().equals(DiscoverQuery.SORT_ORDER.desc))
            order = SolrQuery.ORDER.desc;

        solrQuery.addSortField(discoveryQuery.getSortField(), order);
    }

    for (String property : discoveryQuery.getProperties().keySet()) {
        List<String> values = discoveryQuery.getProperties().get(property);
        solrQuery.add(property, values.toArray(new String[values.size()]));
    }

    List<DiscoverFacetField> facetFields = discoveryQuery.getFacetFields();
    if (0 < facetFields.size()) {
        //Only add facet information if there are any facets
        for (DiscoverFacetField facetFieldConfig : facetFields) {
            String field = transformFacetField(facetFieldConfig, facetFieldConfig.getField(), false);
            solrQuery.addFacetField(field);

            // Setting the facet limit in this fashion ensures that each facet can have its own max
            solrQuery.add("f." + field + "." + FacetParams.FACET_LIMIT,
                    String.valueOf(facetFieldConfig.getLimit()));
            String facetSort;
            if (DiscoveryConfigurationParameters.SORT.COUNT.equals(facetFieldConfig.getSortOrder())) {
                facetSort = FacetParams.FACET_SORT_COUNT;
            } else {
                facetSort = FacetParams.FACET_SORT_INDEX;
            }
            solrQuery.add("f." + field + "." + FacetParams.FACET_SORT, facetSort);
            if (facetFieldConfig.getOffset() != -1) {
                solrQuery.setParam("f." + field + "." + FacetParams.FACET_OFFSET,
                        String.valueOf(facetFieldConfig.getOffset()));
            }
            if (facetFieldConfig.getPrefix() != null) {
                solrQuery.setFacetPrefix(field, facetFieldConfig.getPrefix());
            }
        }

        List<String> facetQueries = discoveryQuery.getFacetQueries();
        for (String facetQuery : facetQueries) {
            solrQuery.addFacetQuery(facetQuery);
        }

        if (discoveryQuery.getFacetMinCount() != -1) {
            solrQuery.setFacetMinCount(discoveryQuery.getFacetMinCount());
        }

        solrQuery.setParam(FacetParams.FACET_OFFSET, String.valueOf(discoveryQuery.getFacetOffset()));
    }

    if (0 < discoveryQuery.getHitHighlightingFields().size()) {
        solrQuery.setHighlight(true);
        solrQuery.add(HighlightParams.USE_PHRASE_HIGHLIGHTER, Boolean.TRUE.toString());
        for (DiscoverHitHighlightingField highlightingField : discoveryQuery.getHitHighlightingFields()) {
            solrQuery.addHighlightField(highlightingField.getField() + "_hl");
            solrQuery.add("f." + highlightingField.getField() + "_hl." + HighlightParams.FRAGSIZE,
                    String.valueOf(highlightingField.getMaxChars()));
            solrQuery.add("f." + highlightingField.getField() + "_hl." + HighlightParams.SNIPPETS,
                    String.valueOf(highlightingField.getMaxSnippets()));
        }

    }

    //Add any configured search plugins !
    List<SolrServiceSearchPlugin> solrServiceSearchPlugins = new DSpace().getServiceManager()
            .getServicesByType(SolrServiceSearchPlugin.class);
    for (SolrServiceSearchPlugin searchPlugin : solrServiceSearchPlugins) {
        searchPlugin.additionalSearchParameters(context, discoveryQuery, solrQuery);
    }
    return solrQuery;
}

From source file:org.phenotips.termrequester.db.solr.SolrDatabaseService.java

License:Open Source License

@Override
public List<Phenotype> searchPhenotypes(String text) throws IOException {
    checkUp();/*  ww  w .  j a va2s . c  o m*/
    try {
        SolrQuery q = new SolrQuery();
        String escaped = ClientUtils.escapeQueryChars(text);
        q.add(CommonParams.Q, escaped);
        q.add(SpellingParams.SPELLCHECK_Q, text);
        q.add(DisMaxParams.PF,
                String.format("%s^20 %s^36 %s^100 %s^30 %s^15 %s^25 %s^70 %s^20 %s^3 %s^5", Schema.NAME,
                        Schema.NAME_SPELL, Schema.NAME_EXACT, Schema.NAME_PREFIX, Schema.SYNONYM,
                        Schema.SYNONYM_SPELL, Schema.SYNONYM_EXACT, Schema.SYNONYM_PREFIX, Schema.TEXT,
                        Schema.TEXT_SPELL));
        String qstring = String.format("%s^10 %s^18 %s^5 %s^6 %s^10 %s^3 %s^1 %s^2 %s^0.5", Schema.NAME,
                Schema.NAME_SPELL, Schema.NAME_STUB, Schema.SYNONYM, Schema.SYNONYM_SPELL, Schema.SYNONYM_STUB,
                Schema.TEXT, Schema.TEXT, Schema.TEXT_SPELL, Schema.TEXT_STUB);
        qstring = addStatusFilter(qstring, Phenotype.Status.SYNONYM);
        q.add(DisMaxParams.QF, qstring);
        q.add("spellcheck", Boolean.toString(true));
        q.add(SpellingParams.SPELLCHECK_COLLATE, Boolean.toString(true));
        q.add(SpellingParams.SPELLCHECK_COUNT, "100");
        q.add(SpellingParams.SPELLCHECK_MAX_COLLATION_TRIES, "3");
        q.add("lowercaseOperators", Boolean.toString(false));
        q.add("defType", "edismax");
        QueryResponse resp = server.query(q);
        List<SolrDocument> results = resp.getResults();
        List<Phenotype> retval = new ArrayList<>(results.size());
        for (SolrDocument doc : results) {
            retval.add(mapper.fromDoc(doc));
        }
        return retval;
    } catch (SolrServerException e) {
        throw new IOException(e);
    }
}

From source file:org.phenotips.vocabulary.internal.solr.HumanPhenotypeOntology.java

License:Open Source License

private SolrParams produceDynamicSolrParams(String originalQuery, Integer rows, String sort, String customFq,
        boolean isId) {
    String query = originalQuery.trim();
    ModifiableSolrParams params = new ModifiableSolrParams();
    String escapedQuery = ClientUtils.escapeQueryChars(query);
    if (isId) {//from ww w.  j av a  2s  .  c om
        params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFq,
                new MessageFormat("id:{0} alt_id:{0}").format(new String[] { escapedQuery })));
    } else {
        params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFq, "term_category:HP\\:0000118"));
    }
    params.add(CommonParams.Q, escapedQuery);
    params.add(SpellingParams.SPELLCHECK_Q, query);
    params.add(CommonParams.ROWS, rows.toString());
    if (StringUtils.isNotBlank(sort)) {
        params.add(CommonParams.SORT, sort);
    }
    return params;
}

From source file:org.phenotips.vocabulary.internal.solr.MendelianInheritanceInMan.java

License:Open Source License

private SolrParams produceDynamicSolrParams(String originalQuery, Integer rows, String sort, String customFq) {
    String query = originalQuery.trim();
    ModifiableSolrParams params = new ModifiableSolrParams();
    String escapedQuery = ClientUtils.escapeQueryChars(query);
    params.add(CommonParams.FQ,/*from   w  w w.ja v  a2  s  . c o  m*/
            StringUtils.defaultIfBlank(customFq, "-(nameSort:\\** nameSort:\\+* nameSort:\\^*)"));
    params.add(CommonParams.Q, escapedQuery);
    params.add(SpellingParams.SPELLCHECK_Q, query);
    String lastWord = StringUtils.substringAfterLast(escapedQuery, " ");
    if (StringUtils.isBlank(lastWord)) {
        lastWord = escapedQuery;
    }
    lastWord += "*";
    params.add(DisMaxParams.BQ,
            String.format("nameSpell:%1$s^20 keywords:%1$s^2 text:%1$s^1 textSpell:%1$s^2", lastWord));
    params.add(CommonParams.ROWS, rows.toString());
    if (StringUtils.isNotBlank(sort)) {
        params.add(CommonParams.SORT, sort);
    }
    return params;
}

From source file:org.phenotips.vocabulary.internal.solr.OncoTree.java

License:Open Source License

/**
 * Adds dynamic solr query parameters to {@code query}, based on the received {@code rawQuery raw query string},
 * {@code rows the maximum number of results to return}, {@code sort the sorting order}, and {@code customFilter a
 * custom filter}./*from w w w.  ja  va 2  s.  c  o  m*/
 *
 * @param rawQuery unprocessed query string
 * @param rows the maximum number of search items to return
 * @param sort the optional sort parameter
 * @param customFilter custom filter for the results
 * @param query a {@link SolrQuery solr query} object
 * @return the updated {@link SolrQuery solr query} object
 */
@Nonnull
private SolrQuery addDynamicQueryParam(@Nonnull final String rawQuery, @Nonnull final Integer rows,
        @Nullable final String sort, @Nullable final String customFilter, @Nonnull SolrQuery query) {
    final String queryString = rawQuery.trim();
    final String escapedQuery = ClientUtils.escapeQueryChars(queryString);
    if (StringUtils.isNotBlank(customFilter)) {
        query.setFilterQueries(customFilter);
    }
    query.setQuery(escapedQuery);
    query.set(SpellingParams.SPELLCHECK_Q, queryString);
    final String lastWord = StringUtils.defaultIfBlank(
            StringUtils.substringAfterLast(escapedQuery, StringUtils.SPACE), escapedQuery) + "*";
    query.set(DisMaxParams.BQ, String.format("nameSpell:%1$s^20 text:%1$s^1 textSpell:%1$s^2", lastWord));
    query.setRows(rows);
    if (StringUtils.isNotBlank(sort)) {
        for (final String sortItem : sort.split("\\s*,\\s*")) {
            query.addSort(StringUtils.substringBefore(sortItem, StringUtils.SPACE),
                    sortItem.endsWith(" desc") || sortItem.startsWith("-") ? SolrQuery.ORDER.desc
                            : SolrQuery.ORDER.asc);
        }
    }
    return query;
}

From source file:org.phenotips.vocabulary.internal.solr.OrphanetRareDiseaseOntology.java

License:Open Source License

/**
 * Adds dynamic solr query parameters to {@code query}, based on the received {@code rawQuery raw query string},
 * {@code rows the maximum number of results to return}, {@code sort the sorting order}, and {@code customFilter a
 * custom filter}./*w  w  w  .j av a2s  .c o  m*/
 *
 * @param rawQuery unprocessed query string
 * @param rows the maximum number of search items to return
 * @param sort the optional sort parameter
 * @param customFilter custom filter for the results
 * @param query a {@link SolrQuery solr query} object
 * @return the updated {@link SolrQuery solr query} object
 */
private SolrQuery addDynamicQueryParam(@Nonnull final String rawQuery, final Integer rows,
        @Nullable final String sort, @Nullable final String customFilter, @Nonnull SolrQuery query) {
    final String queryString = rawQuery.trim();
    final String escapedQuery = ClientUtils.escapeQueryChars(queryString);
    if (StringUtils.isNotBlank(customFilter)) {
        query.setFilterQueries(customFilter);
    }
    query.setQuery(escapedQuery);
    query.set(SpellingParams.SPELLCHECK_Q, queryString);
    final String lastWord = StringUtils.defaultIfBlank(StringUtils.substringAfterLast(escapedQuery, " "),
            escapedQuery) + "*";
    query.set(DisMaxParams.BQ,
            String.format("nameSpell:%1$s^20 defSpell:%1$s^3 text:%1$s^1 textSpell:%1$s^2", lastWord));
    query.setRows(rows);
    if (StringUtils.isNotBlank(sort)) {
        for (final String sortItem : sort.split("\\s*,\\s*")) {
            query.addSort(StringUtils.substringBefore(sortItem, " "),
                    sortItem.endsWith(" desc") || sortItem.startsWith("-") ? ORDER.desc : ORDER.asc);
        }
    }
    return query;
}

From source file:org.phenotips.vocabulary.internal.solr.SolrQueryUtils.java

License:Open Source License

/**
 * Replaces the original query in the Solr parameters with the suggested spellchecked query. It also fixes the boost
 * query, if any./*from  ww  w  . jav  a2s  .c o m*/
 *
 * @param originalParams the original Solr parameters to fix
 * @param suggestedQuery the suggested query
 * @return new Solr parameters with the query and boost query fixed
 */
public static SolrParams applySpellcheckSuggestion(SolrParams originalParams, String suggestedQuery) {
    if (originalParams == null) {
        return null;
    }
    if (StringUtils.isBlank(suggestedQuery)) {
        return originalParams;
    }
    ModifiableSolrParams newParams = new ModifiableSolrParams(originalParams);
    String newQuery = suggestedQuery;

    // Since the spelling suggestion might not be that good, also search for the original user input
    if (StringUtils.isNotEmpty(originalParams.get(SpellingParams.SPELLCHECK_Q))) {
        newQuery = originalParams.get(CommonParams.Q) + "^10 " + suggestedQuery;
    }

    // Check if the last term in the query is a word stub search which, in case the request comes from a
    // user-triggered search for terms from the UI, is a prefix search for the last typed word
    Matcher originalStub = WORD_STUB.matcher(newParams.get(CommonParams.Q));
    Matcher newStub = WORD_STUB.matcher(suggestedQuery);
    if (originalStub.find() && newStub.find() && !StringUtils.equals(originalStub.group(2), newStub.group(2))) {
        // Since word stubs aren't complete words, they may wrongly be "corrected" to a full word that doesn't match
        // what the user started typing; include both the original stub and the "corrected" stub in the query
        newQuery += ' ' + originalStub.group() + "^1.5";
        // Also fix the boost query
        String boostQuery = newParams.get(DisMaxParams.BQ);
        if (StringUtils.isNotEmpty(boostQuery)) {
            newParams.add(DisMaxParams.BQ, boostQuery.replace(originalStub.group(2), newStub.group(2)));
        }
    }
    // Replace the query
    newParams.set(CommonParams.Q, newQuery);

    return newParams;
}