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:actors.SolrActor.java

License:Apache License

public void indexUpdated(SolrIndexEvent msg) {
    try {/*from www  .j a  va  2 s.  c  o m*/
        System.out.println("SolrIndexEvent");
        SolrInputDocument doc = msg.getDocuement();
        //Making realtime GET
        System.out.println("GET");
        SolrQuery parameters = new SolrQuery();
        parameters.setRequestHandler("/get");
        String f1 = doc.getFieldValue("literal.id").toString();
        String f2 = doc.getFieldValue("literal.rev").toString();
        parameters.set("id", f1);
        parameters.set("rev", f2);
        //System.out.println(parameters);

        QueryResponse response = server.query(parameters);

        NamedList<Object> result = response.getResponse();
        //System.out.println(response.getResponse());
        //System.out.println(result.size() );
        //System.out.println();
        //System.out.println(result);
        //validate the doc exists
        if (result == null || result.get("doc") == null) {
            System.out.println("/update/extract");
            ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract");
            // url dropbox
            URL url = new URL(doc.getFieldValue("literal.links").toString());
            ContentStreamBase content = new ContentStreamBase.URLStream(url);
            System.out.println("ContentStreamBase");
            req.addContentStream(content);
            // Adittionall metadata
            req.setParam("literal.id", doc.getFieldValue("literal.id").toString());
            req.setParam("literal.title", doc.getFieldValue("literal.title").toString());
            req.setParam("literal.rev", doc.getFieldValue("literal.rev").toString());
            req.setParam("literal.when", doc.getFieldValue("literal.when").toString());
            req.setParam("literal.path", doc.getFieldValue("literal.path").toString());
            req.setParam("literal.icon", doc.getFieldValue("literal.icon").toString());
            req.setParam("literal.size", doc.getFieldValue("literal.size").toString());
            req.setParam("literal.url", doc.getFieldValue("literal.links").toString());

            req.setParam("uprefix", "attr_");
            req.setParam("fmap.content", "attr_content");
            req.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
            //Requesting Solr
            result = server.request(req);
            //System.out.println("Result: " + result.toString());

        } else {
            System.out.println("It's already update");

        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

License:Open Source License

/**
 * @see au.org.ala.biocache.dao.SearchDAO#getFacetPointsShort(au.org.ala.biocache.dto.SpatialSearchRequestParams, String)
 */// w  w w . j a  va2 s.  c  o m
@Override
public FacetField getFacetPointsShort(SpatialSearchRequestParams searchParams, String pointType)
        throws Exception {
    queryFormatUtils.formatSearchQuery(searchParams);
    if (logger.isInfoEnabled()) {
        logger.info("search query: " + searchParams.getFormattedQuery());
    }
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setRequestHandler("standard");
    solrQuery.setQuery(searchParams.getFormattedQuery());
    solrQuery.setRows(0);
    solrQuery.setFacet(true);
    solrQuery.addFacetField(pointType);
    solrQuery.setFacetMinCount(1);
    solrQuery.setFacetLimit(searchParams.getFlimit());//MAX_DOWNLOAD_SIZE);  // unlimited = -1

    QueryResponse qr = runSolrQuery(solrQuery, searchParams.getFormattedFq(), 0, 0, "_docid_", "asc");
    List<FacetField> facets = qr.getFacetFields();

    //return first facet, there should only be 1
    if (facets != null && facets.size() > 0) {
        return facets.get(0);
    }
    return null;
}

From source file:com.bindez.nlp.extract.ngram.term_frequency.TermFrequency.java

public List<Word> getTermsFrequency(Set<String> words) throws SolrServerException {
    List<Word> result = new ArrayList<Word>();
    server = new SolrServer().getSolrServer();

    for (String word : words) {
        SolrQuery query = new SolrQuery();

        query.setRequestHandler("/terms");
        query.set("terms.fl", "content");
        query.set("terms.regex", word);
        query.set("terms", "true");
        query.set("shards.qt", "/terms");
        query.set("distrib", "true");

        QueryResponse response = server.query(query);
        TermsResponse termsRes = response.getTermsResponse();
        List<TermsResponse.Term> terms = termsRes.getTerms("content");
        TermsResponse.Term term = null;/*  www  .  j  a va2  s. c om*/
        Word w = new Word();
        if (terms != null && terms.size() > 0) {
            term = terms.get(0);
            w.setText(term.getTerm());
            w.setCount(term.getFrequency());
            result.add(w);
        }

    }

    return result;
}

From source file:com.doculibre.constellio.services.AutocompleteServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
static private NamedList<Object> suggest(String q, String fieldName, SolrServer server, Boolean isStringField) {
    NamedList<Object> returnList = new NamedList<Object>();

    // escape special characters
    SolrQuery query = new SolrQuery();

    /*/*from   ww w.j a  v a  2  s  . c o  m*/
     * // * Set terms.lower to the input term
     * query.setParam(TermsParams.TERMS_LOWER, q); // * Set terms.prefix to
     * the input term query.setParam(TermsParams.TERMS_PREFIX, q); // * Set
     * terms.lower.incl to false
     * query.setParam(TermsParams.TERMS_LOWER_INCLUSIVE, "false"); // * Set
     * terms.fl to the name of the source field
     * query.setParam(TermsParams.TERMS_FIELD, fieldName);
     */

    query.setParam(TermsParams.TERMS_FIELD, fieldName);// query.addTermsField("spell");
    query.setParam(TermsParams.TERMS_LIMIT, TERMS_LIMIT);// query.setTermsLimit(MAX_TERMS);
    query.setParam(TermsParams.TERMS, "true");// query.setTerms(true);
    query.setParam(TermsParams.TERMS_LOWER, q);// query.setTermsLower(q);
    query.setParam(TermsParams.TERMS_PREFIX, q);// query.setTermsPrefix(q);
    query.setParam(TermsParams.TERMS_MINCOUNT, TERMS_MINCOUNT);

    query.setRequestHandler(SolrServices.AUTOCOMPLETE_QUERY_NAME);

    try {
        QueryResponse qr = server.query(query);
        NamedList<Object> values = qr.getResponse();
        NamedList<Object> terms = (NamedList<Object>) values.get("terms");// TermsResponse
        // resp
        // =
        // qr.getTermsResponse();
        NamedList<Object> suggestions = (NamedList<Object>) terms.get(fieldName);// items
        // =
        // resp.getTerms("spell");
        if (!isStringField) {
            q = AnalyzerUtils.analyzePhrase(q, false);
        }

        for (int i = 0; i < suggestions.size(); i++) {
            String currentSuggestion = suggestions.getName(i);
            // System.out.println(currentSuggestion);
            if (isStringField) {
                if (currentSuggestion.contains(q)) {
                    // String suffix =
                    // StringUtils.substringAfter(currentSuggestion, q);
                    // if (suffix.isEmpty() &&
                    // !currentSuggestion.equals(q)){
                    // //q n est pas dans currentSuggestion
                    // break;
                    // }
                    if (currentSuggestion.contains(SPECIAL_CHAR)) {
                        // le resultat de recherche retourne des fois une
                        // partie de la valeur existant
                        // dans le champ!
                        currentSuggestion = StringUtils.substringAfter(currentSuggestion, SPECIAL_CHAR);
                    }
                    returnList.add(currentSuggestion, suggestions.getVal(i));
                }
            } else {
                currentSuggestion = AnalyzerUtils.analyzePhrase(currentSuggestion, false);
                if (currentSuggestion.contains(q)) {
                    returnList.add(currentSuggestion, suggestions.getVal(i));
                }
            }
        }

    } catch (SolrServerException e) {
        throw new RuntimeException(e);
    }
    return returnList;
}

From source file:com.doculibre.constellio.services.ClusteringServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*ww w .  j av a 2 s  .c  o  m*/
public List<SimpleOrderedMap<Object>> cluster(SimpleSearch simpleSearch, CollectionFacet facet, int start,
        int row, ConstellioUser user) {
    //      String luceneQuery = simpleSearch.getLuceneQuery();
    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    String solrServerName = simpleSearch.getCollectionName();
    RecordCollection collection = collectionServices.get(solrServerName);

    //Remarque useDismax est  false car nous allons utiliser le type de requete "/clustering"
    //         donc pas besoin d'ajouter les paramtres necessaires  dismax
    SolrQuery query = SearchServicesImpl.toSolrQuery(simpleSearch, false, true, true);
    query.setRequestHandler("/clustering");

    query.setParam(ClusteringComponent.COMPONENT_NAME, Boolean.TRUE);
    query.setParam(ClusteringParams.USE_COLLECTION, facet.isClusteringUseCollection());
    query.setParam(ClusteringParams.USE_SEARCH_RESULTS, facet.isClusteringUseSearchResults());
    query.setParam(ClusteringParams.USE_DOC_SET, facet.isClusteringUseDocSet());
    query.setParam(ClusteringParams.ENGINE_NAME, facet.getClusteringEngine());

    //The maximum number of labels to produce
    query.setParam(CarrotParams.NUM_DESCRIPTIONS, "" + maxClusters);
    //      query.setParam(CarrotParams.NUM_DESCRIPTIONS, "" + facet.getCarrotNumDescriptions());

    query.setParam(CarrotParams.OUTPUT_SUB_CLUSTERS, facet.isCarrotOutputSubclusters());
    query.setParam(ConstellioSolrQueryParams.LUCENE_QUERY, simpleSearch.getLuceneQuery());
    query.setParam(ConstellioSolrQueryParams.COLLECTION_NAME, simpleSearch.getCollectionName());
    query.setParam(ConstellioSolrQueryParams.SIMPLE_SEARCH, simpleSearch.toSimpleParams().toString());
    if (user != null) {
        query.setParam(ConstellioSolrQueryParams.USER_ID, "" + user.getId());
    }

    //If true, then the snippet field (if no snippet field, then the title field) will be highlighted and the highlighted text will be used for the snippet. 
    query.setParam(CarrotParams.PRODUCE_SUMMARY, facet.isCarrotProduceSummary());
    if (facet.getCarrotTitleField() != null) {
        IndexField indexField = facet.getCarrotTitleField();
        query.setParam(CarrotParams.TITLE_FIELD_NAME, indexField.getName());
    }
    if (facet.getCarrotUrlField() != null) {
        IndexField indexField = facet.getCarrotUrlField();
        query.setParam(CarrotParams.URL_FIELD_NAME, indexField.getName());
    }
    if (facet.getCarrotSnippetField() != null) {
        IndexField indexField = facet.getCarrotSnippetField();
        query.setParam(CarrotParams.SNIPPET_FIELD_NAME, indexField.getName());
    }

    // Requte Lucene
    //      query.setQuery(luceneQuery);

    // nb rsultats par page
    query.setRows(row);

    // page de dbut
    query.setStart(start);
    //Les resultats ne vont pas etre affichs
    /*query.setHighlight(true);
    query.setHighlightFragsize(100);
    query.setHighlightSnippets(2);*/

    if (collection.isOpenSearch()) {
        query.setParam("openSearchURL", collection.getOpenSearchURL());
    }

    SolrServer server = SolrCoreContext.getSolrServer(solrServerName);

    QueryResponse queryResponse;
    try {
        queryResponse = server.query(query);
    } catch (SolrServerException e) {
        throw new RuntimeException(e);
    }

    NamedList<Object> values = queryResponse.getResponse();
    Object clusters = values.get("clusters");
    return (List<SimpleOrderedMap<Object>>) clusters;
}

From source file:com.doculibre.constellio.services.FacetServicesImpl.java

License:Open Source License

public static SolrQuery toSolrQuery(SimpleSearch simpleSearch, int start, int row,
        boolean includeSingleValueFacets, boolean notIncludedOnly, List<String> customFieldFacets,
        List<String> customQueryFacets, ConstellioUser user) {
    String solrServerName = simpleSearch.getCollectionName();
    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection collection = collectionServices.get(solrServerName);
    SolrServices solrServices = ConstellioSpringUtils.getSolrServices();
    Boolean usesDisMax = solrServices.usesDisMax(collection);
    SolrQuery query;
    if (!collection.isOpenSearch()) {
        query = SearchServicesImpl.toSolrQuery(simpleSearch, usesDisMax, true, includeSingleValueFacets,
                notIncludedOnly);//from  w w  w .  j  a v a  2  s .  c om
    } else {
        query = SearchServicesImpl.toSolrQuery(simpleSearch, usesDisMax, false, true, false);
    }

    query.setParam(ConstellioSolrQueryParams.COLLECTION_NAME, simpleSearch.getCollectionName());
    query.setParam(ConstellioSolrQueryParams.LUCENE_QUERY,
            simpleSearch.getLuceneQuery(includeSingleValueFacets, true));
    query.setParam(ConstellioSolrQueryParams.SIMPLE_SEARCH, simpleSearch.toSimpleParams().toString());
    if (user != null) {
        query.setParam(ConstellioSolrQueryParams.USER_ID, "" + user.getId());
    }

    if (StringUtils.isEmpty(query.getQuery())) {
        query.setQuery(SimpleSearch.SEARCH_ALL);
        query.setRequestHandler("/elevate");
    }

    query.set("shards.qt", "/elevate");
    query.setRequestHandler("/elevate");

    query.setRows(row);
    query.setStart(start);
    query.setHighlight(true);
    query.setHighlightFragsize(100);
    query.setHighlightSnippets(2);

    query.setFacet(true);
    query.setFacetLimit(400);
    query.setFacetMinCount(1);

    if (collection.isOpenSearch()) {
        query.setParam("openSearchURL", collection.getOpenSearchURL());
        Locale locale = simpleSearch.getSingleSearchLocale();
        if (locale != null) {
            query.setParam("lang", locale.getLanguage());
        }
    } else {
        for (CollectionFacet collectionFacet : collection.getCollectionFacets()) {
            if (customFieldFacets == null && collectionFacet.isFieldFacet()) {
                IndexField indexField = collectionFacet.getFacetField();
                String indexFieldName = indexField.getName();
                if (!notIncludedOnly) {
                    query.addFacetField(indexFieldName);
                } else {
                    SearchedFacet searchedFacet = simpleSearch.getSearchedFacet(indexFieldName);
                    if (searchedFacet != null) {
                        if (!searchedFacet.getIncludedValues().isEmpty()) {
                            StringBuffer sbEx = new StringBuffer();
                            sbEx.append("{!ex=dt}");
                            //                                sbEx.append("{!ex=");
                            //                                boolean first = true;
                            //                                for (String includedValue : searchedFacet.getIncludedValues()) {
                            //                                    if (first) {
                            //                                        first = false;
                            //                                    } else {
                            //                                        sbEx.append(",");
                            //                                    }
                            //                                    sbEx.append(includedValue); 
                            //                                }
                            //                                sbEx.append("}");
                            //                                query.setParam("facet.field", sbEx.toString() + indexFieldName);
                            query.addFacetField(sbEx.toString() + indexFieldName);
                        } else {
                            query.addFacetField(indexFieldName);
                        }
                    }
                }
            } else if (customQueryFacets == null && collectionFacet.isQueryFacet()) {
                // Modification Rida, remplacement de collectionFacet.getLabels() par
                // collectionFacet.getLabelledValues()
                // for (I18NLabel valueLabels : collectionFacet.getLabels()) {
                for (I18NLabel valueLabels : collectionFacet.getLabelledValues()) {
                    String facetQuery = valueLabels.getKey();
                    query.addFacetQuery(facetQuery);
                }
            }
        }
        if (customFieldFacets != null) {
            for (String facetField : customFieldFacets) {
                if (!notIncludedOnly) {
                    query.addFacetField(facetField);
                } else {
                    StringBuffer sbEx = new StringBuffer();
                    sbEx.append("{!ex=dt}");
                    //                        sbEx.append("{!ex=");
                    //                        boolean first = true;
                    //                        for (String includedValue : searchedFacet.getIncludedValues()) {
                    //                            if (first) {
                    //                                first = false;
                    //                            } else {
                    //                                sbEx.append(",");
                    //                            }
                    //                            sbEx.append(includedValue); 
                    //                        }
                    //                        sbEx.append("}");
                    query.setParam("facet.field", sbEx.toString() + facetField);
                }
            }
        }

        if (customQueryFacets != null) {
            for (String facetQuery : customQueryFacets) {
                query.addFacetQuery(facetQuery);
            }
        }
    }

    return query;
}

From source file:com.doculibre.constellio.services.IndexFieldServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from w w w. j ava2  s.  c om
public List<String> suggestValues(IndexField indexField, String text) {
    List<String> values = new ArrayList<String>();
    RecordCollection collection = indexField.getRecordCollection();
    SolrServices solrServices = ConstellioSpringUtils.getSolrServices();
    SolrServer solrServer = solrServices.getSolrServer(collection);
    if (solrServer != null) {
        SolrQuery query = new SolrQuery();
        query.setRequestHandler("/admin/luke");
        query.setParam(CommonParams.FL, indexField.getName());
        query.setParam(LukeRequestHandler.NUMTERMS, "" + 100);

        if (text != null) {
            query.setQuery(indexField.getName() + ":" + text + "*");
        }
        if (collection.isOpenSearch()) {
            query.setParam("openSearchURL", collection.getOpenSearchURL());
        }

        try {
            QueryResponse queryResponse = solrServer.query(query);
            NamedList<Object> fields = (NamedList<Object>) queryResponse.getResponse().get("fields");
            if (fields != null) {
                NamedList<Object> field = (NamedList<Object>) fields.get(indexField.getName());
                if (field != null) {
                    NamedList<Object> topTerms = (NamedList<Object>) field.get("topTerms");
                    if (topTerms != null) {
                        for (Map.Entry<String, Object> topTerm : topTerms) {
                            String topTermKey = topTerm.getKey();
                            if (text == null || topTermKey.toLowerCase().startsWith(text.toLowerCase())) {
                                values.add(topTerm.getKey());
                            }
                        }
                    }
                }
            }
        } catch (SolrServerException e) {
            throw new RuntimeException(e);
        }
    }
    return values;
}

From source file:com.doculibre.constellio.services.SearchServicesImpl.java

License:Open Source License

@Override
public QueryResponse search(SimpleSearch simpleSearch, int start, int rows, SearchParams searchParams,
        ConstellioUser user) {/* www  .j  a v a2 s. c  om*/
    QueryResponse queryResponse;

    String collectionName = simpleSearch.getCollectionName();
    if (collectionName != null) {
        RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
        RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
        RecordCollection collection = collectionServices.get(collectionName);

        SolrServices solrServices = ConstellioSpringUtils.getSolrServices();
        Boolean usesDisMax = solrServices.usesDisMax(collection);

        SolrQuery query;
        if (!collection.isOpenSearch()) {
            query = toSolrQuery(simpleSearch, usesDisMax, true, true);
        } else {
            query = toSolrQuery(simpleSearch, usesDisMax, false, true);
        }
        // displayQuery(query);

        String luceneQuery = simpleSearch.getLuceneQuery();
        query.setParam(ConstellioSolrQueryParams.LUCENE_QUERY, luceneQuery);
        query.setParam(ConstellioSolrQueryParams.SIMPLE_SEARCH, simpleSearch.toSimpleParams().toString());
        query.setParam(ConstellioSolrQueryParams.COLLECTION_NAME, collectionName);
        if (user != null) {
            query.setParam(ConstellioSolrQueryParams.USER_ID, "" + user.getId());
        }

        String queryString = query.getQuery();
        if (StringUtils.isEmpty(queryString)) {
            queryString = SimpleSearch.SEARCH_ALL;
        }

        List<Record> pendingExclusions = recordServices.getPendingExclusions(collection);
        while (!pendingExclusions.isEmpty()) {
            IndexingManager indexingManager = IndexingManager.get(collection);
            if (indexingManager.isActive()) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                pendingExclusions = recordServices.getPendingExclusions(collection);
            } else {
                return null;
            }
        }

        // SolrQuery query = new SolrQuery();
        query.set("collectionName", simpleSearch.getCollectionName());
        // query.setQuery(luceneQuery);

        query.set("shards.qt", "/elevate");
        query.setRequestHandler("/elevate");

        // nb rsultats par page
        query.setRows(rows);

        // page de dbut
        query.setStart(start);
        query.setHighlight(searchParams.isHighlightingEnabled());
        if (searchParams.isHighlightingEnabled()) {
            query.setHighlightFragsize(searchParams.getFragsize());
            query.setHighlightSnippets(searchParams.getSnippets());
        }

        if (simpleSearch.getSortField() != null) {
            ORDER order = SimpleSearch.SORT_DESCENDING.equals(simpleSearch.getSortOrder()) ? ORDER.desc
                    : ORDER.asc;
            IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
            IndexField indexField = indexFieldServices.get(simpleSearch.getSortField(), collection);
            if (indexField != null) {
                IndexField sortIndexField = indexFieldServices.getSortFieldOf(indexField);
                if (sortIndexField != null) {
                    query.setSort(sortIndexField.getName(), order);
                }
            }
        }

        if (collection.isOpenSearch()) {
            query.setParam("openSearchURL", collection.getOpenSearchURL());
            Locale locale = simpleSearch.getSingleSearchLocale();
            if (locale != null) {
                query.setParam("lang", locale.getLanguage());
            }
        }

        if (searchParams.getHighlightedFields() == null) {
            IndexField defaultSearchField = collection.getDefaultSearchIndexField();
            query.addHighlightField(defaultSearchField.getName());
            for (CopyField copyFieldDest : defaultSearchField.getCopyFieldsDest()) {
                IndexField copyIndexFieldSource = copyFieldDest.getIndexFieldSource();
                if (copyIndexFieldSource != null && !copyIndexFieldSource.isTitleField()
                        && copyIndexFieldSource.isHighlighted()) {
                    query.addHighlightField(copyIndexFieldSource.getName());
                }
            }
            IndexField titleField = collection.getTitleIndexField();
            if (titleField != null && titleField.isHighlighted()) {
                query.addHighlightField(titleField.getName());
            }
        } else {
            for (String highlightedField : searchParams.getHighlightedFields()) {
                IndexField field = collection.getIndexField(highlightedField);
                if (field != null) {
                    query.addHighlightField(highlightedField);
                }
            }
        }
        SolrServer server = SolrCoreContext.getSolrServer(collectionName);
        if (server != null) {
            try {
                // displayQuery(query);
                queryResponse = server.query(query);
            } catch (SolrServerException e) {
                queryResponse = null;
            }
        } else {
            queryResponse = null;
        }

        //            if (queryResponse != null && !collection.isOpenSearch()) {
        //                StatsCompiler statCompiler = StatsCompiler.getInstance();
        //                try {
        //                    statCompiler.saveStats(collectionName, SolrLogContext.getStatsSolrServer(),
        //                        SolrLogContext.getStatsCompileSolrServer(), queryResponse, luceneQuery);
        //                } catch (SolrServerException e) {
        //                    throw new RuntimeException(e);
        //                } catch (IOException e) {
        //                    throw new RuntimeException(e);
        //                }
        //            }

    } else {
        queryResponse = null;
    }

    // improveQueryResponse(collectionName, queryResponse);
    // System.out.println("Response size" + queryResponse.getResults().getNumFound());
    return queryResponse;
}

From source file:com.doculibre.constellio.services.SearchServicesImpl.java

License:Open Source License

private static void addQueryTextAndOperatorWithSynonyms(SimpleSearch simpleSearch, SolrQuery query,
        boolean useDismax) {
    String collectionName = simpleSearch.getCollectionName();
    if (StringUtils.isNotEmpty(collectionName)) {
        if (simpleSearch.getAdvancedSearchRule() == null) {
            String textQuery = getTextQuery(simpleSearch);
            if (StringUtils.isNotEmpty(textQuery)) {
                String searchType = simpleSearch.getSearchType();
                StringBuffer sb = new StringBuffer();
                // sb.append("(");
                if (SimpleSearch.SEARCH_ALL.equals(textQuery)) {
                    sb.append(textQuery);
                    if (useDismax) {
                        // Non valide avec disMax => disMax doit etre desactivee
                        query.setRequestHandler(SolrServices.DEFAULT_DISTANCE_NAME);
                        LOGGER.warning(/*from w  w w  .  j  ava2  s .  c  o m*/
                                "Dismax is replaced by the default distance since the former does not allow wildcard");
                    }
                } else if (SimpleSearch.EXACT_EXPRESSION.equals(searchType)) {
                    // FIXME a corriger : si "n" terms avec chacun "m" synonyms => traiter les combinaison
                    // de
                    // synonymes
                    // Sinon solution simple: synonymes de l'expression (solution prise pour l'instant)
                    String textAndSynonyms = SynonymUtils.addSynonyms(textQuery, collectionName, true);
                    sb.append(textAndSynonyms);// SynonymUtils.addSynonyms(textQuery,
                    // collectionName)
                } else {
                    // TOUS_LES_MOTS OU AU_MOINS_UN_MOT
                    String operator;
                    if (SimpleSearch.AT_LEAST_ONE_WORD.equals(searchType)) {
                        operator = "OR";
                    } else {
                        operator = "AND";
                    }
                    String[] terms = textQuery.split(" ");
                    for (int i = 0; i < terms.length; i++) {
                        String term = terms[i];
                        String termAndSynonyms = SynonymUtils.addSynonyms(term, collectionName, false);
                        if (term.equals(termAndSynonyms)) {
                            sb.append(term);
                        } else {
                            sb.append("(" + termAndSynonyms + ")");
                        }
                        if (i < terms.length - 1) {
                            // sb.append(operator);
                            sb.append(" " + operator + " ");
                        }
                    }
                }
                // sb.append(")");
                query.setQuery(sb.toString());
            }
        } else {
            query.setQuery(simpleSearch.getLuceneQuery());
        }
    }
}

From source file:com.doculibre.constellio.services.SearchServicesImpl.java

License:Open Source License

private static void addQueryTextAndOperatorWithoutSynonyms(SimpleSearch simpleSearch, SolrQuery query,
        boolean useDismax) {

    String collectionName = simpleSearch.getCollectionName();
    if (StringUtils.isNotEmpty(collectionName)) {
        if (simpleSearch.getAdvancedSearchRule() == null) {
            String textQuery = getTextQuery(simpleSearch);
            if (StringUtils.isNotEmpty(textQuery)) {
                String searchType = simpleSearch.getSearchType();
                if (SimpleSearch.SEARCH_ALL.equals(textQuery)) {
                    query.setQuery(textQuery);
                    // FIXME : AND ou Operateur par defaut?
                    query.setParam("q.op", "AND");
                    if (useDismax) {
                        // Non valide avec disMax => disMax doit etre desactivee
                        query.setRequestHandler(SolrServices.DEFAULT_DISTANCE_NAME);
                        LOGGER.warning(//from   ww  w .  j  a  v a  2 s  . c o m
                                "Dismax is replaced by the default distance since the former does not allow wildcard");
                    }
                } else if (SimpleSearch.AT_LEAST_ONE_WORD.equals(searchType)) {
                    query.setQuery(textQuery);
                    // Operateur OR
                    query.setParam("q.op", "OR");
                    if (useDismax) {
                        query.setParam("mm", "0");
                    }
                } else if (SimpleSearch.EXACT_EXPRESSION.equals(searchType)) {
                    query.setQuery("\"" + textQuery + "\"");
                    if (useDismax) {
                        // FIXME il faut faire quoi avec dismax?
                    }
                } else {
                    if (SimpleSearch.ALL_WORDS.equals(searchType)) {
                        query.setQuery(textQuery);
                        // Operateur AND
                        query.setParam("q.op", "AND");
                        if (useDismax) {
                            query.setParam("mm", "100");
                        }
                    } else {
                        throw new RuntimeException("Invalid searchType " + searchType);
                    }
                }
            }
        } else {
            query.setQuery(simpleSearch.getLuceneQuery());
        }
    }
}