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

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

Introduction

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

Prototype

public SolrQuery setParam(String name, boolean value) 

Source Link

Usage

From source file:org.janusgraph.diskstorage.solr.SolrIndex.java

License:Apache License

private SolrQuery runCommonQuery(RawQuery query, KeyInformation.IndexRetriever information, BaseTransaction tx,
        String collection, String keyIdField) throws BackendException {
    final SolrQuery solrQuery = new SolrQuery(query.getQuery()).addField(keyIdField).setIncludeScore(true)
            .setStart(query.getOffset());
    if (query.hasLimit()) {
        solrQuery.setRows(Math.min(query.getLimit(), batchSize));
    } else {//from w w  w.j  a  va2 s. co  m
        solrQuery.setRows(batchSize);
    }
    if (!query.getOrders().isEmpty()) {
        addOrderToQuery(solrQuery, query.getOrders());
    }

    for (final Parameter parameter : query.getParameters()) {
        if (parameter.value() instanceof String[]) {
            solrQuery.setParam(parameter.key(), (String[]) parameter.value());
        } else if (parameter.value() instanceof String) {
            solrQuery.setParam(parameter.key(), (String) parameter.value());
        }
    }
    return solrQuery;
}

From source file:org.mousephenotype.cda.solr.service.ImageService.java

License:Apache License

/**
 *
 * @param query//from  w  w w .  j a  va  2  s  .  c om
 *            the url from the page name onwards e.g
 *            q=observation_type:image_record
 * @return query response
 * @throws SolrServerException, IOException
 */
public QueryResponse getResponseForSolrQuery(String query) throws SolrServerException, IOException {

    SolrQuery solrQuery = new SolrQuery();
    String[] paramsKeyValues = query.split("&");
    for (String paramKV : paramsKeyValues) {
        logger.debug("paramKV=" + paramKV);
        String[] keyValue = paramKV.split("=");
        if (keyValue.length > 1) {
            String key = keyValue[0];
            String value = keyValue[1];
            // logger.info("param=" + key + " value=" + value);
            solrQuery.setParam(key, value);
        }

    }
    QueryResponse response = impcImagesCore.query(solrQuery);

    return response;
}

From source file:org.mousephenotype.cda.solr.service.ObservationService.java

License:Apache License

/**
 * Get stats for the baseline graphs on the phenotype pages for each parameter/center
 * if phenotypingCenter is null just return all stats for the center otherwise filter on that center
 *///w ww  .j a v a  2  s.  c  o m
public List<FieldStatsInfo> getStatisticsForParameterFromCenter(String parameterStableId,
        String phenotypingCenter) throws SolrServerException, IOException {
    //http://ves-ebi-d0.ebi.ac.uk:8090/mi/impc/dev/solr/experiment/select?q=*:*&stats=true&stats.field=data_point&stats.facet=parameter_stable_id&rows=0&indent=true&fq=phenotyping_center:HMGU&fq=parameter_stable_id:IMPC_CBC_010_001
    //http://ves-ebi-d0.ebi.ac.uk:8090/mi/impc/dev/solr/experiment/select?q=*:*&stats=true&stats.field=data_point&stats.facet=phenotyping_center&rows=0&indent=true&fq=parameter_stable_id:IMPC_CBC_010_001
    logger.debug("calling getStats for baseline");
    SolrQuery query = new SolrQuery().setQuery("*:*");
    query.setGetFieldStatistics(true);
    query.setGetFieldStatistics(ObservationDTO.DATA_POINT);
    query.setParam("stats.facet", ObservationDTO.PHENOTYPING_CENTER);
    query.setFacetLimit(-1);
    query.addFilterQuery(ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":control");
    if (parameterStableId != null) {
        query.addFilterQuery(ObservationDTO.PARAMETER_STABLE_ID + ":" + parameterStableId);
    }

    if (phenotypingCenter != null) {
        query.addFilterQuery(ObservationDTO.PHENOTYPING_CENTER + ":\"" + phenotypingCenter + "\"");
    }

    query.setRows(0);

    logger.debug("SOLR URL getPipelines " + SolrUtils.getBaseURL(experimentCore) + "/select?" + query);

    QueryResponse response = experimentCore.query(query);
    FieldStatsInfo statsInfo = response.getFieldStatsInfo().get(ObservationDTO.DATA_POINT);
    Map<String, List<FieldStatsInfo>> facetToStatsMap = statsInfo.getFacets();

    List<FieldStatsInfo> centerStatsList = null;
    //just get the first result as we only expect 1
    for (String facet : facetToStatsMap.keySet()) {
        centerStatsList = facetToStatsMap.get(facet);
    }

    return centerStatsList;

}

From source file:org.mule.modules.SolrConnector.java

License:Apache License

/**
 * Submit a query to the server and get the results.
 * <p/>//from   www  .  j av a 2  s .  c  o  m
 * {@sample.xml ../../../doc/solr-connector.xml.sample solr:query}
 *
 * @param q       this is the query string called 'q' using solr's nomenclature, normally this has the form of
 *                <em>field</em>:<em>value</em> or just <em>value</em> for querying the default field. Please take a look
 *                at solr's documentation for info on how to write queries.
 * @param handler which handler to use when querying.
 * @param highlightField The field on which to highlight search results.
 * @param highlightSnippets The number of highlight snippets per result.
 * @param facetFields A list of fields for a faceted query. If not null, will enable faceted search.
 * @param facetLimit The facet limit of the query.
 * @param facetMinCount The facet minimum count of the query.
 * @param parameters These parameters will be added to the query.
 * @param filterQueries A list of queries to filter the results.
 * @param sortFields A list of fields (with sorting criteria) in which the results will be sorted. Sorting criteria
 *                   values could be only either <em>asc</em> or <em>desc</em>.
 * @return a {@link QueryResponse QueryResponse} object with the search results.
 * @throws SolrModuleException This exception wraps exceptions thrown when querying the server fails.
 */
@Processor
public QueryResponse query(@FriendlyName("Query") String q,
        @Optional @Placement(group = "Request", order = 0) @Default("/select") String handler,
        @Optional @Placement(group = "Highlighting") String highlightField,
        @Optional @Placement(group = "Highlighting") @Default("1") int highlightSnippets,
        @Optional @Placement(group = "Faceting") @FriendlyName("Facet Fields") List<String> facetFields,
        @Optional @Placement(group = "Faceting") @Default("8") int facetLimit,
        @Optional @Placement(group = "Faceting") @Default("1") int facetMinCount,
        @Optional @Placement(group = "Query Parameters") @FriendlyName("Additional Prameters") Map<String, String> parameters,
        @Optional @Placement(group = "Filter Queries") @FriendlyName("Filter Queries") List<String> filterQueries,
        @Optional @Placement(group = "Sort Fields") @FriendlyName("Sort Fields") Map<String, SolrQuery.ORDER> sortFields)
        throws SolrModuleException {

    SolrQuery query = new SolrQuery(q);
    query.setQueryType(handler);

    applyHighlightingLogic(query, highlightField, highlightSnippets);
    applyFacetingLogic(query, facetFields, facetLimit, facetMinCount);

    //check for parameters
    if (parameters == null) {
        parameters = Collections.EMPTY_MAP;
    }

    //add the additional parameters
    for (String key : parameters.keySet()) {
        query.setParam(key, parameters.get(key));
    }

    //check for filter queries
    if (filterQueries == null) {
        filterQueries = Collections.EMPTY_LIST;
    }

    query.addFilterQuery(filterQueries.toArray(EMPTY_STRING_ARRAY));

    //add order queries
    if (sortFields == null) {
        sortFields = Collections.EMPTY_MAP;
    }

    for (String key : sortFields.keySet()) {
        query.addSortField(key, sortFields.get(key));
    }

    //finally query the server
    try {

        return server.query(query);

    } catch (SolrServerException ex) {
        logger.error("Got server exception while trying to query", ex);
        throw new SolrModuleException("Got server exception while trying to query", ex);
    }
}

From source file:org.mule.modules.SolrConnector.java

License:Apache License

private void applyHighlightingLogic(SolrQuery query, String highlightField, int highlightSnippets) {

    if (highlightField == null) {
        logger.debug("Highlighting is disabled for this query...");
        return;//from  w  w  w .ja  v  a 2 s  . c o  m
    }

    query.setHighlight(true);
    query.setHighlightSnippets(highlightSnippets);
    query.setParam("hl.fl", highlightField);
}

From source file:org.ofbiz.solr.SolrProductSearch.java

License:Apache License

/**
 * Runs a query on the Solr Search Engine and returns the results.
 * <p>//from  w ww  .  ja  v  a 2 s  .c  om
 * This function only returns an object of type QueryResponse, so it is probably not a good idea to call it directly from within the
 * groovy files (As a decent example on how to use it, however, use keywordSearch instead).
 */
public static Map<String, Object> runSolrQuery(DispatchContext dctx, Map<String, Object> context) {
    // get Connection
    HttpSolrServer server = null;
    Map<String, Object> result;

    Integer viewIndex = (Integer) context.get("viewIndex");
    Integer viewSize = (Integer) context.get("viewSize");
    if (viewIndex < 1) {
        viewIndex = 1;
    }
    try {
        server = new HttpSolrServer(SolrUtil.solrUrl);
        // create Query Object
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery((String) context.get("query"));
        // solrQuery.setQueryType("dismax");
        boolean faceted = (Boolean) context.get("facet");
        if (faceted) {
            solrQuery.setFacet(faceted);
            //solrQuery.addFacetField("manu");
            solrQuery.addFacetField("features");
            solrQuery.addFacetField("cat");
            solrQuery.setFacetMinCount(1);
            solrQuery.setFacetLimit(8);

            solrQuery.addFacetQuery("listPrice:[0 TO 50]");
            solrQuery.addFacetQuery("listPrice:[50 TO 100]");
            solrQuery.addFacetQuery("listPrice:[100 TO 250]");
            solrQuery.addFacetQuery("listPrice:[250 TO 500]");
            solrQuery.addFacetQuery("listPrice:[500 TO 1000]");
            solrQuery.addFacetQuery("listPrice:[1000 TO 2500]");
            solrQuery.addFacetQuery("listPrice:[2500 TO 5000]");
            solrQuery.addFacetQuery("listPrice:[5000 TO 10000]");
            solrQuery.addFacetQuery("listPrice:[10000 TO 50000]");
            solrQuery.addFacetQuery("listPrice:[50000 TO *]");
        }

        boolean spellCheck = (Boolean) context.get("spellcheck");
        if (spellCheck) {
            solrQuery.setParam("spellcheck", spellCheck);
        }

        boolean highLight = (Boolean) context.get("highlight");
        if (highLight) {
            solrQuery.setHighlight(highLight);
            solrQuery.setHighlightSimplePre("<span class=\"highlight\">");
            solrQuery.addHighlightField("description");
            solrQuery.setHighlightSimplePost("</span>");
            solrQuery.setHighlightSnippets(2);
        }

        // Set additional Parameter
        // SolrQuery.ORDER order = SolrQuery.ORDER.desc;

        if (viewIndex != null && viewIndex > 0) {
            solrQuery.setStart((viewIndex - 1) * viewSize);
        }
        if (viewSize != null && viewSize > 0) {
            solrQuery.setRows(viewSize);
        }

        // if ((List) context.get("queryFilter") != null && ((ArrayList<SolrDocument>) context.get("queryFilter")).size() > 0) {
        // List filter = (List) context.get("queryFilter");
        // String[] tn = new String[filter.size()];
        // Iterator it = filter.iterator();
        // for (int i = 0; i < filter.size(); i++) {
        // tn[i] = (String) filter.get(i);
        // }
        // solrQuery.setFilterQueries(tn);
        // }
        String queryFilter = (String) context.get("queryFilter");
        if (UtilValidate.isNotEmpty(queryFilter))
            solrQuery.setFilterQueries(queryFilter.split(" "));
        if ((String) context.get("returnFields") != null) {
            solrQuery.setFields((String) context.get("returnFields"));
        }

        // if((Boolean)context.get("sortByReverse"))order.reverse();
        if ((String) context.get("sortBy") != null && ((String) context.get("sortBy")).length() > 0) {
            SolrQuery.ORDER order;
            if (!((Boolean) context.get("sortByReverse")))
                order = SolrQuery.ORDER.asc;
            else
                order = SolrQuery.ORDER.desc;
            solrQuery.setSort(((String) context.get("sortBy")).replaceFirst("-", ""), order);
        }

        if ((String) context.get("facetQuery") != null) {
            solrQuery.addFacetQuery((String) context.get("facetQuery"));
        }

        QueryResponse rsp = server.query(solrQuery);
        result = ServiceUtil.returnSuccess();
        result.put("queryResult", rsp);
    } catch (Exception e) {
        Debug.logError(e, e.getMessage(), module);
        result = ServiceUtil.returnError(e.toString());
    }
    return result;
}

From source file:org.opencommercesearch.AbstractSearchServer.java

License:Apache License

@Override
public SearchResponse browse(BrowseOptions options, SolrQuery query, Site site, Locale locale,
        FilterQuery... filterQueries) throws SearchServerException {

    boolean hasCategoryId = StringUtils.isNotBlank(options.getCategoryId());
    boolean hasCategoryPath = StringUtils.isNotBlank(options.getCategoryPath());
    boolean hasBrandId = StringUtils.isNotBlank(options.getBrandId());
    boolean addCategoryGraph = (options.isFetchCategoryGraph()
            || (hasBrandId && options.isFetchProducts() && !hasCategoryId)) && !options.isRuleBasedPage();

    String categoryPath = null;//from   w  w w .  ja v  a2  s  . com

    if (hasCategoryPath) {
        categoryPath = options.getCategoryPath();
    } else {
        categoryPath = options.getCatalogId() + ".";
    }

    if (options.isRuleBasedPage()) {
        //handle rule based pages
        String filter = rulesBuilder.buildRulesFilter(options.getCategoryId(), locale);
        query.addFilterQuery(filter);
        query.setParam("q", "*:*");

    } else {
        //handle brand, category or onsale pages                
        if (addCategoryGraph) {
            query.setFacetPrefix(CATEGORY_PATH, categoryPath);
            query.addFacetField(CATEGORY_PATH);
            query.set("f.categoryPath.facet.limit", options.getMaxCategoryResults());
        }

        if (!options.isFetchProducts()) {
            query.setRows(0);
        }

        List<String> queryAltParams = new ArrayList<String>();

        if (hasCategoryId) {
            queryAltParams.add(CATEGORY_PATH + ":" + categoryPath);
            query.setParam("q", "");
        }

        if (hasBrandId) {
            queryAltParams.add(BRAND_ID + ":" + options.getBrandId());
            query.setParam("q", "");
        }

        if (options.isOnSale()) {
            queryAltParams.add("onsale" + locale.getCountry() + ":true");
        }

        if (queryAltParams.size() > 0) {

            query.set(Q_ALT, "(" + StringUtils.join(queryAltParams, " AND ") + ")");
        }
    }

    RepositoryItem catalog = null;
    if (site != null) {
        catalog = (RepositoryItem) site.getPropertyValue("defaultCatalog");
    }

    SearchResponse response = null;
    if (options.isRuleBasedPage()) {
        response = doSearch(query, site, catalog, locale, false, true, categoryPath, options.isOnSale(),
                options.getBrandId(), filterQueries);
    } else if (hasCategoryPath) {
        response = doSearch(query, site, catalog, locale, false, false, categoryPath, options.isOnSale(),
                options.getBrandId(), filterQueries);
    } else {
        response = doSearch(query, site, catalog, locale, false, false, null, options.isOnSale(),
                options.getBrandId(), filterQueries);
    }

    if (addCategoryGraph) {
        response.setCategoryGraph(
                createCategoryGraph(response, options.getCategoryPath(), options.getCatalogId(),
                        options.getCategoryId(), options.getDepthLimit(), options.getSeparator()));
    }

    return response;
}

From source file:org.opencommercesearch.AbstractSearchServer.java

License:Apache License

/**
 * Sets the list of fields that should be returned from search.
 * @param query Current SolrQuery being created.
 * @param country Current country code/*from w w  w.j a  va 2  s.c  o  m*/
 * @param catalog Current catalog code
 */
private void setFieldListParams(SolrQuery query, String country, String catalog) {
    String listPrice = "listPrice" + country;
    String salePrice = "salePrice" + country;
    String discountPercent = "discountPercent" + country;

    if (getCatalogCollection().trim().equalsIgnoreCase("catalogEvaluation")) {
        query.setFields("id", "productId", "title", "brand", "isToos", listPrice, salePrice, discountPercent,
                "url" + country, "reviewAverage", "reviews", "isPastSeason", "freeGift" + catalog, "image",
                "score", "isToos");
    } else {
        if (StringUtils.isEmpty(query.getFields())) {
            query.setFields("id", "productId", "title", "brand", "isToos", listPrice, salePrice,
                    discountPercent, "url" + country, "reviewAverage", "reviews", "isPastSeason",
                    "freeGift" + catalog, "image", "isCloseout");
        }
    }

    query.setParam(GroupCollapseParams.GROUP_COLLAPSE, true);
    query.setParam(GroupCollapseParams.GROUP_COLLAPSE_FL,
            listPrice + "," + salePrice + "," + discountPercent + ",color,colorFamily");
}

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;/*from  w  w  w .  j a  va 2 s  . co  m*/

    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.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   w w w.jav  a  2s  . 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);
    }
}