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, METHOD method) throws SolrServerException, IOException 

Source Link

Document

Performs a query to the Solr server

Usage

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

public static <T extends Serializable> IndexResult<T> find(SolrClient index, Class<T> classToRetrieve,
        Filter filter, Sorter sorter, Sublist sublist, Facets facets)
        throws GenericException, RequestNotValidException {
    IndexResult<T> ret;//  www  .j a  v a  2s .  c om
    SolrQuery query = new SolrQuery();
    query.setQuery(parseFilter(filter));
    query.setSorts(parseSorter(sorter));
    query.setStart(sublist.getFirstElementIndex());
    query.setRows(sublist.getMaximumElementCount());
    parseAndConfigureFacets(facets, query);

    try {
        QueryResponse response = index.query(getIndexName(classToRetrieve), query);
        ret = queryResponseToIndexResult(response, classToRetrieve, facets);
    } catch (SolrServerException | IOException
            | org.apache.solr.client.solrj.impl.HttpSolrClient.RemoteSolrException e) {
        String message = e.getMessage();
        String bodytag = "<body>";
        if (message != null && message.contains(bodytag)) {
            message = message.substring(message.indexOf(bodytag) + bodytag.length(),
                    message.indexOf("</body>"));
            message = message.replaceAll("\\<[^>]*?>", "");
        }
        throw new GenericException("Could not query index, message: " + message, e);
    }

    return ret;
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

public static <T extends Serializable> IndexResult<T> find(SolrClient index, Class<T> classToRetrieve,
        Filter filter, Sorter sorter, Sublist sublist, Facets facets, RodaUser user, boolean showInactive)
        throws GenericException, RequestNotValidException {
    IndexResult<T> ret;//from   ww w  . j av a 2  s  . co m
    SolrQuery query = new SolrQuery();
    query.setQuery(parseFilter(filter));
    query.setSorts(parseSorter(sorter));
    query.setStart(sublist.getFirstElementIndex());
    query.setRows(sublist.getMaximumElementCount());
    parseAndConfigureFacets(facets, query);
    if (hasPermissionFilters(classToRetrieve)) {
        query.addFilterQuery(getFilterQueries(user, showInactive));
    }

    try {
        QueryResponse response = index.query(getIndexName(classToRetrieve), query);
        ret = queryResponseToIndexResult(response, classToRetrieve, facets);
    } catch (SolrServerException | IOException e) {
        throw new GenericException("Could not query index", e);
    }

    return ret;
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

public static <T extends Serializable> IndexResult<T> find(SolrClient index, Class<T> classToRetrieve,
        String tableUUID, Filter filter, Sorter sorter, Sublist sublist, Facets facets)
        throws GenericException, RequestNotValidException {
    IndexResult<T> ret;/*from w w w .  java 2 s.c  o m*/
    SolrQuery query = new SolrQuery();
    query.setQuery(parseFilter(filter));
    query.setSorts(parseSorter(sorter));
    query.setStart(sublist.getFirstElementIndex());
    query.setRows(sublist.getMaximumElementCount());

    parseAndConfigureFacets(facets, query);

    try {
        QueryResponse response = index.query(getTableCollectionName(tableUUID), query);
        ret = queryResponseToIndexResult(response, classToRetrieve, facets);
    } catch (SolrServerException | IOException e) {
        throw new GenericException("Could not query index", e);
    }

    return ret;
}

From source file:com.lucidworks.fusion.support.tests.DocumentLevelACP.java

public ArrayList<SolrDocument> run() {
    ArrayList<SolrDocument> list = new SolrDocumentList();
    try {//from   w  ww .  j  ava  2 s  . c om
        SolrClient client = getSolrClient();

        SolrQuery query = new SolrQuery();
        query.setQuery("*");
        query.setRows(10);

        QueryResponse resp = client.query(DEFAULT_COLLECTION, query);
        SolrDocumentList results = resp.getResults();
        SolrDocument doc;
        for (int i = 0; i < results.size(); ++i) {
            System.out.println(results.get(i));
            doc = results.get(i);
            if (hasACP(doc)) {
                list.add(doc);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return list;
}

From source file:net.yacy.cora.federate.solr.instance.ServerShard.java

License:Open Source License

/**
 * Performs a query to the Solr server/* ww w .  j a  v  a2s  .  co m*/
 * @param params  an object holding all key/value parameters to send along the request
 * @param method  specifies the HTTP method to use for the request, such as GET or POST
 * @throws IOException 
 */
@Override
public QueryResponse query(final SolrParams params, final METHOD method)
        throws SolrServerException, IOException {
    List<SolrClient> qs = this.shards.server4read();
    if (qs.size() == 1) {
        return qs.get(0).query(params, method);
    }

    final Collection<QueryResponse> qrl = new ConcurrentLinkedQueue<QueryResponse>();
    // concurrently call all shards
    List<Thread> t = new ArrayList<Thread>();
    for (final SolrClient s : qs) {
        Thread t0 = new Thread() {
            @Override
            public void run() {
                this.setName("ServerShard.query/2(" + params.toString() + ")");
                QueryResponse rsp;
                try {
                    rsp = s.query(params, method);
                } catch (final Throwable e) {
                    return;
                }
                qrl.add(rsp);
            }
        };
        t0.start();
        t.add(t0);
    }
    for (Thread t0 : t) {
        try {
            t0.join();
        } catch (final InterruptedException e) {
        }
    }

    // prepare combined response
    return ResponseAccumulator.combineResponses(qrl);
}

From source file:org.apache.ranger.solr.SolrUtil.java

License:Apache License

public QueryResponse runQuery(SolrClient solrClient, SolrQuery solrQuery) {
    if (solrQuery != null) {
        QueryResponse response;//ww  w .jav  a  2s  .  c  o m
        try {
            response = solrClient.query(solrQuery, METHOD.POST);
            return response;
        } catch (Throwable e) {
            logger.error("Error from Solr server.", e);
        }
    }
    return null;
}

From source file:org.codice.ddf.persistence.internal.PersistentStoreImpl.java

License:Open Source License

@Override
// Returned Map will have suffixes in the key names - client is responsible for handling them
public List<Map<String, Object>> get(String type, String cql) throws PersistenceException {
    if (StringUtils.isBlank(type)) {
        throw new PersistenceException(
                "The type of object(s) to retrieve must be non-null and not blank, e.g., notification, metacard, etc.");
    }/* ww  w  .j  a  v a  2s . co m*/

    List<Map<String, Object>> results = new ArrayList<>();

    // Set Solr Core name to type and create/connect to Solr Core
    SolrClient solrClient = getSolrClient(type);
    if (solrClient == null) {
        throw new PersistenceException("Unable to create Solr client.");
    }

    SolrQueryFilterVisitor visitor = new SolrQueryFilterVisitor(solrClient, type);

    try {
        SolrQuery solrQuery;
        // If not cql specified, then return all items
        if (StringUtils.isBlank(cql)) {
            solrQuery = new SolrQuery("*:*");
        } else {
            Filter filter = CQL.toFilter(cql);
            solrQuery = (SolrQuery) filter.accept(visitor, null);
        }
        QueryResponse solrResponse = solrClient.query(solrQuery, METHOD.POST);
        long numResults = solrResponse.getResults().getNumFound();
        LOGGER.debug("numResults = {}", numResults);

        SolrDocumentList docs = solrResponse.getResults();
        for (SolrDocument doc : docs) {
            PersistentItem result = new PersistentItem();
            Collection<String> fieldNames = doc.getFieldNames();
            for (String name : fieldNames) {
                LOGGER.debug("field name = {} has value = {}", name, doc.getFieldValue(name));
                if (name.endsWith(PersistentItem.TEXT_SUFFIX) && doc.getFieldValues(name).size() > 1) {
                    result.addProperty(name, doc.getFieldValues(name).stream().filter(s -> s instanceof String)
                            .map(s -> (String) s).collect(Collectors.toSet()));
                } else if (name.endsWith(PersistentItem.XML_SUFFIX)) {
                    result.addXmlProperty(name, (String) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.TEXT_SUFFIX)) {
                    result.addProperty(name, (String) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.LONG_SUFFIX)) {
                    result.addProperty(name, (Long) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.INT_SUFFIX)) {
                    result.addProperty(name, (Integer) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.DATE_SUFFIX)) {
                    result.addProperty(name, (Date) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.BINARY_SUFFIX)) {
                    result.addProperty(name, (byte[]) doc.getFirstValue(name));
                } else {
                    LOGGER.debug("Not adding field {} because it has invalid suffix", name);
                }
            }
            results.add(result);
        }
    } catch (CQLException e) {
        throw new PersistenceException("CQLException while getting Solr data with cql statement " + cql, e);
    } catch (SolrServerException | IOException e) {
        throw new PersistenceException("SolrServerException while getting Solr data with cql statement " + cql,
                e);
    }

    return results;
}

From source file:org.intermine.api.searchengine.solr.SolrKeywordSearchHandler.java

License:GNU General Public License

private QueryResponse performSearch(InterMineAPI im, String queryString, Map<String, String> facetValues,
        List<Integer> ids, int offSet, int rowSize) {

    SolrClient solrClient = SolrClientManager.getClientInstance(im.getObjectStore());

    QueryResponse resp = null;/*from  ww  w  .  j a  v a2  s . c o  m*/

    KeywordSearchPropertiesManager keywordSearchPropertiesManager = KeywordSearchPropertiesManager
            .getInstance(im.getObjectStore());

    Vector<KeywordSearchFacetData> facets = keywordSearchPropertiesManager.getFacets();

    Map<ClassDescriptor, Float> classBoost = keywordSearchPropertiesManager.getClassBoost();

    List<String> fieldNames = getFieldNamesFromSolrSchema(solrClient);

    try {

        SolrQuery newQuery = new SolrQuery();
        newQuery.setQuery(queryString);
        newQuery.setStart(offSet);
        newQuery.setRows(rowSize);
        newQuery.addField("score");
        newQuery.addField("id");
        newQuery.add("defType", "edismax");

        for (KeywordSearchFacetData keywordSearchFacetData : facets) {
            newQuery.addFacetField("facet_" + keywordSearchFacetData.getField());
        }

        // add faceting selections
        for (Map.Entry<String, String> facetValue : facetValues.entrySet()) {
            if (facetValue != null) {
                newQuery.addFilterQuery(facetValue.getKey() + ":" + facetValue.getValue());
            }
        }

        //limiting the query based on search bag
        if (ids != null && !ids.isEmpty()) {
            for (int id : ids) {
                newQuery.addFilterQuery("id", Integer.toString(id));
            }
        }

        String boostQuery = "";

        for (Map.Entry<ClassDescriptor, Float> boostValue : classBoost.entrySet()) {
            if (boostValue != null) {
                boostQuery += "classname:" + boostValue.getKey().getUnqualifiedName() + "^"
                        + boostValue.getValue() + " ";
            }
        }

        LOG.info("BoostQuery : " + boostQuery);

        String fieldListQuery = "";

        for (String field : fieldNames) {
            fieldListQuery = fieldListQuery + field;
            if (field.endsWith("_raw")) {
                fieldListQuery = fieldListQuery + "^2.0";
            }
            fieldListQuery = fieldListQuery + " ";
        }

        LOG.info("Field List Query : " + fieldListQuery);

        newQuery.add("bq", boostQuery);
        newQuery.add("qf", fieldListQuery);

        resp = solrClient.query(newQuery, SolrRequest.METHOD.POST);

        return resp;

    } catch (SolrServerException e) {
        LOG.error("Query performed on solr failed for search term : " + queryString, e);
        e.printStackTrace();

    } catch (IOException e) {
        LOG.error("Query performed on solr failed for search term : " + queryString, e);
        e.printStackTrace();

    }

    return resp;
}

From source file:org.mousephenotype.cda.solr.service.SolrIndex.java

License:Apache License

public List<String> fetchQueryIdsFromChrRange(String chr, String chrStart, String chrEnd, String mode)
        throws IOException, SolrServerException {
    List<String> queryIds = new ArrayList<>();

    SolrClient server = null;
    server = getSolrServer("gene");

    SolrQuery query = new SolrQuery();
    query.setQuery("*:*");
    query.setFilterQueries("seq_region_id:" + chr + " AND seq_region_start:[" + chrStart + " TO " + chrEnd + "]"
            + " AND seq_region_end:[" + chrStart + " TO " + chrEnd + "]");
    query.setFields("mgi_accession_id");

    System.out.println("Query: " + query);
    QueryResponse response = null;//from  www. j a  v  a  2 s. c om
    if (!mode.equals("export")) {
        query.setRows(10); // default, display only a max of 10 records on batchQuery page
        response = server.query(query, METHOD.POST);
    } else {
        query.setRows(0);
        response = server.query(query, METHOD.POST);
        int rows = (int) response.getResults().getNumFound(); // need to figure out how many docs found for full export
        query.setRows(rows); // default
        response = server.query(query, METHOD.POST);
    }

    System.out.println("Found " + response.getResults().getNumFound() + " gene(s) in range");
    for (SolrDocument doc : response.getResults()) {
        queryIds.add(doc.get("mgi_accession_id").toString());
    }
    return queryIds;
}

From source file:org.mousephenotype.cda.solr.service.SolrIndex.java

License:Apache License

public QueryResponse getBatchQueryJson(String idlist, String fllist, String dataTypeName)
        throws SolrServerException, IOException {

    SolrClient server = null;

    Map<String, String> coreIdQMap = coreIdQMap();
    String qField = coreIdQMap.get(dataTypeName);

    if (dataTypeName.equals("disease")) {
        server = getSolrServer("disease"); // points to new phenodigm
    }/* ww  w .  j  a  v  a2 s. co m*/
    if (dataTypeName.equals("hp")) {
        server = getSolrServer("mp");
    } else if (dataTypeName.equals("ensembl") || dataTypeName.contains("marker_symbol")) {
        server = getSolrServer("gene");
    } else {
        server = getSolrServer(dataTypeName);
    }

    String[] idList = StringUtils.split(idlist, ",");
    String querystr = null;

    // search keyword by mouse symbol: check 2 fields in gene core (marker_symbol_lowercase, marker_synonym_lowercase)
    if (dataTypeName.equals("mouse_marker_symbol")) {
        querystr = "marker_symbol_lowercase:(" + StringUtils.join(idList, " OR ") + ")"
                + " OR marker_synonym_lowercase:(" + StringUtils.join(idList, " OR ") + ")";
    }
    // search keyword by human symbol: check 2 fields in gene core (human_gene_symbol_lowercase, human_symbol_synonym_lowercase)
    else if (dataTypeName.equals("human_marker_symbol")) {
        querystr = "human_gene_symbol_lowercase:(" + StringUtils.join(idList, " OR ") + ")"
                + " OR human_symbol_synonym_lowercase:(" + StringUtils.join(idList, " OR ") + ")";
    } else {
        querystr = qField + ":(" + StringUtils.join(idList, " OR ") + ")";
    }

    //System.out.println("BatchQuery: " + querystr);
    SolrQuery query = new SolrQuery();
    query.setQuery(querystr);

    if (dataTypeName.equals("disease")) { // points to phenodigm
        //query.setFilterQueries("type:hp_mp");
        query.setFilterQueries("type:disease_gene_summary");
    }

    query.setStart(0);

    query.setRows(0);

    QueryResponse response = server.query(query, METHOD.POST);
    long rowCount = response.getResults().getNumFound(); // so that we know how many rows is returned

    //      System.out.println("row count: "+rowCount);
    //query.setRows(idList.length);  // default
    query.setRows((int) rowCount);

    // retrieves wanted fields
    query.setFields(fllist);
    System.out.println("BATCHQUERY " + dataTypeName + " : " + query);

    QueryResponse response2 = server.query(query, METHOD.POST);
    //System.out.println("response: "+ response2);

    return response2;
}