Example usage for org.apache.solr.client.solrj.impl HttpSolrClient query

List of usage examples for org.apache.solr.client.solrj.impl HttpSolrClient query

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj.impl HttpSolrClient query.

Prototype

public QueryResponse query(SolrParams params) throws SolrServerException, IOException 

Source Link

Document

Performs a query to the Solr server

Usage

From source file:com.gdn.x.ui.controller.CommonController.java

protected List searchByQuery(String queryParameter) throws MalformedURLException, SolrServerException {
    List actualResult = new ArrayList<String>();
    try {//from ww w.ja va  2  s .  co m
        //            for solr 5
        HttpSolrClient solr = new HttpSolrClient(solrUrlSearch);
        //for Solr 4
        //            HttpSolrServer solr = new HttpSolrServer("");

        SolrQuery query = new SolrQuery();

        query.setQuery(queryParameter);
        query.setFields("id");
        query.setRequestHandler("/browse");
        query.setStart(0);
        query.setRows(40);
        QueryResponse response = solr.query(query);
        SolrDocumentList results = response.getResults();

        int j = 0;
        for (int i = 0; i < results.size(); ++i, j++) {
            actualResult.add(results.get(i).get("id"));
        }
    } catch (IOException ex) {
        Logger.getLogger(RunGoldenListController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return actualResult;
}

From source file:com.gdn.x.ui.controller.Evaluation.CommonControllerEvaluation.java

protected List searchByQueryEvaluation(String queryParameter)
        throws MalformedURLException, SolrServerException {
    List actualResult = new ArrayList<String>();
    try {/*from  w  w  w .  j a  v a 2s .  c  o m*/
        //            for solr 5
        HttpSolrClient solr = new HttpSolrClient(solrUrlSearch);
        //for Solr 4
        //            HttpSolrServer solr = new HttpSolrServer("http://172.17.132.9:8983/solr/collection3");

        SolrQuery query = new SolrQuery();

        query.setQuery(queryParameter);
        query.setFields("id");
        query.setRequestHandler("/browse");
        query.setStart(0);
        query.setRows(24);
        QueryResponse response = solr.query(query);
        SolrDocumentList results = response.getResults();

        int j = 0;
        for (int i = 0; i < results.size(); ++i, j++) {
            actualResult.add(results.get(i).get("id"));
        }
        //                System.out.println(results.getNumFound());
        //            System.out.println(actualResult);

    } catch (IOException ex) {
        Logger.getLogger(RunGoldenListController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return actualResult;
}

From source file:edu.tamu.tcat.trc.digires.books.hathitrust.HTFilesSearchService.java

License:Apache License

@Override
public CopySearchResult find(ContentQuery query) throws ResourceAccessException {
    if (solrServerFuture == null)
        throw new IllegalStateException("Service is disposed");

    // HACK hard coded. Should be provided to the service
    try {// www.j  a v  a2s.c  om
        HttpSolrClient solrServer = solrServerFuture.get(2, TimeUnit.MINUTES);
        Objects.requireNonNull(solrServer, "No active connection to Solr Server");

        String queryString = formatQueryString(query);

        SolrQuery solrQuery = new SolrQuery(queryString);
        solrQuery.setRows(Integer.valueOf(query.getLimit()));
        solrQuery.setStart(Integer.valueOf(query.getOffset()));
        //         solrQuery.addFilterQuery(buildDateFilter(query));
        QueryResponse response = solrServer.query(solrQuery);
        return getSearchResults(response);
    } catch (Exception ex) {
        throw new ResourceAccessException("", ex);
    }

}

From source file:it.damore.solr.importexport.App.java

License:Open Source License

/**
 * @param client/*www  . ja  v  a 2  s .co m*/
 * @param outputFile
 * @throws SolrServerException
 * @throws IOException
 */
private static void readAllDocuments(HttpSolrClient client, File outputFile)
        throws SolrServerException, IOException {

    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery("*:*");
    if (config.getFilterQuery() != null) {
        solrQuery.addFilterQuery(config.getFilterQuery());
    }
    solrQuery.setRows(0);

    solrQuery.addSort(config.getUniqueKey(), ORDER.asc); // Pay attention to this line

    String cursorMark = CursorMarkParams.CURSOR_MARK_START;

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

    // objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    DateFormat df = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:sss'Z'");
    objectMapper.setDateFormat(df);
    objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);

    QueryResponse r = client.query(solrQuery);

    long nDocuments = r.getResults().getNumFound();
    logger.info("Found " + nDocuments + " documents");

    if (!config.getDryRun()) {
        logger.info("Creating " + config.getFileName());

        Set<SkipField> skipFieldsEquals = config.getSkipFieldsSet().stream()
                .filter(s -> s.getMatch() == MatchType.EQUAL).collect(Collectors.toSet());
        Set<SkipField> skipFieldsStartWith = config.getSkipFieldsSet().stream()
                .filter(s -> s.getMatch() == MatchType.STARTS_WITH).collect(Collectors.toSet());
        Set<SkipField> skipFieldsEndWith = config.getSkipFieldsSet().stream()
                .filter(s -> s.getMatch() == MatchType.ENDS_WITH).collect(Collectors.toSet());

        try (PrintWriter pw = new PrintWriter(outputFile)) {
            solrQuery.setRows(200);
            boolean done = false;
            while (!done) {
                solrQuery.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
                QueryResponse rsp = client.query(solrQuery);
                String nextCursorMark = rsp.getNextCursorMark();

                for (SolrDocument d : rsp.getResults()) {
                    skipFieldsEquals.forEach(f -> d.removeFields(f.getText()));
                    if (skipFieldsStartWith.size() > 0 || skipFieldsEndWith.size() > 0) {
                        Map<String, Object> collect = d.entrySet().stream()
                                .filter(e -> !skipFieldsStartWith.stream()
                                        .filter(f -> e.getKey().startsWith(f.getText())).findFirst()
                                        .isPresent())
                                .filter(e -> !skipFieldsEndWith.stream()
                                        .filter(f -> e.getKey().endsWith(f.getText())).findFirst().isPresent())
                                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
                        pw.write(objectMapper.writeValueAsString(collect));
                    } else {
                        pw.write(objectMapper.writeValueAsString(d));
                    }
                    pw.write("\n");
                }
                if (cursorMark.equals(nextCursorMark)) {
                    done = true;
                }

                cursorMark = nextCursorMark;
            }

        }
    }

}

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

License:Apache License

/**
 * Runs a query on the Solr Search Engine and returns the results.
 * <p>//from  ww w  . j av a 2  s . c  o m
 * 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
    HttpSolrClient client = null;
    String solrIndexName = (String) context.get("indexName");
    Map<String, Object> result;
    try {
        client = SolrUtil.getInstance().getHttpSolrClient(solrIndexName);
        // 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("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 (context.get("viewIndex") != null && (Integer) context.get("viewIndex") > 0) {
            solrQuery.setStart((Integer) context.get("viewIndex"));
        }
        if (context.get("viewSize") != null && (Integer) context.get("viewSize") > 0) {
            solrQuery.setRows((Integer) context.get("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 = client.query(solrQuery);
        result = ServiceUtil.returnSuccess();
        result.put("queryResult", rsp);
    } catch (Exception e) {
        Debug.logError(e, e.getMessage(), module);
        result = ServiceUtil.returnError(e.toString());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                // do nothing
            }
        }
    }
    return result;
}

From source file:org.zaizi.manifoldcf.agents.output.solrwrapper.SolrWrapperConnector.java

License:Open Source License

/**
 * Returns from the Entity core all the children entities of a specific primary document
 * //from w w  w .j a  v  a  2  s.co  m
 * ATTENTION : This can be improved accessing with GET only the documentURI doc, then retrieving or entity types or
 * entities ID ( that are there with SMLT fields)
 * 
 * @param documentURI
 * @param configuration
 * @return
 */
private List<String> retrieveChildrenFromSolr(String documentURI, ConfigParams configuration, String field) {
    QueryResponse getResponse;
    SolrQuery getQuery;
    List<String> childrenIds = new ArrayList<String>();
    SolrDocumentList results = new SolrDocumentList();

    HttpSolrClient solrServer = getHttpSolrServer(configuration);

    getQuery = new SolrQuery();
    getQuery.setRequestHandler("/get");
    getQuery.set("ids", documentURI);

    try {
        getResponse = solrServer.query(getQuery);
        results = getResponse.getResults();
        if (results.size() > 0) {
            SolrDocument d = results.get(0);
            childrenIds = (List<String>) d.getFieldValue(field);
        }

    } catch (SolrServerException e) {
        Logging.connectors.error("Error retrieving children for : " + documentURI, e);

    } finally {
        return childrenIds;
    }

}

From source file:se.nrm.dina.naturarv.portal.Main.java

public static void main(String[] args) {
    try {/*ww w . java2s. co  m*/
        HttpSolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr").build();
        SolrQuery query = new SolrQuery();

        query.setQuery("*");
        query.setFields("clnm");
        query.setStart(0);

        QueryResponse response = client.query(query);
        SolrDocumentList results = response.getResults();
        for (int i = 0; i < results.size(); ++i) {
            System.out.println(results.get(i));
        }
    } catch (SolrServerException | IOException ex) {

    }
}