Example usage for org.apache.solr.client.solrj.response SpellCheckResponse getCollatedResult

List of usage examples for org.apache.solr.client.solrj.response SpellCheckResponse getCollatedResult

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj.response SpellCheckResponse getCollatedResult.

Prototype

public String getCollatedResult() 

Source Link

Document

Return the first collated query string.

Usage

From source file:com.gisgraphy.domain.valueobject.FulltextResultsDto.java

License:Open Source License

/**
 * @param response//from   w  w  w .j  av  a2s .  c om
 *            The {@link QueryResponse} to build the DTO
 */
public FulltextResultsDto(QueryResponse response) {
    super();
    this.results = SolrUnmarshaller.unmarshall(response);
    this.QTime = response.getQTime();
    this.numFound = response.getResults().getNumFound();
    this.maxScore = response.getResults().getMaxScore();
    this.resultsSize = results == null ? 0 : results.size();
    SpellCheckResponse spellCheckResponse = response.getSpellCheckResponse();
    if (spellCheckResponse != null) {
        Map<String, Suggestion> suggestionMapInternal = spellCheckResponse.getSuggestionMap();
        if (suggestionMapInternal != null) {
            suggestionMap = spellCheckResponse.getSuggestionMap();
        }
        if (spellCheckResponse.getCollatedResult() != null) {
            collatedResult = spellCheckResponse.getCollatedResult().trim();
        }
        List<Suggestion> suggestions = spellCheckResponse.getSuggestions();
        if (suggestions.size() != 0) {
            StringBuffer sb = new StringBuffer();
            for (Suggestion suggestion : suggestions) {
                sb.append(suggestion.getSuggestions().get(0)).append(" ");
            }
            spellCheckProposal = sb.toString().trim();
        }
    }

}

From source file:com.nridge.ds.solr.SolrResponseBuilder.java

License:Open Source License

private void populateSpelling(QueryResponse aQueryResponse) {
    Logger appLogger = mAppMgr.getLogger(this, "populateSpelling");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    SpellCheckResponse spellCheckResponse = aQueryResponse.getSpellCheckResponse();
    if (spellCheckResponse != null) {
        mDocument.addRelationship(Solr.RESPONSE_SPELLING, createSpellCheckBag());
        Relationship spellingRelationship = mDocument.getFirstRelationship(Solr.RESPONSE_SPELLING);
        if (spellingRelationship != null) {
            DataBag spellingBag = spellingRelationship.getBag();
            spellingBag.setValueByName("suggestion", spellCheckResponse.getCollatedResult());
            spellingBag.setValueByName("is_spelled_correctly", spellCheckResponse.isCorrectlySpelled());
        }/*  www  .j  a va 2  s  .  com*/
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:org.hippoecm.hst.demo.components.SolrRight.java

License:Apache License

@Override
public void doBeforeServeResource(final HstRequest request, final HstResponse response)
        throws HstComponentException {
    if (request.getParameter("suggestquery") == null) {
        // no query
        return;/*from w w w. ja va 2 s  .  c om*/
    }

    HippoSolrClient solrClient = HstServices.getComponentManager().getComponent(HippoSolrClient.class.getName(),
            SOLR_MODULE_NAME);
    String suggest = request.getParameter("suggestquery");
    try {

        HippoQuery hippoQuery = solrClient.createQuery(suggest);

        // we want to get suggestions/autocompletion/didyoumean only!
        hippoQuery.getSolrQuery().setRequestHandler("suggest");
        HippoQueryResult result = hippoQuery.execute();

        // we do not need to bind the beans with their providers for faceting, so no need for
        // result.bindHits()

        // because suggestions reuse the spell check component, we can use the spell check response
        final SpellCheckResponse spellCheckResponse = result.getQueryResponse().getSpellCheckResponse();
        if (spellCheckResponse != null) {
            request.setAttribute("collated", spellCheckResponse.getCollatedResult());
            request.setAttribute("suggestions", spellCheckResponse.getSuggestions());
        }

    } catch (SolrServerException e) {
        throw new HstComponentException(e);
    }

}

From source file:org.opencommercesearch.AbstractSearchServer.java

License:Apache License

private SearchResponse doSearch(SolrQuery query, Site site, RepositoryItem catalog, Locale locale,
        boolean isSearch, boolean isRuleBasedPage, String categoryPath, boolean isOutletPage, String brandId,
        FilterQuery... filterQueries) throws SearchServerException {
    if (site == null) {
        throw new IllegalArgumentException("Missing site");
    }/* w  ww .ja v a 2s  .com*/
    if (catalog == null) {
        throw new IllegalArgumentException("Missing catalog");
    }
    long startTime = System.currentTimeMillis();

    query.addFacetField("category");
    query.set("facet.mincount", 1);

    RuleManager ruleManager = new RuleManager(getSearchRepository(), getRulesBuilder(),
            getRulesSolrServer(locale));
    if ((query.getRows() != null && query.getRows() > 0)
            || (query.get("group") != null && query.getBool("group"))) {
        setGroupParams(query, locale);
        setFieldListParams(query, locale.getCountry(), catalog.getRepositoryId());
        try {
            ruleManager.setRuleParams(query, isSearch, isRuleBasedPage, categoryPath, filterQueries, catalog,
                    isOutletPage, brandId);

            if (ruleManager.getRules().containsKey(SearchRepositoryItemDescriptor.REDIRECT_RULE)) {
                Map<String, List<RepositoryItem>> rules = ruleManager.getRules();
                List<RepositoryItem> redirects = rules.get(SearchRepositoryItemDescriptor.REDIRECT_RULE);
                if (redirects != null) {
                    RepositoryItem redirect = redirects.get(0);
                    return new SearchResponse(query, null, null, null,
                            (String) redirect.getPropertyValue(RedirectRuleProperty.URL), null, true);
                }
            }

        } catch (RepositoryException ex) {
            if (isLoggingError()) {
                logError("Unable to load search rules: " + ex.getMessage());
            }
            throw create(SEARCH_EXCEPTION, ex);
        } catch (SolrServerException ex) {
            if (isLoggingError()) {
                logError("Unable to load search rules: " + ex.getMessage());
            }
            throw create(SEARCH_EXCEPTION, ex);
        } catch (SolrException ex) {
            if (isLoggingError()) {
                logError("Unable to load search rules: " + ex.getMessage());
            }
            throw create(SEARCH_EXCEPTION, ex);
        }
    } else {
        ruleManager.setFilterQueries(filterQueries, catalog.getRepositoryId(), query);
    }

    try {
        QueryResponse queryResponse = getCatalogSolrServer(locale).query(query);

        String correctedTerm = null;
        boolean matchesAll = true;

        //if no results, check for spelling errors
        if (query.getRows() > 0 && isEmptySearch(queryResponse.getGroupResponse())
                && StringUtils.isNotEmpty(query.getQuery())) {

            SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
            //try to do searching for the corrected term matching all terms (q.op=AND)
            QueryResponse tentativeResponse = handleSpellCheck(spellCheckResponse, getCatalogSolrServer(locale),
                    query, "AND");
            if (tentativeResponse != null) {
                //if we got results, set the corrected term variable and proceed to return the results
                queryResponse = tentativeResponse;
                correctedTerm = spellCheckResponse.getCollatedResult();
            } else {
                //if we didn't got any response, try doing another search matching any term (q.op=OR)
                tentativeResponse = handleSpellCheck(spellCheckResponse, getCatalogSolrServer(locale), query,
                        "OR");
                if (tentativeResponse != null) {
                    //if we got results for the match any term scenario. Set similar results to true
                    //and set the corrected term.
                    queryResponse = tentativeResponse;
                    matchesAll = false;
                    correctedTerm = query.getQuery();
                }
            }

        }

        long searchTime = System.currentTimeMillis() - startTime;
        if (isLoggingDebug()) {
            logDebug("Search time is " + searchTime + ", search engine time is " + queryResponse.getQTime());
        }

        SearchResponse searchResponse = new SearchResponse(query, queryResponse, ruleManager, filterQueries,
                null, correctedTerm, matchesAll);
        searchResponse.setRuleQueryTime(ruleManager.getLoadRulesTime());
        return searchResponse;
    } catch (SolrServerException ex) {
        throw create(SEARCH_EXCEPTION, ex);
    } catch (SolrException ex) {
        throw create(SEARCH_EXCEPTION, ex);
    }

}

From source file:org.opencommercesearch.AbstractSearchServer.java

License:Apache License

private QueryResponse handleSpellCheck(SpellCheckResponse spellCheckResponse, T catalogSolrServer,
        SolrQuery query, String queryOp) throws SolrServerException {

    QueryResponse queryResponse;//www  .j  a v a  2s .  com

    if (spellCheckResponse != null && StringUtils.isNotBlank(spellCheckResponse.getCollatedResult())) {
        //check if we have any spelling suggestion
        String tentativeCorrectedTerm = spellCheckResponse.getCollatedResult();

        //if we have spelling suggestions, try doing another search using 
        //q.op as the specified queryOp param (the default one is AND so we only add it if it's OR)
        //and use q="corrected phrase" to see if we can get results
        if ("OR".equals(queryOp)) {
            query.setParam("q.op", "OR");
            query.setParam("mm", getMinimumMatch());
        }
        query.setQuery(tentativeCorrectedTerm);
        queryResponse = catalogSolrServer.query(query);

        //if we didn't got any results from the search with q="corrected phrase" return null
        //otherwise return the results
        return isEmptySearch(queryResponse.getGroupResponse()) ? null : queryResponse;

    } else if ("OR".equals(queryOp)) {
        //for the match any terms scenario with no corrected terms do another query
        query.setParam("q.op", "OR");
        query.setParam("mm", getMinimumMatch());
        queryResponse = catalogSolrServer.query(query);
        return isEmptySearch(queryResponse.getGroupResponse()) ? null : queryResponse;
    } else {
        //if we didn't got any corrected terms and are not in the match any term scenario, 
        //then return null
        return null;
    }
}

From source file:org.zaizi.sensefy.api.service.SearchService.java

License:Open Source License

public SearchResponse getSearchResponse(String query, String fields, String filters, int start, Integer rows,
        String order, boolean facet, boolean spellcheck, boolean clustering, String clusterSort,
        boolean security, Principal user) {
    SearchResponse response = new SearchResponse();

    response.setQuery(query);//from  w  w  w. j a  v  a 2s  .c  o  m
    SearchResults responseContent = new SearchResults();
    responseContent.setStart(start);
    Long startTime = System.currentTimeMillis();
    try {
        FacetConfigurationList facetConfiguration = null;
        if (facet)
            facetConfiguration = facetConfigurers.getFacetConfiguration();
        SolrQuery documentsQuery = QueryBuilder.getSolrQuery(query, fields, facet, facetConfiguration, filters,
                start, rows, order, security, spellcheck, clustering, user);

        QueryResponse primaryIndexResponse;
        primaryIndexResponse = this.getPrimaryIndex().query(documentsQuery);
        Map<String, Map<String, List<String>>> highlightingSnippets = primaryIndexResponse.getHighlighting();
        SpellCheckResponse spellCheckResponse = primaryIndexResponse.getSpellCheckResponse();
        String collationQuery;
        if (spellCheckResponse != null) {
            collationQuery = spellCheckResponse.getCollatedResult();
            responseContent.setCollationQuery(collationQuery);
        }
        SolrDocumentList primaryIndexResults = primaryIndexResponse.getResults();
        responseContent.setNumFound(primaryIndexResults.getNumFound());
        responseContent.setDocuments(primaryIndexResults);
        responseContent.setHighlight(highlightingSnippets);
        response.setSearchResults(responseContent);
        if (clustering) {
            if (clusterSort != null && clusterSort.equals("size"))
                ClusterParser.parseClusters(primaryIndexResponse, response, true);
            else
                ClusterParser.parseClusters(primaryIndexResponse, response, false);
        }
        if (facet)
            FacetParser.parseFacets(primaryIndexResponse, response, facetConfiguration);
    } catch (SolrServerException e) {
        processAPIException(response, e, "[Keyword Based Search] Error - stacktrace follows", 500,
                ComponentCode.SOLR);
    }
    Long elapsedTime = System.currentTimeMillis() - startTime;
    response.setTime(elapsedTime);

    return response;
}