Example usage for org.apache.solr.common.params CommonParams START

List of usage examples for org.apache.solr.common.params CommonParams START

Introduction

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

Prototype

String START

To view the source code for org.apache.solr.common.params CommonParams START.

Click Source Link

Document

zero based offset of matching documents to retrieve

Usage

From source file:org.phenotips.ontology.internal.solr.AbstractSolrOntologyService.java

License:Open Source License

/**
 * Get the number of entries that match a specific Lucene query.
 *
 * @param query a valid the Lucene query as string
 * @return the number of entries matching the query
 *///w ww.ja  v  a2  s  . co  m
protected long count(String query) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(CommonParams.Q, query);
    params.set(CommonParams.START, "0");
    params.set(CommonParams.ROWS, "0");
    SolrDocumentList results;
    try {
        results = this.externalServicesAccess.getServer().query(params).getResults();
        return results.getNumFound();
    } catch (Exception ex) {
        this.logger.error("Failed to count ontology terms: {}", ex.getMessage(), ex);
        return 0;
    }
}

From source file:org.phenotips.ontology.internal.solr.SolrQueryUtils.java

License:Open Source License

/**
 * Adds extra parameters to a Solr query for better term searches, including custom options. More specifically, adds
 * parameters for requesting the score to be included in the results, for requesting a spellcheck result, and sets
 * the {@code start} and {@code rows} parameters when missing.
 *
 * @param originalParams the original Solr parameters to enhance
 * @param queryOptions extra options to include in the query; these override the default values, but don't override
 *            values already set in the query
 * @return the enhanced parameters/*from ww w.  java 2 s .  co m*/
 */
public static SolrParams enhanceParams(SolrParams originalParams, Map<String, String> queryOptions) {
    if (originalParams == null) {
        return null;
    }
    ModifiableSolrParams newParams = new ModifiableSolrParams();
    newParams.set(CommonParams.START, "0");
    newParams.set(CommonParams.ROWS, "1000");
    newParams.set(CommonParams.FL, "* score");
    if (queryOptions != null) {
        for (Map.Entry<String, String> item : queryOptions.entrySet()) {
            newParams.set(item.getKey(), item.getValue());
        }
    }
    for (Map.Entry<String, Object> item : originalParams.toNamedList()) {
        if (item.getValue() != null && item.getValue() instanceof String[]) {
            newParams.set(item.getKey(), (String[]) item.getValue());
        } else {
            newParams.set(item.getKey(), String.valueOf(item.getValue()));
        }
    }
    newParams.set("spellcheck", Boolean.toString(true));
    newParams.set(SpellingParams.SPELLCHECK_COLLATE, Boolean.toString(true));
    return newParams;
}

From source file:org.phenotips.ontology.internal.solr.SolrQueryUtilsTest.java

License:Open Source License

@Test
public void testEnhanceParamsDefaultValues() {
    ModifiableSolrParams input = new ModifiableSolrParams();
    SolrParams output = SolrQueryUtils.enhanceParams(input);
    Assert.assertNull(output.get(CommonParams.Q));
    Assert.assertEquals("* score", output.get(CommonParams.FL));
    Assert.assertEquals(true, output.getBool(SpellingParams.SPELLCHECK_COLLATE));
    Assert.assertEquals(0, (int) output.getInt(CommonParams.START));
    Assert.assertTrue(output.getInt(CommonParams.ROWS) > 100);
}

From source file:org.phenotips.ontology.internal.solr.SolrQueryUtilsTest.java

License:Open Source License

@Test
public void testEnhanceParamsDoesntReplaceExistingValues() {
    ModifiableSolrParams input = new ModifiableSolrParams();
    input.set(CommonParams.Q, "field:value");
    input.set(CommonParams.FL, "id");
    input.set(CommonParams.START, 30);
    input.set(CommonParams.ROWS, 10);//from   ww w.j  ava 2  s  .c  o  m
    SolrParams output = SolrQueryUtils.enhanceParams(input);
    Assert.assertEquals("field:value", output.get(CommonParams.Q));
    Assert.assertEquals("id", output.get(CommonParams.FL));
    Assert.assertEquals(true, output.getBool(SpellingParams.SPELLCHECK_COLLATE));
    Assert.assertEquals(30, (int) output.getInt(CommonParams.START));
    Assert.assertEquals(10, (int) output.getInt(CommonParams.ROWS));
}

From source file:org.phenotips.solr.OmimScriptService.java

License:Open Source License

/**
 * Prepare the map of parameters that can be passed to a Solr query, in order to get a list of diseases matching the
 * selected positive and negative phenotypes.
 *
 * @param phenotypes the list of already selected phenotypes
 * @param nphenotypes phenotypes that are not observed in the patient
 * @return the computed Solr query parameters
 *//*from  ww w  . j a v  a 2s  .  co m*/
private MapSolrParams prepareParams(Collection<String> phenotypes, Collection<String> nphenotypes) {
    Map<String, String> params = new HashMap<String, String>();
    String q = "symptom:" + StringUtils.join(phenotypes, " symptom:");
    if (nphenotypes.size() > 0) {
        q += "  not_symptom:" + StringUtils.join(nphenotypes, " not_symptom:");
    }
    q += " -nameSort:\\** -nameSort:\\+* -nameSort:\\^*";
    params.put(CommonParams.Q, q.replaceAll("HP:", "HP\\\\:"));
    params.put(CommonParams.ROWS, "100");
    params.put(CommonParams.START, "0");
    params.put(CommonParams.DEBUG_QUERY, Boolean.toString(true));
    params.put(CommonParams.EXPLAIN_STRUCT, Boolean.toString(true));

    return new MapSolrParams(params);
}

From source file:org.phenotips.vocabulary.internal.RemoteGeneNomenclature.java

License:Open Source License

@Override
public List<VocabularyTerm> search(Map<String, ?> fieldValues, Map<String, String> queryOptions) {
    try {/*from www  . j  a  va  2  s . c  o  m*/
        HttpGet method = new HttpGet(
                this.searchServiceURL + URLEncoder.encode(generateQuery(fieldValues), Consts.UTF_8.name()));
        method.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
        try (CloseableHttpResponse httpResponse = this.client.execute(method)) {
            String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8);
            JSONObject responseJSON = new JSONObject(response);
            JSONArray docs = responseJSON.getJSONObject(RESPONSE_KEY).getJSONArray(DATA_KEY);
            if (docs.length() >= 1) {
                List<VocabularyTerm> result = new LinkedList<>();
                // The remote service doesn't offer any query control, manually select the right range
                int start = 0;
                if (queryOptions.containsKey(CommonParams.START)
                        && StringUtils.isNumeric(queryOptions.get(CommonParams.START))) {
                    start = Math.max(0, Integer.parseInt(queryOptions.get(CommonParams.START)));
                }
                int end = docs.length();
                if (queryOptions.containsKey(CommonParams.ROWS)
                        && StringUtils.isNumeric(queryOptions.get(CommonParams.ROWS))) {
                    end = Math.min(end, start + Integer.parseInt(queryOptions.get(CommonParams.ROWS)));
                }

                for (int i = start; i < end; ++i) {
                    result.add(new JSONOntologyTerm(docs.getJSONObject(i), this));
                }
                return result;
                // This is too slow, for the moment only return summaries
                // return getTerms(ids);
            }
        } catch (IOException | JSONException ex) {
            this.logger.warn("Failed to search gene names: {}", ex.getMessage());
        }
    } catch (UnsupportedEncodingException ex) {
        // This will not happen, UTF-8 is always available
    }
    return Collections.emptyList();
}

From source file:org.phenotips.vocabulary.internal.solr.AbstractSolrVocabulary.java

License:Open Source License

/**
 * Get the number of entries that match a specific Lucene query.
 *
 * @param query a valid the Lucene query as string
 * @return the number of entries matching the query
 *//*  w ww. j a v a  2  s  .  c om*/
protected long count(String query) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(CommonParams.Q, query);
    params.set(CommonParams.START, "0");
    params.set(CommonParams.ROWS, "0");
    SolrDocumentList results;
    try {
        this.logger.debug("Counting terms matching [{}] in [{}]", query, getCoreName());
        results = this.externalServicesAccess.getSolrConnection().query(params).getResults();
        return results.getNumFound();
    } catch (Exception ex) {
        this.logger.error("Failed to count ontology terms: {}", ex.getMessage(), ex);
        return -1;
    }
}

From source file:org.phenotips.vocabulary.internal.solr.SolrQueryUtils.java

License:Open Source License

/**
 * Adds extra parameters to a Solr query for better term searches, including custom options. More specifically, adds
 * parameters for requesting the score to be included in the results, for requesting a spellcheck result, and sets
 * the {@code start} and {@code rows} parameters when missing.
 *
 * @param originalParams the original Solr parameters to enhance
 * @param queryOptions extra options to include in the query; these override the default values, but don't override
 *            values already set in the query
 * @return the enhanced parameters//from  ww  w .  ja  v a 2s  . c om
 */
public static SolrParams enhanceParams(SolrParams originalParams, Map<String, String> queryOptions) {
    if (originalParams == null) {
        return null;
    }
    ModifiableSolrParams newParams = new ModifiableSolrParams();
    newParams.set(CommonParams.START, "0");
    newParams.set(CommonParams.ROWS, "1000");
    newParams.set(CommonParams.FL, "* score");
    if (queryOptions != null) {
        for (Map.Entry<String, String> item : queryOptions.entrySet()) {
            newParams.set(item.getKey(), item.getValue());
        }
    }
    for (Map.Entry<String, Object> item : originalParams.toNamedList()) {
        if (item.getValue() != null && item.getValue() instanceof String[]) {
            newParams.set(item.getKey(), (String[]) item.getValue());
        } else {
            newParams.set(item.getKey(), String.valueOf(item.getValue()));
        }
    }
    if (newParams.get(SPELLCHECK) == null) {
        newParams.set(SPELLCHECK, Boolean.toString(true));
        newParams.set(SpellingParams.SPELLCHECK_COLLATE, Boolean.toString(true));
    }
    return newParams;
}

From source file:org.sakaiproject.nakamura.message.LiteCountServlet.java

License:Apache License

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    LOGGER.debug("In count servlet");

    Session session = StorageClientUtils
            .adaptToSession(request.getResourceResolver().adaptTo(javax.jcr.Session.class));

    try {// w  w w  . ja  va2  s .com
        // Do the query
        // We do the query on the user his messageStore's path.
        String messageStorePath = ClientUtils
                .escapeQueryChars(messagingService.getFullPathToStore(request.getRemoteUser(), session));
        //path:a\:zach/contacts AND resourceType:sakai/contact AND state:("ACCEPTED" -NONE) (name:"*" OR firstName:"*" OR lastName:"*" OR email:"*")) AND readers:(zach OR everyone)&start=0&rows=25&sort=score desc
        StringBuilder queryString = new StringBuilder(
                "(path:" + messageStorePath + "* AND resourceType:sakai/message" + " AND type:internal");

        // Get the filters
        if (request.getRequestParameter("filters") != null && request.getRequestParameter("values") != null) {
            // The user wants to filter some things.
            String[] filters = request.getRequestParameter("filters").getString().split(",");
            String[] values = request.getRequestParameter("values").getString().split(",");
            if (filters.length != values.length) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "The amount of values doesn't match the amount of keys.");
            }

            for (int i = 0; i < filters.length; i++) {
                String filterName = filters[i].replaceFirst("sakai:", "");
                queryString.append(" AND " + filterName + ":\"" + values[i] + "\"");
            }
        }

        queryString.append(")");

        // The "groupedby" clause forces us to inspect every message. If not
        // specified, all we need is the count.
        final long itemCount;
        if (request.getRequestParameter("groupedby") == null) {
            itemCount = 0;
        } else {
            itemCount = MAX_RESULTS_COUNTED;
        }
        Map<String, Object> queryOptions = ImmutableMap.of(PARAMS_ITEMS_PER_PAGE,
                (Object) Long.toString(itemCount), CommonParams.START, "0", CommonParams.SORT, "_created desc");

        Query query = new Query(queryString.toString(), queryOptions);
        LOGGER.info("Submitting Query {} ", query);
        SolrSearchResultSet resultSet = searchServiceFactory.getSearchResultSet(request, query, false);
        Iterator<Result> resultIterator = resultSet.getResultSetIterator();

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        JSONWriter write = new JSONWriter(response.getWriter());

        if (request.getRequestParameter("groupedby") == null) {
            write.object();
            write.key("count");
            write.value(resultSet.getSize());
            write.endObject();
        } else {
            // The user want to group the count by a specified set.
            // We will have to traverse each node, get that property and count each
            // value for it.
            String groupedby = request.getRequestParameter("groupedby").getString();
            if (groupedby.startsWith("sakai:")) {
                groupedby = groupedby.substring(6);
            }

            long count = 0;
            Map<String, Integer> mapCount = new HashMap<String, Integer>();
            while (resultIterator.hasNext()) {
                Result n = resultIterator.next();

                if (count >= MAX_RESULTS_COUNTED) {
                    break;
                }
                count++;

                if (n.getProperties().containsKey(groupedby)) {
                    String key = (String) n.getFirstValue(groupedby);
                    int val = 1;
                    if (mapCount.containsKey(key)) {
                        val = mapCount.get(key) + 1;
                    }
                    mapCount.put(key, val);
                }
            }

            write.object();
            write.key("count");
            write.array();
            for (Entry<String, Integer> e : mapCount.entrySet()) {
                write.object();

                write.key("group");
                write.value(e.getKey());
                write.key("count");
                write.value(e.getValue());

                write.endObject();
            }
            write.endArray();
            write.endObject();

        }

    } catch (JSONException e) {
        LOGGER.error("JSON issue from query " + request.getQueryString(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage());
    } catch (Exception e) {
        LOGGER.error("Unexpected exception for query " + request.getQueryString(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage());
    }

}

From source file:org.sakaiproject.nakamura.message.search.MessageCountServiceImpl.java

License:Apache License

@Override
public long getUnreadMessageCount(SlingHttpServletRequest request) {
    final javax.jcr.Session jcrSession = request.getResourceResolver().adaptTo(javax.jcr.Session.class);
    final Session session = StorageClientUtils.adaptToSession(jcrSession);
    AuthorizableManager authzManager = null;
    Authorizable au = null;//from   ww w . j  a  va  2  s. c om
    try {
        authzManager = session.getAuthorizableManager();
        au = authzManager.findAuthorizable(request.getRemoteUser());
    } catch (Exception e) {
        LOGGER.error("error getting Authorizable for remote user", e);
    }

    if (au == null) {
        return 0;
    }

    // We don't do queries for anonymous users. (Possible ddos hole).
    String userID = au.getId();
    if (UserConstants.ANON_USERID.equals(userID)) {
        return 0;
    }

    String store = messagingService.getFullPathToStore(au.getId(), session);
    store = ISO9075.encodePath(store);
    String queryString = "messagestore:" + ClientUtils.escapeQueryChars(store)
            + " AND type:internal AND messagebox:inbox AND read:false";
    final Map<String, Object> queryOptions = ImmutableMap.of(PARAMS_ITEMS_PER_PAGE, (Object) "0",
            CommonParams.START, "0");
    Query query = new Query(queryString, queryOptions);
    LOGGER.debug("Submitting Query {} ", query);

    SolrSearchResultSet resultSet = null;
    try {
        resultSet = searchServiceFactory.getSearchResultSet(request, query, false);
    } catch (SolrSearchException e) {
        LOGGER.error("error executing query", e);
        return 0;
    }

    return resultSet.getSize();
}