Example usage for org.apache.solr.client.solrj SolrQuery setQuery

List of usage examples for org.apache.solr.client.solrj SolrQuery setQuery

Introduction

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

Prototype

public SolrQuery setQuery(String query) 

Source Link

Usage

From source file:cz.incad.kramerius.k5indexer.Server.java

public SolrDocumentList getDocs(String query) throws SolrServerException {
    SolrQuery squery = new SolrQuery();
    squery.setQuery(query);
    squery.addSort("price", SolrQuery.ORDER.asc);
    QueryResponse rsp = server.query(squery);
    return rsp.getResults();
}

From source file:cz.incad.vdk.client.tools.Search.java

License:Open Source License

public String getAsXML() throws JSONException {

    try {/*from w  w w . ja va 2 s  . co  m*/

        String q = req.getParameter("q");
        SolrQuery query = new SolrQuery();
        if (q == null || q.equals("")) {
            q = "*:*";
            query.setSort("_version_", SolrQuery.ORDER.desc);
        }
        query.setQuery(q);
        query.set("q.op", "AND");
        query.setFacet(true);
        query.setStart(getStart());
        query.setRows(getRows());

        if (LoggedController.isLogged(req)) {
            query.addFacetField(opts.getStrings("user_facets"));
        }
        query.addFacetField(opts.getStrings("facets"));

        query.setFacetMinCount(1);

        JSONObject others = opts.getJSONObject("otherParams");
        Iterator keys = others.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            Object val = others.get(key);
            if (val instanceof Integer) {
                query.set(key, (Integer) val);
            } else if (val instanceof String) {
                query.set(key, (String) val);
            } else if (val instanceof Boolean) {
                query.set(key, (Boolean) val);
            }

        }
        addFilters(query);

        return IndexerQuery.xml(query);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

License:Open Source License

public void removeAllWanted() throws Exception {
    SolrQuery query = new SolrQuery("chci:[* TO *]");
    query.addField("code");
    SolrDocumentList docs = IndexerQuery.query(query);
    long numFound = docs.getNumFound();
    Iterator<SolrDocument> iter = docs.iterator();
    while (iter.hasNext()) {
        if (jobData.isInterrupted()) {
            LOGGER.log(Level.INFO, "INDEXER INTERRUPTED");
            break;
        }/*w  w  w .  j  av a2 s  .  com*/
        StringBuilder sb = new StringBuilder();

        SolrDocument resultDoc = iter.next();
        String docCode = (String) resultDoc.getFieldValue("code");
        sb.append("<add><doc>");
        sb.append("<field name=\"code\">").append(docCode).append("</field>");
        sb.append("<field name=\"md5\">").append(docCode).append("</field>");

        sb.append("<field name=\"chci\" update=\"set\" null=\"true\" />");
        sb.append("</doc></add>");
        SolrIndexerCommiter.postData(sb.toString());
        SolrIndexerCommiter.postData("<commit/>");
    }
    query.setQuery("nechci:[* TO *]");
    query.addField("code");
    docs = IndexerQuery.query(query);
    iter = docs.iterator();
    while (iter.hasNext()) {
        if (jobData.isInterrupted()) {
            LOGGER.log(Level.INFO, "INDEXER INTERRUPTED");
            break;
        }
        StringBuilder sb = new StringBuilder();

        SolrDocument resultDoc = iter.next();
        String docCode = (String) resultDoc.getFieldValue("code");
        sb.append("<add><doc>");
        sb.append("<field name=\"code\">").append(docCode).append("</field>");
        sb.append("<field name=\"md5\">").append(docCode).append("</field>");

        sb.append("<field name=\"nechci\" update=\"set\" null=\"true\" />");
        sb.append("</doc></add>");
        SolrIndexerCommiter.postData(sb.toString());
        SolrIndexerCommiter.postData("<commit/>");
    }

    numFound += docs.getNumFound();
    if (numFound > 0 && !jobData.isInterrupted()) {
        removeAllWanted();
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.indexing.AutocompleteIndexer.java

License:Apache License

/**
 * Transforms the searched phrase to a Solr document.
 * @param phrase The input searched phrase.
 * @return The Solr document representing the searched phrase.
 * @throws IllegalAccessException//from   w w w .ja va  2 s .c om
 * @throws IOException
 * @throws SolrServerException
 */
@Override
public SolrInputDocument prepareForIndexing(String phrase)
        throws IllegalAccessException, IOException, SolrServerException {

    SolrInputDocument document = new SolrInputDocument();

    SolrQuery query = new SolrQuery();
    query.setFields(IndexField.AUTOCOMPLETE.getValue());

    query.setQuery("uuid:autocomplete#" + phrase);
    QueryResponse response = solrServer.query(query);

    int count;
    // the phrase is not indexed yet
    if (response.getResults().size() == 0) {
        count = 0;
    }
    // already indexed
    else {
        String foundPhrase = ((List<String>) response.getResults().get(0)
                .getFieldValue(IndexField.AUTOCOMPLETE.getValue())).get(0);
        int delimiterPosition = foundPhrase.lastIndexOf('#');
        // the phrase was originally retrieved by indexing a document
        if (delimiterPosition == -1) {
            count = 0;
        }
        // the phrase was indexed after performing a search query
        else {
            count = Integer
                    .valueOf(foundPhrase.substring(foundPhrase.lastIndexOf('#') + 1, foundPhrase.length()));
        }
        count++;
    }

    document.addField(IndexField.UUID.getValue(), "autocomplete#" + phrase);
    document.addField(IndexField.ID.getValue(), 0);
    document.addField(IndexField.AUTOCOMPLETE.getValue(), phrase + "#" + count);

    return document;
}

From source file:cz.zcu.kiv.eegdatabase.logic.search.FulltextSearchService.java

License:Apache License

/**
 * Configures the query to be processed.
 * @param inputQuery The query string./*from ww  w  .  j  a va 2  s .c o  m*/
 * @param start Index of the first returned result.
 * @param count Number of results we wish to display.
 * @return Configured query.
 */
private SolrQuery configureQuery(String inputQuery, ResultCategory category, int start, int count) {
    SolrQuery query = new SolrQuery();
    query.setQuery(inputQuery);
    if (category != null && !category.equals(ResultCategory.ALL)) {
        query.addFilterQuery(IndexField.CLASS.getValue() + ":\"" + category.getValue() + "\"");
    }
    query.setStart(start);
    query.setRows(count);
    query.setHighlightSimplePre(FullTextSearchUtils.HIGHLIGHTED_TEXT_BEGIN);
    query.setHighlightSimplePost(FullTextSearchUtils.HIGHLIGHTED_TEXT_END);
    return query;
}

From source file:cz.zcu.kiv.eegdatabase.logic.search.FulltextSearchService.java

License:Apache License

/**
 * Gets values to autocomplete for the input string.
 * The autocomplete feature works for multivalued fields and is based on a highlighting trick.
 * See http://solr.pl/en/2013/02/25/autocomplete-on-multivalued-fields-using-highlighting/
 * @param keywordStart// w  ww .  j av a 2 s  . c om
 * @return Autocomplete values.
 * @throws SolrServerException
 */
public Set<String> getTextToAutocomplete(String keywordStart) throws SolrServerException {
    SolrQuery query = new SolrQuery();
    query.setQuery(IndexField.AUTOCOMPLETE.getValue() + ":" + keywordStart);
    query.setFields(IndexField.AUTOCOMPLETE.getValue());
    query.setHighlight(true);
    query.setParam("hl.fl", IndexField.AUTOCOMPLETE.getValue());
    query.setHighlightSimplePre("");
    query.setHighlightSimplePost("");
    query.setRows(FullTextSearchUtils.AUTOCOMPLETE_ROWS);

    Map<String, Integer> map = new TreeMap<String, Integer>();
    QueryResponse response = solrServer.query(query);

    Set<String> foundIds = response.getHighlighting().keySet();
    for (String id : foundIds) {

        List<String> resultsPerDocument = response.getHighlighting().get(id)
                .get(IndexField.AUTOCOMPLETE.getValue());
        if (resultsPerDocument != null) {
            for (String result : resultsPerDocument) {
                String resultValue;
                int resultFrequency;
                int delimiterPosition = result.lastIndexOf('#');
                if (delimiterPosition == -1) { // autocomplete phrase was copied from title
                    resultValue = result;
                    resultFrequency = 0;
                } else {
                    resultValue = result.substring(0, delimiterPosition);
                    try {
                        resultFrequency = Integer
                                .valueOf(result.substring(delimiterPosition + 1, result.length()));
                    } catch (NumberFormatException e) {
                        resultFrequency = 0;
                    }
                }

                map.put(resultValue.toLowerCase(), resultFrequency);
            }
        }

        if (map.size() == FullTextSearchUtils.AUTOCOMPLETE_ROWS) {
            break;
        }
    }

    map = sortByValue(map);
    return map.keySet();
}

From source file:cz.zcu.kiv.eegdatabase.logic.search.FulltextSearchService.java

License:Apache License

/**
 * Gets the number of all documents matching the query.
 * @param queryString The query string.//w  ww  . j av  a2  s . c  o  m
 * @return The number of all documents matching the query.
 */
public int getTotalNumberOfDocumentsForQuery(String queryString, ResultCategory category) {
    SolrQuery q = new SolrQuery();
    q.setQuery(queryString);
    if (category != null && !category.equals(ResultCategory.ALL)) {
        q.setFilterQueries(IndexField.CLASS.getValue() + ":\"" + category.getValue() + "\"");
    }
    q.setRows(0); // don't actually request any data
    try {
        return (int) solrServer.query(q).getResults().getNumFound();
    } catch (SolrServerException e) {
        log.error(e);
        e.getCause().printStackTrace();
    }
    return 0;
}

From source file:datacite.oai.provider.service.MDSSearchServiceSolrImpl.java

License:Open Source License

@Override
public DatasetRecordBean getDatasetByID(String id) throws ServiceException {
    SolrQuery query = new SolrQuery();
    query.setQuery("dataset_id:" + id);

    try {//from   w  w  w .  ja  v a 2  s.co  m
        QueryResponse response = solrServer.query(query);
        if (response.getResults().isEmpty())
            return null;
        SolrDocument doc = response.getResults().get(0);
        return convertToRecord(doc);
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:datacite.oai.provider.service.MDSSearchServiceSolrImpl.java

License:Open Source License

static SolrQuery constructSolrQuery(Date updateDateFrom, Date updateDateTo, String setspec, int offset,
        int length) throws ServiceException {
    SolrQuery query = new SolrQuery();
    query.setQuery("*:*");
    query.setRows(length);//from   w  ww  . jav  a 2 s  . c o m
    query.setStart(offset);
    query.setSortField("updated", ORDER.asc);

    setspec = StringUtils.trimToEmpty(setspec);
    if (setspec.contains(Constants.Set.BASE64_PART_DELIMITER)) {
        String split[] = setspec.split(Constants.Set.BASE64_PART_DELIMITER, 2);
        setspec = split[0];
        String base64 = split[1];
        String solrfilter = new String(Base64.decodeBase64(base64));
        logger.info("decoded base64 setspec: " + solrfilter);
        solrfilter = solrfilter.replaceAll("^[?&]+", "");

        List<NameValuePair> params = URLEncodedUtils.parse(solrfilter, Charset.defaultCharset());
        for (NameValuePair param : params) {
            String name = param.getName();
            String value = param.getValue();
            if (name.equals("q"))
                query.setQuery(value);
            else if (name.equals("fq"))
                query.addFilterQuery(value);
            else
                throw new ServiceException("parameter '" + name + "' is not supported");
        }
    }

    if (setspec != null && setspec.trim().length() > 0) {
        setspec = setspec.trim().toUpperCase();

        String field = setspec.contains(".") ? "datacentre_symbol" : "allocator_symbol";
        query.addFilterQuery(field + ":" + setspec);
    }

    String from = dateFormat.format(updateDateFrom);
    String to = dateFormat.format(updateDateTo);

    query.addFilterQuery("updated:[" + from + " TO " + to + "]");

    query.setParam(CommonParams.QT, "/api");

    return query;
}

From source file:datacite.oai.provider.service.MDSSearchServiceSolrImpl.java

License:Open Source License

@Override
public Pair<List<SetRecordBean>, Integer> getSets() throws ServiceException {
    SolrQuery query = new SolrQuery();
    query.setQuery("*:*");
    query.setRows(0);//  w w w  . j a  va2 s.co m
    query.setFacet(true);
    query.setFacetLimit(-1);
    query.addFacetField("allocator_facet", "datacentre_facet");

    try {
        QueryResponse response = solrServer.query(query);

        SortedSet<String> facetValues = new TreeSet<String>();
        for (FacetField facet : response.getFacetFields()) {
            for (Count count : facet.getValues()) {
                facetValues.add(count.getName());
            }
        }

        ArrayList<SetRecordBean> sets = new ArrayList<SetRecordBean>();
        for (String facetValue : facetValues) {
            String[] parts = facetValue.split(" - ", 2);
            String symbol = parts[0];
            String name = parts[1];
            sets.add(new SetRecordBean(symbol, name));
        }

        return new Pair<List<SetRecordBean>, Integer>(sets, sets.size());

    } catch (Exception e) {
        throw new ServiceException(e);
    }

}