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

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

Introduction

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

Prototype

public ModifiableSolrParams set(String name, String... val) 

Source Link

Document

Replace any existing parameter with the given name.

Usage

From source file:org.springframework.data.solr.core.QueryParserBase.java

License:Apache License

/**
 * Set {@code q.op} parameter for {@link SolrQuery}
 * //from   w  w w .j av a 2s . c  om
 * @param solrQuery
 * @param defaultOperator
 */
protected void appendDefaultOperator(SolrQuery solrQuery, Operator defaultOperator) {
    if (defaultOperator != null && !Query.Operator.NONE.equals(defaultOperator)) {
        solrQuery.set("q.op", defaultOperator.asQueryStringRepresentation());
    }
}

From source file:org.swissbib.sru.targets.solr.SOLRQueryTransformation.java

License:Open Source License

@Override
public QueryResponse runQuery() throws Exception {

    QueryResponse response = null;//from ww  w .j  av  a  2s  .co  m

    try {

        if (null == cqlNode) {
            throw new SRUException("no cqlNode -> target not initialized",
                    "no cqlNode -> target not initialized");
        }

        StringBuffer luceneStringQuery = new StringBuffer();
        makeLuceneQuery(cqlNode, luceneStringQuery);

        SolrQuery parameters = new SolrQuery();
        parameters.set("q", luceneStringQuery.toString());

        String sR = inputParams.getFirstValue("startRecord");
        int startRecord = 0;

        try {
            startRecord = sR != null && sR.length() > 0 ? Integer.parseInt(sR) : 0;
            startRecord = startRecord == 1 ? 0 : startRecord;
        } catch (Exception ex) {

            System.out.println("invalid start parameter -> use 0 as default");
        }

        //for backward compatibility - was 1 in the former version

        String rows = inputParams.getFirstValue("maximumRecords");
        int maxRows = 10;
        try {
            maxRows = rows != null && rows.length() > 0 ? Integer.parseInt(rows) : 0;
        } catch (Exception ex) {

            System.out.println("invalid rows parameter -> use 10 as default");
        }

        parameters.set("start", startRecord);
        parameters.set("rows", maxRows);

        if (this.generalFilterQuery != null) {

            //SOLR needs this df parameter on the local as well as on the general level
            //grr - SOLR syntax...
            parameters.set("df", "title_short");
            parameters.set("fq", this.generalFilterQuery);

        }

        //seems that edismax needs a default query field
        //todo: have a closer look into the pre condition
        //parameters.set("df","title_short") ; //should be a default field if no one is defined in the configuration of the server

        //this.searchServer.setParser(new BinaryResponseParser());
        //this.searchServer.setRequestWriter(new BinaryRequestWriter());

        response = this.searchServer.query(parameters);

    } catch (SRUException sruException) {
        throw sruException;

    } catch (Exception excep) {

        SRUException sruex = new SRUException("undefined details", "undefined message", excep);
        sruex.setUseExceptionMessage(true);
        throw sruex;

    } catch (Throwable throwable) {

        SRUException sruex = new SRUException("undefined details", "undefined message", throwable);
        sruex.setUseExceptionMessage(true);
        throw sruex;
    }

    return response;
}

From source file:org.topicquests.solr.Solr3Client.java

License:Apache License

/**
 * Run a query based on <code>queryString</code>
 * @param queryString//from   w  w  w.  ja  va 2s. c  o  m
 * @param start TODO
 * @param count TODO
 * @return  NamedList<Object> in result or error string
 */
public IResult runQuery(String queryString, int start, int count) {
    System.out.println("Solr3Client.runQuery- " + queryString + " " + start + " " + count);
    IResult result = new ResultPojo();
    SolrQuery parameters = new SolrQuery();
    parameters.set("q", queryString);
    parameters.setStart(start);
    if (count > -1)
        parameters.setRows(count);
    //force result as JSON
    //      parameters.set("wt", "json");
    System.out.println("Solr3Client.runQuery-1 " + parameters.toString());
    try {
        QueryResponse x = server.query(parameters);
        System.out.println("ZZZZ " + x.getResults());
        result.setResultObject(x.getResults());
    } catch (Exception e) {
        log.logError("SolrClient3.runQuery " + e.getMessage() + " " + queryString, e);
        result.addErrorString(e.getMessage());
    }
    return result;
}

From source file:org.topicquests.solr.Solr4Client.java

License:Apache License

/**
 * Run a query based on <code>queryString</code>
 * @param queryString//  w w w  . j ava 2  s.  c o  m
 * @param start TODO
 * @param count TODO
 * @return  NamedList<Object> in result or error string
 */
public IResult runQuery(String queryString, int start, int count) {
    System.out.println("Solr4Client.runQuery- " + queryString + " " + start + " " + count);
    IResult result = new ResultPojo();
    SolrQuery parameters = new SolrQuery();
    parameters.set("q", queryString);
    parameters.setStart(start);
    if (count > -1)
        parameters.setRows(count);
    //force result as JSON
    //      parameters.set("wt", "json");
    System.out.println("Solr4Client.runQuery-1 " + parameters.toString());
    try {
        QueryResponse x = server.query(parameters);
        //         System.out.println("Solr3Client.runQuery "+x.getStatus());
        //         System.out.println("XXXX "+x.getHeader());
        //         System.out.println("YYYY "+x.getResponse());
        System.out.println("ZZZZ " + x.getResults());
        result.setResultObject(x.getResults());
    } catch (Exception e) {
        //TODO log the error
        e.printStackTrace();
        result.addErrorString(e.getMessage());
    }
    return result;
}

From source file:org.topicquests.solr.SolrCloudClient.java

License:Apache License

/**
 * Run a query based on <code>queryString</code>
 * @param queryString//  w w  w.ja v  a2 s.  c o  m
 * @param start TODO
 * @param count TODO
 * @return  NamedList<Object> in result or error string
 */
public IResult runQuery(String queryString, int start, int count) {
    log.logDebug("SolrCloudClient.runQuery- " + queryString + " " + start + " " + count);
    IResult result = new ResultPojo();
    SolrQuery parameters = new SolrQuery();
    parameters.set("q", queryString);
    parameters.setStart(start);
    if (count > -1)
        parameters.setRows(count);
    log.logDebug("SolrCloudClient.runQuery-1 " + parameters.toString());
    try {
        QueryResponse x = server.query(parameters);
        log.logDebug("SolrCloudClient.runQuery-2 " + x.getResults());
        result.setResultObject(x.getResults());
    } catch (Exception e) {
        log.logError("SolrCloudClient.runQuery " + e.getMessage() + " " + queryString, e);
        result.addErrorString(e.getMessage());
    }
    return result;
}

From source file:org.vootoo.client.netty.NettySolrClientTest.java

License:Apache License

@Test
public void test_netty_client_query() {
    String id = createDocId();//from w w w.  j  a  v a 2s . c  om
    SolrQuery solrQuery = new SolrQuery("*:*");
    solrQuery.set(RequestParams.WriteResponseId, id);

    try {
        QueryResponse query = solrClient.query(solrQuery);
        //System.out.println(query);
        Assert.assertEquals("GET", query.getResponseHeader().get("METHOD"));
        assertIdResult(query, id);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}

From source file:org.vootoo.server.netty.SolrServerHandlerTest.java

License:Apache License

protected SolrQuery createIdQuery(String id) {
    SolrQuery query = new SolrQuery("id:\"" + id + "\"");
    query.set("_timeout_", 1000);
    query.set("indent", "on");
    return query;
}

From source file:org.vroyer.hive.solr.SolrTableCursor.java

License:Open Source License

private void fetchNextDocumentChunk() throws IOException {
    SolrQuery query = new SolrQuery();
    query.setStart(start);/*w w  w  .jav a2s . com*/

    if (table.facetType == null) {
        query.setRows(Math.min(count, this.solrSplitSize));
        for (String s : table.fields) {
            // Don't push solr_query, this is an internal column when a cassandra table is indexed by SOLR.
            if (!s.equalsIgnoreCase("solr_query")) {
                query.addField(s);
            }
        }
    } else {
        query.setRows(0);
    }

    List<NameValuePair> params = URLEncodedUtils.parse(table.qs, Charset.forName("UTF-8"));
    for (NameValuePair nvp : params) {
        query.set(nvp.getName(), nvp.getValue());
    }
    if (table.fq.length() > 0) {
        query.set("fq", table.fq.toString());
    }
    if (table.q.length() > 0) {
        query.set("q", table.q.toString());
    }
    if (query.get("q") == null) {
        query.set("q", "*:*");
    }

    if (log.isInfoEnabled()) {
        StringBuffer sb = new StringBuffer("");
        Map<String, String[]> map = query.toMultiMap(query.toNamedList());
        for (String s : map.keySet()) {
            sb.append(s).append('=').append(Arrays.toString(map.get(s))).append(' ');
        }
        log.info("SOLR request: " + sb.toString());
    }

    checkRequiredFilterFields();

    QueryResponse response;
    try {
        response = server.query(query);
    } catch (SolrServerException e) {
        throw new IOException(e);
    }

    if (table.facetType != null) {
        if (table.facetType.equalsIgnoreCase("ranges")) {
            List<RangeFacet.Count> counts = response.getFacetRanges().get(0).getCounts();
            for (RangeFacet.Count rfc : counts) {
                facets.add(new FacetEntry(rfc.getValue(), rfc.getCount()));
            }
        } else if (table.facetType.equalsIgnoreCase("fields")) {
            List<FacetField.Count> counts = response.getFacetFields().get(0).getValues();
            for (FacetField.Count rfc : counts) {
                facets.add(new FacetEntry(rfc.getName(), rfc.getCount()));
            }
        } else if (table.facetType.equalsIgnoreCase("queries")) {
            Map<String, Integer> queries = response.getFacetQuery();
            for (String k : queries.keySet()) {
                facets.add(new FacetEntry(k, queries.get(k)));
            }
        }
    } else {
        buffer = response.getResults();
        numFound = buffer.getNumFound();
        log.info("SOLR response numFound=" + buffer.getNumFound());
        start += buffer.size();
        count -= buffer.size();
    }
    pos = 0;
}

From source file:org.xwiki.query.solr.internal.SolrQueryExecutor.java

License:Open Source License

@Override
public <T> List<T> execute(Query query) throws QueryException {
    try {// w  ww  .j av  a  2 s.  c o  m
        SolrInstance solrInstance = solrInstanceProvider.get();

        SolrQuery solrQuery = new SolrQuery(query.getStatement());

        // Overwrite offset and limit only if the query object explicitly says so, otherwise use whatever the query
        // statement says or the defaults
        if (query.getOffset() > 0) {
            solrQuery.setStart(query.getOffset());
        }
        if (query.getLimit() > 0) {
            solrQuery.setRows(query.getLimit());
        }

        // TODO: good idea? Any confusion? Do we really needs something like this?
        // Reuse the Query.getNamedParameters() map to get extra parameters.
        for (Entry<String, Object> entry : query.getNamedParameters().entrySet()) {
            Object value = entry.getValue();

            if (value instanceof Iterable) {
                solrQuery.set(entry.getKey(), toStringArray((Iterable) value));
            } else if (value != null && value.getClass().isArray()) {
                solrQuery.set(entry.getKey(), toStringArray(value));
            } else {
                solrQuery.set(entry.getKey(), String.valueOf(value));
            }
        }

        QueryResponse response = solrInstance.query(solrQuery);

        // Check access rights need to be checked before returning the response.
        // FIXME: this is not really the best way, mostly because at this point all grouping operations
        // have already been performed and any change on the result will not ensure that the grouping
        // information (facets, highlighting, maxScore, etc.) is still relevant.
        // A better way would be using a PostFilter as described in this article:
        // http://java.dzone.com/articles/custom-security-filtering-solr
        // Basically, we would be asking
        this.filterResponse(response);

        return (List<T>) Arrays.asList(response);
    } catch (Exception e) {
        throw new QueryException("Exception while executing query", query, e);
    }
}

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
 * /*  w  w  w.jav a2 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;
    }

}