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.opengeoportal.harvester.api.client.solr.SolrSearchParams.java

License:Open Source License

private void buildBoundigBoxQuery(SolrQuery query) {
    if (isValidBBox()) {
        String fqParam = "{!frange l=0 incl=false cache=false}$intx";
        query.addFilterQuery(fqParam);//from  ww  w.  j a  va 2 s.  c  o  m
        // @formatter:off
        // product(
        //    max(
        //       0,
        //       sub(
        //           min(180,MaxX),
        //           max(-180,MinX)
        //       )
        //    ),
        //    max(
        //       0,
        //       sub(
        //           min(41.902277040963,MaxY),
        //           max(-86.30131338825,MinY)
        //       )
        //    )
        // )
        // @formatter:on
        String intxTemplateString = "product(max(0,sub(min(%f,MaxX)," + "max(%f,MinX))),max(0,sub(min(%f,MaxY),"
                + "max(%f,MinY))))";
        String intxParam = String.format(Locale.ENGLISH, intxTemplateString, this.bboxEast, this.bboxWest,
                this.bboxNorth, this.bboxSouth);
        query.setParam("intx", intxParam);
    }
}

From source file:org.openmrs.module.chartsearch.solr.ChartSearchSearcher.java

License:Mozilla Public License

public List<ChartListItem> getDocumentList(Integer patientId, String searchText, Integer start, Integer length,
        List<String> selectedCategories) throws Exception {
    SolrServer solrServer = SolrSingleton.getInstance().getServer();
    SolrQuery query = new SolrQuery();
    List<ChartListItem> list = new ArrayList<ChartListItem>();
    ChartSearchNonFacetFiltering nonFaceting = new ChartSearchNonFacetFiltering();

    searchText = StringUtils.isNotBlank(searchText) ? searchText : "*";
    //check for existence of characters such as ", and : in the search text and submit as it is if so
    if (searchText.contains("\"")) {
        String searchWhole = "text:" + searchText;
        query.setQuery(searchWhole);/*from  w w  w . ja  va  2  s .c  om*/
    } else if (searchText.contains(":")) {
        query.setQuery(searchText);
    } else if (searchText.equals("*")) {
        query.setQuery(String.format("text:(%s)", searchText));
    } else {
        ChartSearchSyntax searchSyntax = new ChartSearchSyntax(searchText);
        searchText = searchSyntax.getSearchQuery();

        if (StringUtils.isNumeric(searchText)) {
            //this allows 36 returning 36.* for numerics
            searchText = searchText + ".*" + " || " + searchText;
        }
        query.setQuery(String.format("text:(%s)", searchText));
    }

    query.addFilterQuery(String.format("person_id:%d", patientId));
    addSelectedFilterQueriesToQuery(query, selectedCategories);
    query.setStart(start);
    query.setRows(length);
    query.setHighlight(true).setHighlightSnippets(1).setHighlightSimplePre("<b>")
            .setHighlightSimplePost("</b>");
    query.setParam("hl.fl", "text");

    query.remove(FacetParams.FACET_FIELD);
    query.setFacet(true);
    //adding facet field for concept_class
    query.addFacetField("concept_class_name");

    nonFaceting.applyNonFacetingLogicWhileSearching(patientId, searchText, selectedCategories, solrServer,
            query, list);

    return list;
}

From source file:org.roda.core.index.utils.SolrUtils.java

public static <T extends IsIndexed> IndexResult<T> find(SolrClient index, Class<T> classToRetrieve,
        Filter filter, Sorter sorter, Sublist sublist, Facets facets, List<String> fieldsToReturn)
        throws GenericException, RequestNotValidException {
    IndexResult<T> ret;//from  w w w  .j  ava 2 s  . c  om
    SolrQuery query = new SolrQuery();
    query.setParam("q.op", DEFAULT_QUERY_PARSER_OPERATOR);
    query.setQuery(parseFilter(filter));
    query.setSorts(parseSorter(sorter));
    query.setStart(sublist.getFirstElementIndex());
    query.setRows(sublist.getMaximumElementCount());
    if (!fieldsToReturn.isEmpty()) {
        query.setFields(fieldsToReturn.toArray(new String[fieldsToReturn.size()]));
    }
    parseAndConfigureFacets(facets, query);

    try {
        QueryResponse response = index.query(getIndexName(classToRetrieve).get(0), query);
        ret = queryResponseToIndexResult(response, classToRetrieve, facets, fieldsToReturn);
    } catch (SolrServerException | IOException e) {
        throw new GenericException("Could not query index", e);
    } catch (SolrException e) {
        throw new RequestNotValidException(e);
    } catch (RuntimeException e) {
        throw new GenericException("Unexpected exception while querying index", e);
    }

    return ret;
}

From source file:org.roda.core.index.utils.SolrUtils.java

public static <T extends IsIndexed> IndexResult<T> find(SolrClient index, Class<T> classToRetrieve,
        Filter filter, Sorter sorter, Sublist sublist, Facets facets, User user, boolean justActive,
        List<String> fieldsToReturn) throws GenericException, RequestNotValidException {
    IndexResult<T> ret;/*www . j a  v  a 2 s  . c o  m*/
    SolrQuery query = new SolrQuery();
    query.setParam("q.op", DEFAULT_QUERY_PARSER_OPERATOR);
    query.setQuery(parseFilter(filter));
    query.setSorts(parseSorter(sorter));
    query.setStart(sublist.getFirstElementIndex());
    query.setRows(sublist.getMaximumElementCount());
    query.setFields(fieldsToReturn.toArray(new String[fieldsToReturn.size()]));
    parseAndConfigureFacets(facets, query);
    if (hasPermissionFilters(classToRetrieve)) {
        query.addFilterQuery(getFilterQueries(user, justActive, classToRetrieve));
    }

    try {
        QueryResponse response = index.query(getIndexName(classToRetrieve).get(0), query);
        ret = queryResponseToIndexResult(response, classToRetrieve, facets, fieldsToReturn);
    } catch (SolrServerException | IOException e) {
        throw new GenericException("Could not query index", e);
    } catch (SolrException e) {
        throw new RequestNotValidException(e.getMessage());
    } catch (RuntimeException e) {
        throw new GenericException("Unexpected exception while querying index", e);
    }

    return ret;
}

From source file:org.roda.core.index.utils.SolrUtils.java

public static <T extends IsIndexed> List<String> suggest(SolrClient index, Class<T> classToRetrieve,
        String field, String queryString, boolean justActive, User user, boolean allowPartial)
        throws GenericException {
    StringBuilder queryBuilder = new StringBuilder();
    appendKeyValue(queryBuilder, field + RodaConstants.INDEX_SEARCH_SUFFIX, queryString + "*");
    SolrQuery query = new SolrQuery();
    query.setParam("q.op", DEFAULT_QUERY_PARSER_OPERATOR);
    query.setQuery(queryBuilder.toString());
    if (hasPermissionFilters(classToRetrieve)) {
        query.addFilterQuery(getFilterQueries(user, justActive, classToRetrieve));
    }/*from  ww w.jav a  2 s.  c  o m*/
    parseAndConfigureFacets(new Facets(new SimpleFacetParameter(field)), query);
    List<String> suggestions = new ArrayList<>();
    try {
        QueryResponse response = index.query(getIndexName(classToRetrieve).get(0), query);
        response.getFacetField(field).getValues().forEach(count -> suggestions.add(count.getName()));
    } catch (SolrServerException | IOException | SolrException e) {
        throw new GenericException("Could not get suggestions", e);
    } catch (RuntimeException e) {
        throw new GenericException("Unexpected exception while querying index", e);
    }

    return suggestions;
}

From source file:org.sakaiproject.nakamura.search.solr.QueryServlet.java

License:Apache License

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    SolrServer server = solrServerService.getServer();

    SolrQuery q = new SolrQuery();

    @SuppressWarnings("unchecked")
    Map<String, String[]> params = request.getParameterMap();

    for (String param : params.keySet()) {
        q.setParam(param, params.get(param));
    }/*w  ww.jav a 2  s  . c  om*/

    try {
        String result = server.query(q).getResponse().toString();

        if (params.get("indent") != null) {
            result = new SolrOutputIndenter().indent(result);
        }

        response.getWriter().println(result);
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.schedoscope.metascope.index.SolrQueryExecutor.java

License:Apache License

public List<String> suggest(String userInput) {
    List<String> suggestions = new LinkedList<String>();

    SolrQuery query = new SolrQuery();
    query.setParam(CommonParams.QT, "/suggest");
    query.setParam("suggest", true);
    query.setParam(SuggesterParams.SUGGEST_BUILD, true);
    query.setParam(SuggesterParams.SUGGEST_DICT, "metascope");
    query.setParam(SuggesterParams.SUGGEST_Q, userInput);

    /* execute the query */
    QueryResponse queryResponse = null;//from   w  w w  .j  a  va 2s  . c  om
    try {
        queryResponse = solrClient.query(query);
    } catch (Exception e) {
        e.printStackTrace();
    }

    List<Suggestion> currentSuggestions = new LinkedList<Suggestion>();
    if (queryResponse != null) {
        SuggesterResponse suggestorRespone = queryResponse.getSuggesterResponse();
        if (suggestorRespone != null) {
            Map<String, List<Suggestion>> suggestorResponeMap = suggestorRespone.getSuggestions();
            for (Entry<String, List<Suggestion>> e : suggestorResponeMap.entrySet()) {
                for (Suggestion suggestion : e.getValue()) {
                    int counter = 0;
                    for (Suggestion s : currentSuggestions) {
                        if (s.getWeight() > suggestion.getWeight()) {
                            counter++;
                        }
                    }
                    currentSuggestions.add(counter, suggestion);
                }
            }
        }
    }

    for (Suggestion suggestion : currentSuggestions) {
        suggestions.add(suggestion.getTerm());
    }

    return suggestions;
}

From source file:org.sindice.siren.demo.ncpr.NCPRQuery.java

License:Apache License

/**
 * A query that shows how to use the nested query parameter to use Solr's
 * query parsers on Solr's fields.//from w ww . j  av a2  s .  co  m
 */
private SolrQuery getNestedQuery() {
    final SolrQuery query = new SolrQuery();
    query.setQuery("DeviceOwner : { Website : uri(www.sourcelondon.net) }");
    query.setParam("nested", "{!lucene} name:university");
    return query;
}

From source file:org.sindice.siren.solr.qparser.TestNestedQuery.java

License:Apache License

@Test
public void testCurlyBracketInNestedQuery() throws IOException, SolrServerException {
    this.addJsonString("1", "{ \"aaa\" : { \"bbb\" : \"ccc\" } }");
    SolrQuery query = new SolrQuery();
    query.setQuery("aaa : bbb");
    query.setParam("nested", "{!keyword} aaa : { bbb : ccc } ");
    query.setRequestHandler("keyword");
    String[] results = this.search(query, ID_FIELD);
    assertEquals(1, results.length);//  w  w w . j  av  a2  s.  c  om

    query = new SolrQuery();
    query.setQuery("aaa : bbb");
    query.setParam("nested", "{!json} { \"node\" : { \"query\" : \"ccc\" } }");
    query.setRequestHandler("keyword");
    results = this.search(query, ID_FIELD);
    assertEquals(1, results.length);
}

From source file:org.sleuthkit.autopsy.keywordsearch.AccountsText.java

License:Open Source License

@Override
@NbBundle.Messages({ "AccountsText.getMarkup.noMatchMsg="
        + "<html><pre><span style\\\\='background\\\\:yellow'>There were no keyword hits on this page. <br />"
        + "The keyword could have been in the file name."
        + " <br />Advance to another page if present, or to view the original text, choose File Text"
        + " <br />in the drop down menu to the right...</span></pre></html>",
        "AccountsText.getMarkup.queryFailedMsg="
                + "<html><pre><span style\\\\='background\\\\:yellow'>Failed to retrieve keyword hit results."
                + " <br />Confirm that Autopsy can connect to the Solr server. "
                + "<br /></span></pre></html>" })
public String getText() {
    loadPageInfo(); //inits once

    SolrQuery q = new SolrQuery();
    q.setShowDebugInfo(DEBUG); //debug
    q.addHighlightField(HIGHLIGHT_FIELD);
    q.setQuery(queryString);//  w  w w  . j a  v  a 2 s .c  om

    //set the documentID filter
    String queryDocumentID = this.solrObjectId + Server.CHUNK_ID_SEPARATOR + this.currentPage;
    q.addFilterQuery(Server.Schema.ID.toString() + ":" + queryDocumentID);

    //configure the highlighter
    q.setParam("hl.useFastVectorHighlighter", "true"); //fast highlighter scales better than standard one NON-NLS
    q.setParam("hl.tag.pre", HIGHLIGHT_PRE); //makes sense for FastVectorHighlighter only NON-NLS
    q.setParam("hl.tag.post", HIGHLIGHT_POST); //makes sense for FastVectorHighlighter only NON-NLS
    q.setParam("hl.fragListBuilder", "single"); //makes sense for FastVectorHighlighter only NON-NLS
    q.setParam("hl.maxAnalyzedChars", Server.HL_ANALYZE_CHARS_UNLIMITED); //docs says makes sense for the original Highlighter only, but not really //NON-NLS

    try {
        //extract highlighting and bail early on null responses
        Map<String, Map<String, List<String>>> highlightingPerDocument = solrServer.query(q, METHOD.POST)
                .getHighlighting();
        Map<String, List<String>> highlightingPerField = highlightingPerDocument.get(queryDocumentID);
        if (highlightingPerField == null) {
            return Bundle.AccountsText_getMarkup_noMatchMsg();
        }
        List<String> highlights = highlightingPerField.get(HIGHLIGHT_FIELD);
        if (highlights == null) {
            return Bundle.AccountsText_getMarkup_noMatchMsg();
        }

        //There should only be one item
        String highlighting = highlights.get(0).trim();

        /*
         * use regex matcher to iterate over occurences of HIGHLIGHT_PRE,
         * and prepend them with an anchor tag.
         */
        Matcher m = ANCHOR_DETECTION_PATTERN.matcher(highlighting);
        StringBuffer sb = new StringBuffer(highlighting.length());
        int count = 0;
        while (m.find()) {
            count++;
            m.appendReplacement(sb, INSERT_PREFIX + count + INSERT_POSTFIX);
        }
        m.appendTail(sb);

        //store total hits for this page, now that we know it
        this.numberOfHitsPerPage.put(this.currentPage, count);
        if (this.currentItem() == 0 && this.hasNextItem()) {
            this.nextItem();
        }

        // extracted content (minus highlight tags) is HTML-escaped
        return "<html><pre>" + sb.toString() + "</pre></html>"; //NON-NLS
    } catch (Exception ex) {
        LOGGER.log(Level.WARNING, "Error executing Solr highlighting query: " + keywords, ex); //NON-NLS
        return Bundle.AccountsText_getMarkup_queryFailedMsg();
    }
}