Example usage for org.apache.solr.client.solrj.response QueryResponse getSpellCheckResponse

List of usage examples for org.apache.solr.client.solrj.response QueryResponse getSpellCheckResponse

Introduction

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

Prototype

public SpellCheckResponse getSpellCheckResponse() 

Source Link

Usage

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

License:Open Source License

/**
 * @param response//from   ww  w  . java 2s. 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());
        }//from w  ww.j  av a 2s.  c  o m
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.yaotrue.learn.solr.SolrjTest.java

License:Apache License

@Test
public void testSuggest() throws SolrServerException, IOException {
    SolrQuery params = new SolrQuery();
    params.set("qt", "/suggest");
    params.set("suggest", true);
    params.set("suggest.dictionary", "mySuggester");
    params.set("suggest.q", "?");
    QueryResponse query = solrClient.query(params);
    NamedList<Object> response = query.getResponse();
    //      response.get("suggest")
    SpellCheckResponse spellCheckResponse = query.getSpellCheckResponse();
    List<Suggestion> suggestions = spellCheckResponse.getSuggestions();
    for (Suggestion suggestion : suggestions) {//JAVA
        List<String> suggestions2 = suggestion.getAlternatives();
        for (String string : suggestions2) {
            System.out.println(string);
        }/*from   w  ww  .j  a  va 2s .c  om*/
    }
    SolrDocumentList results = query.getResults();
    for (int i = 0; i < results.getNumFound(); i++) {
        System.out.println(results.get(i).get("suggestion"));
    }
}

From source file:edu.toronto.cs.cidb.solr.SolrScriptService.java

License:Open Source License

/**
 * Perform a search, falling back on the suggested spellchecked query if the original query fails to return any
 * results./*from ww w  . ja  v a2  s.co m*/
 * 
 * @param params the Solr parameters to use, should contain at least a value for the "q" parameter; use
 *        {@link #getSolrQuery(String, int, int)} to get the proper parameter expected by this method
 * @return the list of matching documents, empty if there are no matching terms
 */
private SolrDocumentList search(MapSolrParams params) {
    try {
        QueryResponse response = this.server.query(params);
        SolrDocumentList results = response.getResults();
        if (results.size() == 0 && !response.getSpellCheckResponse().isCorrectlySpelled()) {
            String suggestedQuery = response.getSpellCheckResponse().getCollatedResult();
            // The spellcheck doesn't preserve the identifiers, manually
            // correct this
            suggestedQuery = suggestedQuery.replaceAll("term_category:hip", "term_category:HP");
            MapSolrParams newParams = new MapSolrParams(
                    getSolrQuery(suggestedQuery, params.get(CommonParams.SORT),
                            params.getInt(CommonParams.ROWS, -1), params.getInt(CommonParams.START, 0)));
            return this.server.query(newParams).getResults();
        } else {
            return results;
        }
    } catch (SolrServerException ex) {
        this.logger.error("Failed to search: {}", ex.getMessage(), ex);
    }
    return null;
}

From source file:edu.toronto.cs.phenotips.solr.AbstractSolrScriptService.java

License:Open Source License

/**
 * Perform a search, falling back on the suggested spellchecked query if the original query fails to return any
 * results.// w  ww  .j a v  a  2  s .  c  o  m
 * 
 * @param params the Solr parameters to use, should contain at least a value for the "q" parameter; use
 *            {@link #getSolrQuery(String, int, int)} to get the proper parameter expected by this method
 * @return the list of matching documents, empty if there are no matching terms
 */
private SolrDocumentList search(MapSolrParams params) {
    try {
        NamedList<Object> newParams = params.toNamedList();
        if (newParams.get(CommonParams.FL) == null) {
            newParams.add(CommonParams.FL, "* score");
        }
        QueryResponse response = this.server.query(MapSolrParams.toSolrParams(newParams));
        SolrDocumentList results = response.getResults();
        if (response.getSpellCheckResponse() != null
                && !response.getSpellCheckResponse().isCorrectlySpelled()) {
            String suggestedQuery = response.getSpellCheckResponse().getCollatedResult();
            if (StringUtils.isEmpty(suggestedQuery)) {
                return results;
            }
            Pattern p = Pattern.compile("(\\w++):(\\w++)\\*$", Pattern.CASE_INSENSITIVE);
            Matcher originalStub = p.matcher((String) newParams.get(CommonParams.Q));
            newParams.remove(CommonParams.Q);
            Matcher newStub = p.matcher(suggestedQuery);
            if (originalStub.find() && newStub.find()) {
                suggestedQuery += ' ' + originalStub.group() + "^1.5 " + originalStub.group(2) + "^1.5";
                String boostQuery = (String) newParams.get(DisMaxParams.BQ);
                if (boostQuery != null) {
                    boostQuery += ' ' + boostQuery.replace(originalStub.group(2), newStub.group(2));
                    newParams.remove(DisMaxParams.BQ);
                    newParams.add(DisMaxParams.BQ, boostQuery);
                }
            }
            newParams.add(CommonParams.Q, suggestedQuery);
            SolrDocumentList spellcheckResults = this.server.query(MapSolrParams.toSolrParams(newParams))
                    .getResults();
            if (results.getMaxScore() < spellcheckResults.getMaxScore()) {
                results = spellcheckResults;
            }
        }
        return results;
    } catch (SolrServerException ex) {
        this.logger.error("Failed to search: {}", ex.getMessage(), ex);
    }
    return null;
}

From source file:edu.ub.ir.oof1.service.Solr.java

private List<String> spellcheck(QueryResponse resp) {
    List<String> out = null;
    try {/*from  w  ww.  j a v  a  2 s  .c o  m*/
        SpellCheckResponse spellResp = resp.getSpellCheckResponse();

        if (!spellResp.isCorrectlySpelled()) {
            for (Suggestion suggest : resp.getSpellCheckResponse().getSuggestions()) {
                System.out.println(suggest.getAlternatives());
                out = suggest.getAlternatives();
                if (out != null) {
                    break;
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return out;
}

From source file:eu.prestoprime.search.Searcher.java

License:Open Source License

/**
 * Queries Solr for auto-complete suggestions for an entered term. See
 * SearchHandler "suggest" in solrConfig.xml for tweaking.
 * //from www.j  a va  2s  . com
 * @param term
 * @return
 */
public P4Suggestions getSuggestion(String term) {
    P4Suggestions suggs = new P4Suggestions(term);
    QueryResponse response = new QueryResponse();
    SolrQuery query = new SolrQuery(term);
    query.setQueryType("/suggest");

    try {
        response = SolrServerConnection.getInstance().getSolrServer().query(query);
        if (response.getSpellCheckResponse() != null
                && !response.getSpellCheckResponse().getSuggestionMap().entrySet().isEmpty()) {
            Map<String, Suggestion> resultMap = response.getSpellCheckResponse().getSuggestionMap();
            for (Entry<String, Suggestion> entry : resultMap.entrySet()) {
                suggs.suggestions.add(new P4Suggestion(entry.getKey(), entry.getValue().getAlternatives()));
            }
        }
    } catch (SolrServerException e) {
        LOGGER.fatal(e);
        LOGGER.fatal("Could not query Solr for suggestions. Query = '" + query.getQuery() + "'.");
    }
    return suggs;
}

From source file:fr.paris.lutece.plugins.search.solr.business.SolrSearchEngine.java

License:Open Source License

/**
 * Return the result with facets. Does NOT support authentification yet.
 * @param strQuery the query/*from w  w w  .  j  a va2 s. c o  m*/
 * @param facetQueries The selected facets
 * @param sortName The facet name to sort by
 * @param sortOrder "asc" or "desc"
 * @param nLimit Maximal number of results.
 * @return the result with facets
 */
public SolrFacetedResult getFacetedSearchResults(String strQuery, String[] facetQueries, String sortName,
        String sortOrder, int nLimit, int nCurrentPageIndex, int nItemsPerPage, Boolean bSpellCheck) {
    SolrFacetedResult facetedResult = new SolrFacetedResult();

    SolrClient solrServer = SolrServerService.getInstance().getSolrServer();
    List<SolrSearchResult> results = new ArrayList<SolrSearchResult>();
    Hashtable<Field, List<String>> myValuesList = new Hashtable<Field, List<String>>();

    if (solrServer != null) {
        SolrQuery query = new SolrQuery(strQuery);
        query.setHighlight(true);
        query.setHighlightSimplePre(SOLR_HIGHLIGHT_PRE);
        query.setHighlightSimplePost(SOLR_HIGHLIGHT_POST);
        query.setHighlightSnippets(SOLR_HIGHLIGHT_SNIPPETS);
        query.setHighlightFragsize(SOLR_HIGHLIGHT_FRAGSIZE);
        query.setFacet(true);
        query.setFacetLimit(SOLR_FACET_LIMIT);
        //            query.setFacetMinCount( 1 );

        for (Field field : SolrFieldManager.getFacetList().values()) {
            //Add facet Field
            if (field.getEnableFacet()) {
                if (field.getName().equalsIgnoreCase("date")
                        || field.getName().toLowerCase().endsWith("_date")) {
                    query.setParam("facet.date", field.getName());
                    query.setParam("facet.date.start", SOLR_FACET_DATE_START);
                    query.setParam("facet.date.gap", SOLR_FACET_DATE_GAP);
                    query.setParam("facet.date.end", SOLR_FACET_DATE_END);
                    query.setParam("facet.date.mincount", "0");
                } else {
                    query.addFacetField(field.getSolrName());
                    query.setParam("f." + field.getSolrName() + ".facet.mincount",
                            String.valueOf(field.getFacetMincount()));
                }
                myValuesList.put(field, new ArrayList<String>());
            }
        }

        //Facet intersection
        List<String> treeParam = new ArrayList<String>();

        for (FacetIntersection intersect : SolrFieldManager.getIntersectionlist()) {
            treeParam.add(intersect.getField1().getSolrName() + "," + intersect.getField2().getSolrName());
        }

        //(String []) al.toArray (new String [0]);
        query.setParam("facet.tree", (String[]) treeParam.toArray(new String[0]));
        query.setParam("spellcheck", bSpellCheck);

        //sort order
        if ((sortName != null) && !"".equals(sortName)) {
            if (sortOrder.equals("asc")) {
                query.setSort(sortName, ORDER.asc);
            } else {
                query.setSort(sortName, ORDER.desc);
            }
        } else {
            for (Field field : SolrFieldManager.getSortList()) {
                if (field.getDefaultSort()) {
                    query.setSort(field.getName(), ORDER.desc);
                }
            }
        }

        //Treat HttpRequest
        //FacetQuery
        if (facetQueries != null) {
            for (String strFacetQuery : facetQueries) {
                //                    if ( strFacetQuery.contains( DATE_COLON ) )
                //                    {
                //                        query.addFilterQuery( strFacetQuery );
                //                    }
                //                    else
                //                    {
                String myValues[] = strFacetQuery.split(":", 2);
                if (myValues != null && myValues.length == 2) {
                    myValuesList = getFieldArrange(myValues, myValuesList);
                }
                //strFacetQueryWithColon = strFacetQuery.replaceFirst( SolrConstants.CONSTANT_COLON, COLON_QUOTE );
                //strFacetQueryWithColon += SolrConstants.CONSTANT_QUOTE;
                //                        query.addFilterQuery( strFacetQuery );
                //                    }
            }

            for (Field tmpFieldValue : myValuesList.keySet()) {
                List<String> strValues = myValuesList.get(tmpFieldValue);
                String strFacetString = "";
                if (strValues.size() > 0) {
                    strFacetString = extractQuery(strValues, tmpFieldValue.getOperator());
                    if (tmpFieldValue.getName().equalsIgnoreCase("date")
                            || tmpFieldValue.getName().toLowerCase().endsWith("_date")) {
                        strFacetString = strFacetString.replaceAll("\"", "");
                    }
                    query.addFilterQuery(tmpFieldValue.getName() + ":" + strFacetString);
                }
            }
        }

        try {

            // count query
            query.setRows(0);
            QueryResponse response = solrServer.query(query);

            int nResults = (int) response.getResults().getNumFound();
            facetedResult.setCount(nResults > nLimit ? nLimit : nResults);

            query.setStart((nCurrentPageIndex - 1) * nItemsPerPage);
            query.setRows(nItemsPerPage > nLimit ? nLimit : nItemsPerPage);

            query.setParam("defType", DEF_TYPE);
            String strWeightValue = generateQueryWeightValue();
            query.setParam("qf", strWeightValue);

            response = solrServer.query(query);

            //HighLight
            Map<String, Map<String, List<String>>> highlightsMap = response.getHighlighting();
            SolrHighlights highlights = null;

            if (highlightsMap != null) {
                highlights = new SolrHighlights(highlightsMap);
            }

            //resultList
            List<SolrItem> itemList = response.getBeans(SolrItem.class);
            results = SolrUtil.transformSolrItemsToSolrSearchResults(itemList, highlights);

            //set the spellcheckresult
            facetedResult.setSolrSpellCheckResponse(response.getSpellCheckResponse());

            //Date facet
            if ((response.getFacetDates() != null) && !response.getFacetDates().isEmpty()) {
                facetedResult.setFacetDateList(response.getFacetDates());
            }

            //FacetField
            facetedResult.setFacetFields(response.getFacetFields());

            //Facet intersection (facet tree)
            NamedList<Object> resp = (NamedList<Object>) response.getResponse().get("facet_counts");

            if (resp != null) {
                NamedList<NamedList<NamedList<Integer>>> trees = (NamedList<NamedList<NamedList<Integer>>>) resp
                        .get("trees");
                Map<String, ArrayList<FacetField>> treesResult = new HashMap<String, ArrayList<FacetField>>();

                if (trees != null) {
                    for (Entry<String, NamedList<NamedList<Integer>>> selectedFacet : trees) { //Selected Facet (ex : type,categorie )
                                                                                               //System.out.println(selectedFacet.getKey());

                        ArrayList<FacetField> facetFields = new ArrayList<FacetField>(
                                selectedFacet.getValue().size());

                        for (Entry<String, NamedList<Integer>> facetField : selectedFacet.getValue()) {
                            FacetField ff = new FacetField(facetField.getKey());

                            //System.out.println("\t" + facetField.getKey());
                            for (Entry<String, Integer> value : facetField.getValue()) { // Second Level
                                ff.add(value.getKey(), value.getValue());

                                //System.out.println("\t\t" + value.getKey() + " : " + value.getValue());
                            }

                            facetFields.add(ff);
                        }

                        treesResult.put(selectedFacet.getKey(), facetFields);
                    }
                }

                facetedResult.setFacetIntersection(treesResult);
            }
        } catch (SolrServerException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (IOException e) {
            AppLogService.error(e.getMessage(), e);
        }
    } else {
        facetedResult.setFacetFields(new ArrayList<FacetField>());
    }

    facetedResult.setSolrSearchResults(results);

    return facetedResult;
}

From source file:fr.paris.lutece.plugins.search.solr.business.SolrSearchEngine.java

License:Open Source License

/**
 * Return the suggestion terms//from   w  w  w.  ja v  a  2s.  c  o  m
 * @param term the terms of search
 * @return The spell checker response
 */
public SpellCheckResponse getSpellChecker(String term) {
    SpellCheckResponse spellCheck = null;
    SolrClient solrServer = SolrServerService.getInstance().getSolrServer();

    SolrQuery query = new SolrQuery(term);
    //Do not return results (optimization)
    query.setRows(0);
    //Activate spellChecker
    query.setParam("spellcheck", "true");
    //The request handler used
    query.setRequestHandler("/" + SOLR_SPELLCHECK_HANDLER);
    //The number of suggest returned

    query.setParam("spellcheck.count", "1"); // TODO
                                             //Returns the frequency of the terms

    query.setParam("spellcheck.extendedResults", "true"); // TODO
                                                          //Return the best suggestion combinaison with many words

    query.setParam("spellcheck.collate", "true"); // TODO

    try {
        QueryResponse response = solrServer.query(query);
        spellCheck = response.getSpellCheckResponse();
    } catch (SolrServerException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    }

    return spellCheck;
}

From source file:fr.paris.lutece.plugins.search.solr.web.SolrSuggestServlet.java

License:Open Source License

/**
 * Displays the indexing parameters/*from  ww  w .  j a v  a2  s. com*/
 *
 * @param request the http request
 * @return the html code which displays the parameters page
 */
public String getSuggest(HttpServletRequest request) {
    String callback = request.getParameter("callback");
    String terms = request.getParameter("q");

    SolrSearchEngine engine = SolrSearchEngine.getInstance();
    StringBuffer result = new StringBuffer();
    result.append(callback);

    result.append("({\"response\":{\"docs\":[");

    QueryResponse response = engine.getJsonpSuggest(terms, callback);
    Collation solr = null;
    //String fieldName = null;
    //int i= 1;

    //Iterate on all document
    for (Iterator<Collation> ite = response.getSpellCheckResponse().getCollatedResults().iterator(); ite
            .hasNext();) {
        if (ite.hasNext()) {
            solr = ite.next();

            String collation = solr.getCollationQueryString();

            //iterate on each field
            //for ( String suggest : suggestions )
            //{
            result.append("{");
            result.append("\"").append("title").append("\":\"").append(collation).append("\"");

            if (ite.hasNext()) {
                result.append("},");
            } else {
                result.append("}");
            }
        }
        // i++;
        //}
    }

    //Close result
    result.append("]}})");

    return result.toString();
}