Example usage for org.apache.solr.client.solrj SolrClient query

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

Introduction

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

Prototype

public QueryResponse query(SolrParams params) throws SolrServerException, IOException 

Source Link

Document

Performs a query to the Solr server

Usage

From source file:org.mycore.restapi.v1.MCRRestAPIClassifications.java

License:Open Source License

private void filterNonEmpty(String classId, Element e) {
    SolrClient solrClient = MCRSolrClientFactory.getSolrClient();
    for (int i = 0; i < e.getChildren("category").size(); i++) {
        Element cat = e.getChildren("category").get(i);

        SolrQuery solrQquery = new SolrQuery();
        solrQquery.setQuery("category:\""
                + MCRSolrUtils.escapeSearchValue(classId + ":" + cat.getAttributeValue("ID")) + "\"");
        solrQquery.setRows(0);/*w  w w  .java 2s .c  om*/
        try {
            QueryResponse response = solrClient.query(solrQquery);
            SolrDocumentList solrResults = response.getResults();
            if (solrResults.getNumFound() == 0) {
                e.removeContent(cat);
                i--;
            }
        } catch (SolrServerException | IOException exc) {
            LOGGER.error(exc);
        }
    }
    for (int i = 0; i < e.getChildren("category").size(); i++) {
        filterNonEmpty(classId, e.getChildren("category").get(i));
    }
}

From source file:org.mycore.restapi.v1.utils.MCRRestAPIObjectsHelper.java

License:Open Source License

private static MCRObject retrieveMCRObject(String idString) throws MCRRestAPIException {
    String key = "mcr"; // the default value for the key
    if (idString.contains(":")) {
        int pos = idString.indexOf(":");
        key = idString.substring(0, pos);
        idString = idString.substring(pos + 1);
        if (!key.equals("mcr")) {
            try {
                idString = URLDecoder.decode(idString, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                //will not happen
            }/*from  w w w .j av  a 2  s  . c  o  m*/
            //ToDo - Shall we restrict the key set with a property?

            //throw new MCRRestAPIException(MCRRestAPIError.create(Response.Status.BAD_REQUEST,
            //        "The ID is not valid.", "The prefix is unkown. Only 'mcr' is allowed."));
        }
    }
    if (key.equals("mcr")) {

        MCRObjectID mcrID = null;
        try {
            mcrID = MCRObjectID.getInstance(idString);
        } catch (Exception e) {
            throw new MCRRestAPIException(MCRRestAPIError.create(Response.Status.BAD_REQUEST,
                    "The MyCoRe ID '" + idString
                            + "' is not valid. Did you use the proper format: '{project}_{type}_{number}'?",
                    e.getMessage()));
        }

        if (!MCRMetadataManager.exists(mcrID)) {
            throw new MCRRestAPIException(MCRRestAPIError.create(Response.Status.NOT_FOUND,
                    "There is no object with the given MyCoRe ID '" + idString + "'.", null));
        }

        return MCRMetadataManager.retrieveMCRObject(mcrID);
    } else {
        SolrClient solrClient = MCRSolrClientFactory.getSolrClient();
        SolrQuery query = new SolrQuery();
        query.setQuery(key + ":" + idString);
        try {
            QueryResponse response = solrClient.query(query);
            SolrDocumentList solrResults = response.getResults();
            if (solrResults.getNumFound() == 1) {
                String id = solrResults.get(0).getFieldValue("returnId").toString();
                return retrieveMCRObject(id);
            } else {
                if (solrResults.getNumFound() == 0) {
                    throw new MCRRestAPIException(MCRRestAPIError.create(Response.Status.NOT_FOUND,
                            "There is no object with the given ID '" + key + ":" + idString + "'.", null));
                } else {
                    throw new MCRRestAPIException(
                            MCRRestAPIError.create(Response.Status.NOT_FOUND,
                                    "The ID is not unique. There are " + solrResults.getNumFound()
                                            + " objecst fore the given ID '" + key + ":" + idString + "'.",
                                    null));
                }
            }
        } catch (SolrServerException | IOException e) {
            LOGGER.error(e);
        }
        return null;
    }
}

From source file:org.phenotips.variantstore.db.solr.SolrUtils.java

License:Open Source License

/**
 * Loop over all the documents returned by the query. This method queries the DB multiple times. Every time we get
 * data back, we pass it onto a processor, and stop processing data if the processor tells us it's had enough.
 *
 * @param server    the solr db//from  w  w w .ja  v  a  2s .  co  m
 * @param q         the query
 * @param uniqueKey the solr uniqueKey field to sort on. Required for solr's Cursor functionality.
 *@param processor the processor to handle the data. If the function returns true, we stop fetching more data.
 *  @throws IOException
 * @throws SolrServerException
 */
static void processAllDocs(SolrClient server, SolrQuery q, String uniqueKey,
        Function<Collection<SolrDocument>, Boolean> processor) throws IOException, SolrServerException {
    boolean done = false;
    String oldCursorMark;
    String cursorMark = CursorMarkParams.CURSOR_MARK_START;
    QueryResponse resp;

    // Cursor functionality requires a sort containing a uniqueKey field tie breaker
    q.addSort(uniqueKey, SolrQuery.ORDER.desc);

    while (!done) {
        oldCursorMark = cursorMark;
        q.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
        resp = server.query(q);
        done = processor.apply(resp.getResults());
        cursorMark = resp.getNextCursorMark();
        done = done || oldCursorMark.equals(cursorMark);
    }
}

From source file:richtercloud.solr.bean.indexing.NewMain.java

/**
 * @param args the command line arguments
 *//*ww w.  ja v a2  s  .  c  o  m*/
public static void main(String[] args) {
    SolrClient solrServer;
    solrServer = new HttpSolrClient.Builder("http://localhost:8983/solr/test1").build();
    List<MyBean> myBeans = new LinkedList<>(
            Arrays.asList(new MyBean("a", "1", 1), new MyBean("b", "2", 2), new MyBean("c", "3", 3)));
    String searchTerm = "a";
    try {
        solrServer.addBeans(myBeans);
        solrServer.commit();
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("q", searchTerm);
        QueryResponse queryResponse = solrServer.query(solrQuery);
        List<MyBean> foundDocuments = queryResponse.getBeans(MyBean.class);
        System.out.println(foundDocuments);
    } catch (SolrServerException | IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:uk.bl.wa.annotation.Annotator.java

License:Open Source License

private static void searchAndApplyAnnotations(Annotator anr, SolrClient solr, SolrQuery parameters)
        throws SolrServerException, URISyntaxException, IOException {
    QueryResponse response = solr.query(parameters);
    SolrDocumentList list = response.getResults();
    for (SolrDocument doc : list) {
        SolrInputDocument solrInDoc = new SolrInputDocument();
        solrInDoc.setField(SolrFields.ID, doc.getFieldValue(SolrFields.ID));
        solrInDoc.setField(SolrFields.CRAWL_DATE, doc.getFieldValue(SolrFields.CRAWL_DATE));
        solrInDoc.setField(SolrFields.SOLR_URL, doc.getFieldValue(SolrFields.SOLR_URL));
        String uriString = (String) solrInDoc.getFieldValue(SolrFields.SOLR_URL);
        URI uri = new URI(uriString);
        // Update all of those records with the applicable
        // categories etc.
        anr.applyAnnotations(uri, solrInDoc);
        solr.add(solrInDoc);// ww w  .j a  v a 2 s  .c om
    }
}

From source file:uk.bl.wa.annotation.CollectionsUpdateTest.java

License:Open Source License

public static void doQuery(SolrClient ss, String id) throws SolrServerException, IOException {
    SolrParams p = new SolrQuery("id:\"" + id + "\"");
    QueryResponse r = ss.query(p);
    System.out.println("GOT collection " + r.getResults().get(0).getFieldValue("collection"));
    System.out.println("GOT collections " + r.getResults().get(0).getFieldValue("collections"));
    System.out.println("STILL GOT crawl_date " + r.getResults().get(0).getFieldValue("crawl_date"));
}