Example usage for org.apache.solr.common.params ModifiableSolrParams add

List of usage examples for org.apache.solr.common.params ModifiableSolrParams add

Introduction

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

Prototype

public ModifiableSolrParams add(String name, String... val) 

Source Link

Document

Add the given values to any existing name

Usage

From source file:at.newmedialab.lmf.util.solr.suggestion.service.SuggestionService.java

License:Apache License

private SolrQueryResponse query(String query, String df, String[] fields, String[] fqs) {

    SolrQueryResponse rsp = new SolrQueryResponse();

    //append *//from www.j a  v  a 2 s.  com
    if (!query.endsWith("*")) {
        query = query.trim() + "*";
    }

    //Prepare query
    ModifiableSolrParams params = new ModifiableSolrParams();
    SolrQueryRequest req = new LocalSolrQueryRequest(solrCore, params);
    params.add(CommonParams.Q, query.toLowerCase());
    params.add(CommonParams.DF, df);
    params.add("q.op", "AND");
    params.add(FacetParams.FACET, "true");
    params.add(FacetParams.FACET_LIMIT, internalFacetLimit);
    params.add(FacetParams.FACET_MINCOUNT, "1");
    for (String field : fields) {
        params.add(FacetParams.FACET_FIELD, field);
    }
    if (fqs != null) {
        for (String fq : fqs) {
            params.add(CommonParams.FQ, fq);
        }
    }

    if (spellcheck_enabled) {
        params.add("spellcheck", "true");
        params.add("spellcheck.collate", "true");
    }

    try {
        //execute query and return
        searchHandler.handleRequestBody(req, rsp);
        return rsp;
    } catch (SolrException se) {
        throw se;
    } catch (Exception e) {
        e.printStackTrace();
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "internal server error");
    } finally {
        req.close();
    }
}

From source file:com.apexxs.neonblack.solr.Queries.java

License:Apache License

public List<BorderData> doBorderQuery(String lonLat) {
    List<BorderData> entries = new ArrayList<>();

    String queryString = "shape:\"Intersects(" + lonLat + ")\"";

    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*");
    params.add("fq", queryString);

    try {/*  w w w  . j  av a  2  s .  co m*/
        QueryResponse response = geodataCore.query(params);
        entries = response.getBeans(BorderData.class);
    } catch (Exception ex) {
        logger.error("Error in doBorderQuery for argument " + lonLat + " " + ex.getMessage());
    }

    return entries;
}

From source file:com.apexxs.neonblack.solr.Queries.java

License:Apache License

public List<GeoNamesEntry> geoNamesWithinDistanceOf(String lonLat, String distanceInKm) {
    List<GeoNamesEntry> entries = new ArrayList<>();

    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*");
    params.add("fq", "{!geofilt sfield=lonLat}");
    params.add("pt", lonLat);
    params.add("d", distanceInKm);
    params.add("rows", config.getNumProximalHits().toString());

    try {/* w ww  .  jav a  2 s  . c o m*/
        QueryResponse response = geonamesCore.query(params);
        entries = response.getBeans(GeoNamesEntry.class);
    } catch (Exception ex) {
        logger.error("Error in geoNamesWithinDistance for argument " + lonLat + ", " + distanceInKm + " "
                + ex.getMessage());
    }

    return entries;
}

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

License:Open Source License

public static void main(String[] args) throws Exception {
    SolrDocumentList solrDocumentList;/* w  w w  . j a v  a2 s  .  c  o  m*/
    //        
    // InputStream inputXML = OpenSearchSolrServer.class.getResourceAsStream("opensearch_example.xml");
    // SAXReader saxReader = new SAXReader();
    // Document doc = saxReader.read(inputXML);
    // IOUtils.closeQuietly(inputXML);
    //
    // System.out.println("Mock request");
    // solrDocumentList = parse(doc.getRootElement());
    // printResults(solrDocumentList);

    System.out.println("Real request");
    OpenSearchSolrServer solrServer = new OpenSearchSolrServer();
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("openSearchURL", "http://recherched.gouv.qc.ca/internet/opensearch");
    params.add(CommonParams.Q, "doculibre");
    params.add(CommonParams.START, "5");
    params.add(CommonParams.ROWS, "10");
    params.add("lang", "en");
    NamedList<Object> results = solrServer.request(new QueryRequest(params));
    solrDocumentList = (SolrDocumentList) results.get("response");
    printResults(solrDocumentList);

    QueryResponse queryResponse = solrServer.query(params);
    solrDocumentList = queryResponse.getResults();
    printResults(solrDocumentList);
}

From source file:com.doculibre.constellio.solr.handler.component.ManifoldCFAuthorizationComponent.java

License:Open Source License

@Override
public void prepare(ResponseBuilder rb) throws IOException {
    SolrQueryRequest req = rb.req;/*  w w w .j  av a 2 s  .  c  o m*/
    SolrParams params = req.getParams();

    // A runtime param can skip
    if (!params.getBool(ENABLE, true)) {
        return;
    }

    boolean hasManifoldConnector = false;

    String collectioName = params.get(ConstellioSolrQueryParams.COLLECTION_NAME);
    RecordCollectionServices recordCollectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection recordCollection = recordCollectionServices.get(collectioName);
    if (recordCollection != null) {
        for (ConnectorInstance connector : recordCollection.getConnectorInstances()) {
            if (connector.getConnectorType().getName().equals(ManifoldCFConnectorType.CONNECTOR_TYPE_NAME)) {
                hasManifoldConnector = true;
                break;
            } else if (connector.getConnectorType().getName()
                    .equals(IntelliGIDConnectorType.CONNECTOR_TYPE_NAME)) {
                hasManifoldConnector = true;
                break;
            }
        }
    }

    //skip calling the component if we don't use the service (the manifoldcf server could not be up)
    if (hasManifoldConnector) {
        ConstellioUser user;
        String userIdStr = params.get(ConstellioSolrQueryParams.USER_ID);
        if (userIdStr != null) {
            UserServices userServices = ConstellioSpringUtils.getUserServices();
            try {
                user = userServices.get(new Long(userIdStr));
            } catch (NumberFormatException e) {
                user = null;
            }
        } else {
            user = null;
        }

        if (user != null) {
            ModifiableSolrParams newParams = new ModifiableSolrParams(params);
            newParams.add(AUTHENTICATED_USER_NAME, user.getUsername() + "@" + user.getDomain());
            req.setParams(newParams);
        } else {
            ModifiableSolrParams newParams = new ModifiableSolrParams(params);
            newParams.add(AUTHENTICATED_USER_NAME, "guest@guest");
            req.setParams(newParams);
        }
        super.prepare(rb);
    }
}

From source file:com.doculibre.constellio.wicket.servlet.SolrServletEmulator.java

License:Open Source License

@SuppressWarnings("deprecation")
public void writeResponse(String solrQuery, RecordCollection collection, ConstellioUser user,
        HttpServletRequest request, HttpServletResponse response) {
    OutputStream outputStream;/*from ww  w  .j  a va2s. c  o m*/
    try {
        outputStream = response.getOutputStream();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    if (user != null && !user.hasSearchPermission(collection)) {
        throw new RuntimeException("The user doesn't have search permission on the collection");
    } else if (user == null && collection.hasSearchPermission()) {
        throw new RuntimeException("The collection requires a user with search permission");
    } else {
        SimpleSearch simpleSearch = new SimpleSearch();
        simpleSearch.setCollectionName(collection.getName());

        if (solrQuery.contains("facet=constellio")) {
            solrQuery = solrQuery.replace("facet=constellio", "facet=on");
            solrQuery = addConstellioFacets(simpleSearch, solrQuery, collection, user);
            LOGGER.info("Using constellio facets, new query is " + solrQuery);
        }
        ModifiableSolrParams solrParams = new ModifiableSolrParams(
                SolrRequestParsers.parseQueryString(solrQuery));

        String queryType = solrParams.get("qt");
        if (queryType != null && (queryType.toLowerCase().equals("spellchecker")
                || queryType.toLowerCase().equals("spellcheck"))) {
            writeSpellCheckerResponse(simpleSearch, solrParams, collection, user, outputStream);

        } else {
            String cdf = solrParams.get("cdf");
            if (cdf != null && cdf.equals("true")) {
                SearchResultFieldServices searchResultFieldServices = ConstellioSpringUtils
                        .getSearchResultFieldServices();
                List<SearchResultField> fields = searchResultFieldServices.list();
                List<String> fieldNames = new ArrayList<String>();
                for (SearchResultField field : fields) {
                    if (field.getRecordCollection().equals(collection)) {
                        fieldNames.add(field.getIndexField().getName());
                    }
                }
                solrParams.add("fl", StringUtils.join(fieldNames.toArray(), ","));
                solrParams.remove("cdf");
            }
            try {
                SolrServer solrServer = SolrCoreContext.getSolrServer(collection);
                QueryResponse queryResponse = solrServer.query(solrParams);

                if (queryResponse.getStatus() == 0) {
                    String ipAddress = request.getRemoteAddr();
                    simpleSearch.setQuery(solrParams.get("q"));
                    StatsServices statsServices = ConstellioSpringUtils.getStatsServices();
                    statsServices.logSearch(simpleSearch, queryResponse, ipAddress);
                    XMLResponseWriter xmlWriter = new XMLResponseWriter();
                    SolrQueryResponse sResponse = new SolrQueryResponse();
                    sResponse.setAllValues(queryResponse.getResponse());

                    try (OutputStreamWriter out = new OutputStreamWriter(outputStream)) {
                        xmlWriter.write(out, new LocalSolrQueryRequest(null, solrParams), sResponse);
                        out.flush();
                    } catch (IOException e) {
                        throw new RuntimeException("Unable to convert Solr response into XML", e);
                    }
                }
            } catch (SolrException e) {
                // if (!e.logged)
                LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
                // try {
                // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
                // } catch (IOException e1) {
                // throw new RuntimeException(e1);
                // }
                // if (!e.logged) SolrException.log(log,e);
                sendErr(e.code(), SolrException.toStr(e), response, outputStream);
            } catch (Throwable e) {
                LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
                // try {
                // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
                // } catch (IOException e1) {
                // throw new RuntimeException(e1);
                // }
                // SolrException.log(log,e);
                sendErr(500, SolrException.toStr(e), response, outputStream);
            }

            // final SolrCore core =
            // SolrCoreContext.getCores().getCore(collection.getName());
            // // SolrServletRequest solrReq = new SolrServletRequest(core,
            // request);
            // SolrQueryRequest solrReq = new LocalSolrQueryRequest(core,
            // solrParams);
            // SolrQueryResponse solrRsp = new SolrQueryResponse();
            // try {
            //
            // SolrRequestHandler handler =
            // core.getRequestHandler(solrReq.getParams().get(CommonParams.QT));
            // if (handler==null) {
            // LOGGER.log(Level.WARNING, "Unknown Request Handler '" +
            // solrReq.getParams().get(CommonParams.QT)
            // + "' :" + solrReq);
            // // log.warn("Unknown Request Handler '" +
            // solrReq.getQueryType() +"' :" + solrReq);
            // throw new
            // SolrException(SolrException.ErrorCode.BAD_REQUEST,"Unknown Request Handler '"
            // + solrReq.getParams().get(CommonParams.QT) + "'");
            // }
            // core.execute(handler, solrReq, solrRsp );
            // if (solrRsp.getException() == null) {
            // String ipAddress = request.getRemoteAddr();
            //
            // simpleSearch.setQuery(solrParams.get("q"));
            // QueryResponse qrsp = new QueryResponse();
            // qrsp.setResponse(getParsedResponse(solrReq, solrRsp));
            //
            // StatsServices statsServices =
            // ConstellioSpringUtils.getStatsServices();
            // statsServices.logSearch(simpleSearch, qrsp, ipAddress);
            //
            // QueryResponseWriter responseWriter =
            // core.getQueryResponseWriter(solrReq);
            // // Now write it out
            // final String ct = responseWriter.getContentType(solrReq,
            // solrRsp);
            // // don't call setContentType on null
            // if (null != ct) response.setContentType(ct);
            // if (responseWriter instanceof BinaryQueryResponseWriter) {
            // BinaryQueryResponseWriter binWriter =
            // (BinaryQueryResponseWriter) responseWriter;
            // binWriter.write(outputStream, solrReq, solrRsp);
            // } else {
            // String charset =
            // ContentStreamBase.getCharsetFromContentType(ct);
            // Writer out = (charset == null ||
            // charset.equalsIgnoreCase("UTF-8"))
            // ? new OutputStreamWriter(outputStream, UTF8)
            // : new OutputStreamWriter(outputStream, charset);
            // out = new FastWriter(out);
            // responseWriter.write(out, solrReq, solrRsp);
            // out.flush();
            // }
            // } else {
            // Exception e = solrRsp.getException();
            // LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
            // //
            // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
            // int rc=500;
            // if (e instanceof SolrException) {
            // rc=((SolrException)e).code();
            // }
            // sendErr(rc, SolrException.toStr(e), response, outputStream);
            // }
            // } catch (SolrException e) {
            // // if (!e.logged)
            // LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
            // // try {
            // //
            // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
            // // } catch (IOException e1) {
            // // throw new RuntimeException(e1);
            // // }
            // // if (!e.logged) SolrException.log(log,e);
            // sendErr(e.code(), SolrException.toStr(e), response,
            // outputStream);
            // } catch (Throwable e) {
            // LOGGER.log(Level.SEVERE, SolrException.toStr(e), e);
            // // try {
            // //
            // outputStream.write(ExceptionUtils.getFullStackTrace(e).getBytes());
            // // } catch (IOException e1) {
            // // throw new RuntimeException(e1);
            // // }
            // // SolrException.log(log,e);
            // sendErr(500, SolrException.toStr(e), response, outputStream);
            // } finally {
            // // This releases the IndexReader associated with the request
            // solrReq.close();
            // }
        }
    }
}

From source file:com.gisgraphy.fulltext.FulltextQuerySolrHelper.java

License:Open Source License

/**
 * @return A Representation of all the needed parameters
 *//*from  w w w  .  j av a2  s .com*/
public static ModifiableSolrParams parameterize(FulltextQuery query) {
    boolean spellchecker = true;
    ModifiableSolrParams parameters = new ModifiableSolrParams();

    parameters.set(Constants.INDENT_PARAMETER, query.isOutputIndented() ? "on" : "off");
    parameters.set(Constants.ECHOPARAMS_PARAMETER, "none");

    //pagination
    parameters.set(Constants.START_PARAMETER, String.valueOf(query.getFirstPaginationIndex() - 1));// sub 1 because solr start at 0
    parameters.set(Constants.ROWS_PARAMETER, String.valueOf(query.getPagination().getMaxNumberOfResults()));

    //xslt?
    if (query.getOutputFormat() == OutputFormat.ATOM) {
        parameters.set(Constants.STYLESHEET_PARAMETER, Constants.ATOM_STYLESHEET);
    } else if (query.getOutputFormat() == OutputFormat.GEORSS) {
        parameters.set(Constants.STYLESHEET_PARAMETER, Constants.GEORSS_STYLESHEET);
    }

    //set outputformat
    if (query.isSuggest()) {
        parameters.set(Constants.OUTPUT_FORMAT_PARAMETER, OutputFormat.JSON.getParameterValue());
    } else {
        parameters.set(Constants.OUTPUT_FORMAT_PARAMETER, query.getOutputFormat().getParameterValue());
    }

    //set field list
    /*if (query.isSuggest()){
       // parameters.set(Constants.FL_PARAMETER,"");//we took the one by default
    } else*/
    if (query.getOutputFormat() == OutputFormat.ATOM || query.getOutputFormat() == OutputFormat.GEORSS) {
        // force Medium style if ATOM or Geo RSS
        parameters.set(Constants.FL_PARAMETER, outputStyleHelper.getFulltextFieldList(OutputStyle.MEDIUM,
                query.getOutput().getLanguageCode()));
    } else {
        parameters.set(Constants.FL_PARAMETER, outputStyleHelper.getFulltextFieldList(query.getOutput()));
    }

    //filter query
    if (query.getPoint() != null) {
        parameters.set(Constants.SPATIAL_FIELD_PARAMETER, GisFeature.LOCATION_COLUMN_NAME);
        parameters.add(Constants.POINT_PARAMETER, query.getPoint().getY() + "," + query.getPoint().getX());
        if (query.getRadius() != 0) {
            parameters.add(Constants.FQ_PARAMETER, FQ_LOCATION);
            parameters.add(Constants.DISTANCE_PARAMETER, query.getRadius() / 1000 + "");
        } else if (query.getRadius() == 0) {
            parameters.add(Constants.DISTANCE_PARAMETER, MAX_RADIUS + "");
        }
    }
    if (query.getCountryCode() != null && !"".equals(query.getCountryCode().trim())) {
        parameters.add(Constants.FQ_PARAMETER,
                String.format(FQ_COUNTRYCODE, query.getCountryCode().toUpperCase()));
    }

    if (query.getPlaceTypes() != null && containsOtherThingsThanNull(query.getPlaceTypes())) {
        StringBuffer sb = new StringBuffer();
        sb.append("(");
        boolean firstAppend = false;
        for (int i = 0; i < query.getPlaceTypes().length; i++) {
            if (query.getPlaceTypes()[i] != null) {
                if (firstAppend) {
                    sb.append(" OR ");
                }
                sb.append(query.getPlaceTypes()[i].getSimpleName());
                firstAppend = true;
            }
        }
        sb.append(")");
        parameters.add(Constants.FQ_PARAMETER, FQ_PLACETYPE + sb.toString());
    }

    boolean isNumericQuery = isNumericQuery(query.getQuery());
    StringBuffer querybuffer;

    if (query.getQuery().startsWith(FEATUREID_PREFIX)) {
        spellchecker = false;
        String id = query.getQuery().substring(FEATUREID_PREFIX.length());
        String queryString = String.format(NESTED_QUERY_ID_TEMPLATE, id);
        parameters.set(Constants.QUERY_PARAMETER, queryString);
        parameters.set(Constants.QT_PARAMETER, Constants.SolrQueryType.advanced.toString());
        /*if (query.getPoint() != null ){
        parameters.set(Constants.BF_PARAMETER, BF_NEAREST);
        }*/
    } else if (query.getQuery().startsWith(OPENSTREETMAPID_PREFIX)) {
        spellchecker = false;
        String id = query.getQuery().substring(OPENSTREETMAPID_PREFIX.length());
        String queryString = String.format(NESTED_QUERY_OPENSTREETMAP_ID_TEMPLATE, id);
        parameters.set(Constants.QUERY_PARAMETER, queryString);
        parameters.set(Constants.QT_PARAMETER, Constants.SolrQueryType.advanced.toString());
    } else if (query.isSuggest()) {
        if (!isStreetQuery(query) && smartStreetDetection.getStreetTypes(query.getQuery()).size() == 1) {//only if there is no pacetype=street
            //   parameters.set(Constants.BQ_PARAMETER, STREET_BOOST_QUERY);
            parameters.add(Constants.FQ_PARAMETER,
                    FullTextFields.PLACETYPE.getValue() + ":" + Street.class.getSimpleName());
        }
        parameters.set(Constants.QT_PARAMETER, Constants.SolrQueryType.suggest.toString());
        parameters.set(Constants.QUERY_PARAMETER, query.getQuery());
        if (query.getPoint() != null) {
            parameters.set(Constants.BF_PARAMETER, BF_NEAREST);
        }
    } else if (isNumericQuery(query.getQuery())) {
        parameters.set(Constants.QT_PARAMETER, Constants.SolrQueryType.advanced.toString());
        String queryString = String.format(NESTED_QUERY_NUMERIC_TEMPLATE, query.getQuery());
        parameters.set(Constants.QUERY_PARAMETER, queryString);
    } else {
        // we overide the query type
        /*parameters.set(Constants.QT_PARAMETER,
         Constants.SolrQueryType.standard.toString());
        parameters.set(Constants.QUERY_PARAMETER, query.getQuery());*/
        String boost = "";
        if ((!isStreetQuery(query) && smartStreetDetection.getStreetTypes(query.getQuery()).size() == 1)) {
            boost = STREET_BOOST_QUERY;
        } else if (query.getPlaceTypes() == null) {
            boost = CITY_BOOST_QUERY;//we force boost to city because it is not a 'Typed' query
        }
        String is_in = isStreetQuery(query) ? IS_IN_SENTENCE : "";
        String boostNearest = "";
        if (query.getPoint() != null) {//&& query.getRadius()==0
            boostNearest = BF_NEAREST;
        }
        if (!query.isAllwordsRequired()) {
            querybuffer = new StringBuffer(String.format(NESTED_QUERY_NOT_ALL_WORDS_REQUIRED_TEMPLATE, is_in,
                    boost, boostNearest, query.getQuery()));
        } else {
            //with all word required we don't search in is_in
            querybuffer = new StringBuffer(
                    String.format(NESTED_QUERY_TEMPLATE, "", boost, boostNearest, query.getQuery()));

        }
        parameters.set(Constants.QT_PARAMETER, Constants.SolrQueryType.advanced.toString());
        String queryAsStr = querybuffer.toString();
        logger.error("queryAsStr=" + queryAsStr);

        parameters.set(Constants.QUERY_PARAMETER, queryAsStr);
    }

    if (SpellCheckerConfig.enabled && query.hasSpellChecking() && !isNumericQuery && !query.isSuggest()
            && spellchecker) {
        parameters.set(Constants.SPELLCHECKER_ENABLED_PARAMETER, "true");
        parameters.set(Constants.SPELLCHECKER_QUERY_PARAMETER, query.getQuery());
        parameters.set(Constants.SPELLCHECKER_COLLATE_RESULTS_PARAMETER, SpellCheckerConfig.collateResults);
        parameters.set(Constants.SPELLCHECKER_NUMBER_OF_SUGGESTION_PARAMETER,
                SpellCheckerConfig.numberOfSuggestion);
        parameters.set(Constants.SPELLCHECKER_DICTIONARY_NAME_PARAMETER,
                SpellCheckerConfig.spellcheckerDictionaryName.toString());
    }

    return parameters;
}

From source file:com.kmwllc.search.graph.QueryTest.java

License:Open Source License

public static void main(String[] args) {
    String solrUrl = "http://localhost:8983/solr";
    SolrServer solrServer = new HttpSolrServer(solrUrl);
    int numQueries = 1000;
    long totalTime = 0;
    long maxTime = 0;
    long maxCount = 0;
    long largestResultSet = 0;
    for (int id = 0; id < numQueries; id++) {
        ModifiableSolrParams params = new ModifiableSolrParams();
        String queryString = "id:doc_" + id;
        params.add("q", queryString);
        params.add("defType", "graph");
        params.add("rows", "0");
        QueryResponse qresp;/*from ww  w  . ja v a2 s  . c o  m*/
        try {
            qresp = solrServer.query(params);
        } catch (SolrServerException e) {
            //        throw new RuntimeException();
            System.out.println(e.getLocalizedMessage());
            e.printStackTrace();
            break;
        }
        long numFound = qresp.getResults().getNumFound();
        int qTime = qresp.getQTime();
        System.out.println("Query " + queryString + " Found " + numFound + " in " + qTime + "ms.");
        totalTime += qTime;
        if (qTime > maxTime) {
            maxTime = qTime;
            maxCount = numFound;
        }
        if (numFound > largestResultSet) {
            largestResultSet = numFound;
        }
    }
    long avgTime = totalTime / numQueries;
    System.out.println("Total Time : " + totalTime + " AVG: " + avgTime);
    System.out.println("Max Time : " + maxTime + " Num: " + maxCount);
    System.out.println("Largest Result Set : " + largestResultSet);
}

From source file:com.pearson.openideas.cq5.components.services.solr.SolrHelper.java

License:Open Source License

/**
 * Add Filter Criteria to a SOLR Query.//  w  w  w.  ja  va2 s  .c  o  m
 * 
 * @param filterCriteria
 *            the list of filter criteria
 * @param query
 *            the query
 */
public static void addFilterCriteria(final Map<String, List<Object>> filterCriteria, final SolrQuery query) {
    if (filterCriteria != null && filterCriteria.size() > 0) {
        for (String key : filterCriteria.keySet()) {
            List<Object> values = filterCriteria.get(key);
            for (Object value : values) {

                if (value == null) {
                    log.debug("Adding null filter criteria {}.", key);
                    query.addFilterQuery(key);
                } else if (value instanceof String[]) {
                    ModifiableSolrParams params = new ModifiableSolrParams();
                    for (String s : (String[]) value) {
                        log.debug("Adding multi-value filter criteria {}:{}.", key, s);
                        params.add(key, s);
                    }
                    query.add(params);
                } else {
                    log.debug("Adding single-value filter criteria {}:{}.", key, String.valueOf(value));
                    query.addFilterQuery(key + ":" + String.valueOf(value));
                }
            }
        }
    }

}

From source file:de.uni_tuebingen.ub.ixTheo.handler.component.FacetPrefixSortComponent.java

License:Apache License

/**
 * Actually run the query//from  w w  w  .  j a  v  a 2 s  . c  o  m
 */
@Override
public void process(ResponseBuilder rb) throws IOException {
    if (rb.doFacets) {
        final ModifiableSolrParams params = new ModifiableSolrParams();
        final SolrParams origParams = rb.req.getParams();
        final Iterator<String> iter = origParams.getParameterNamesIterator();
        setCollator(origParams.get("lang"));
        while (iter.hasNext()) {
            final String paramName = iter.next();
            // Deduplicate the list with LinkedHashSet, but _only_ for facet
            // params.
            if (!paramName.startsWith(FacetParams.FACET)) {
                params.add(paramName, origParams.getParams(paramName));
                continue;
            }
            final HashSet<String> deDupe = new LinkedHashSet<>(Arrays.asList(origParams.getParams(paramName)));
            params.add(paramName, deDupe.toArray(new String[deDupe.size()]));
        }

        final SimplePrefixSortFacets facets = new SimplePrefixSortFacets(rb.req, rb.getResults().docSet, params,
                rb);
        final NamedList<Object> counts = org.apache.solr.handler.component.FacetComponent
                .getFacetCounts(facets);

        final String[] pivots = params.getParams(FacetParams.FACET_PIVOT);
        if (pivots != null && pivots.length > 0) {
            PivotFacetProcessor pivotProcessor = new PivotFacetProcessor(rb.req, rb.getResults().docSet, params,
                    rb);
            SimpleOrderedMap<List<NamedList<Object>>> v = pivotProcessor.process(pivots);
            if (v != null) {
                counts.add(PIVOT_KEY, v);
            }
        }

        // Check whether we have to reorder out results
        // according to prefix

        final String sort = params.get(FacetParams.FACET_SORT);
        if (FacetPrefixSortParams.FACET_SORT_PREFIX.equals(sort)) {

            // Determine a score relative to the original query

            // Determine the query and make it compatible with our metric
            // class
            // by splitting the single terms
            String[] queryTerms = params.getParams(CommonParams.Q);
            final Collection<String> queryTermsCollection = new ArrayList<>();
            for (String s : queryTerms) {
                // Split at whitespace except we have a quoted term
                Matcher matcher = WHITE_SPACES_WITH_QUOTES_SPLITTING_PATTERN.matcher(s);
                while (matcher.find()) {
                    queryTermsCollection.add(matcher.group().replaceAll("^\"|\"$", ""));
                }
            }

            // In some contexts, i.e. in KWC that are derived from ordinary
            // keywords or if
            // wildcards occur, also add all the query terms as a single
            // phrase term
            // with stripped wildcards
            StringBuilder sb = new StringBuilder();
            for (String s : queryTermsCollection) {
                s = s.replace("*", "");
                sb.append(s);
                sb.append(" ");
            }

            queryTermsCollection.add(sb.toString().trim());

            final ArrayList<String> queryList = new ArrayList<>(queryTermsCollection);
            final String facetfield = params.get(FacetParams.FACET_FIELD);

            // Get the current facet entry and make it compatible with our
            // metric class
            // "facet_fields" itself contains a NamedList with the
            // facet.field as key

            final NamedList<Object> facetFieldsNamedList = (NamedList<Object>) counts.get("facet_fields");
            final NamedList<Object> facetFields = (NamedList<Object>) facetFieldsNamedList.get(facetfield);

            final List<Entry<Entry<String, Object>, Double>> facetPrefixListScored = new ArrayList<>();
            for (final Entry<String, Object> entry : facetFields) {
                final String facetTerms = entry.getKey();

                // Split up each KWC and calculate the scoring

                ArrayList<String> facetList = new ArrayList<>(
                        Arrays.asList(facetTerms.split("(?<!" + Pattern.quote("\\") + ")/")));

                // For usability reasons sort the result facets according to
                // the order of the search
                facetList = KeywordSort.sortToReferenceChain(queryList, facetList);

                final double score = KeywordChainMetric.calculateSimilarityScore(queryList, facetList);

                // Collect the result in a sorted list and throw away
                // garbage
                if (score > 0) {
                    String facetTermsSorted = StringUtils.join(facetList, "/");
                    Map.Entry<String, Object> sortedEntry = new AbstractMap.SimpleEntry<>(facetTermsSorted,
                            entry.getValue());
                    facetPrefixListScored.add(new AbstractMap.SimpleEntry<>(sortedEntry, score));
                }
            }

            Collections.sort(facetPrefixListScored, ENTRY_COMPARATOR);

            // Extract all the values wrap it back to NamedList again and
            // replace in the original structure

            facetFieldsNamedList.clear();
            NamedList<Object> facetNamedListSorted = new NamedList<>();

            // We had to disable all limits and offsets sort according
            // Handle this accordingly now

            int offset = (params.getInt(FacetParams.FACET_OFFSET) != null)
                    ? params.getInt(FacetParams.FACET_OFFSET)
                    : 0;
            int limit = (params.getInt(FacetParams.FACET_LIMIT) != null)
                    ? params.getInt(FacetParams.FACET_LIMIT)
                    : 100;

            // Strip uneeded elements
            int s = facetPrefixListScored.size();
            int off = (offset < s) ? offset : 0;
            limit = (limit < 0) ? s : limit; // Handle a negative limit
            // param, i.e. unlimited results
            int lim = (offset + limit <= s) ? (offset + limit) : s;

            final List<Entry<Entry<String, Object>, Double>> facetPrefixListScoredTruncated = facetPrefixListScored
                    .subList(off, lim);

            for (Entry<Entry<String, Object>, Double> e : facetPrefixListScoredTruncated) {
                facetNamedListSorted.add(e.getKey().getKey(), e.getKey().getValue());
            }

            facetFieldsNamedList.add(facetfield, facetNamedListSorted);
            NamedList<Object> countList = new NamedList<>();
            countList.add("count", facetPrefixListScored.size());
            facetFieldsNamedList.add(facetfield + "-count", countList);

            counts.remove("facet_fields");
            counts.add("facet_fields", facetFieldsNamedList);
        }

        rb.rsp.add("facet_counts", counts);
    }
}