Search in sources :

Example 1 with QueryResult

use of com.cloudant.client.api.query.QueryResult in project java-cloudant by cloudant.

the class Database method query.

/**
 * <p>
 *     Query documents using an index and a query selector.
 * </p>
 * <p>
 *     Note: the most convenient way to generate query selectors is using a
 *     {@link com.cloudant.client.api.query.QueryBuilder}.
 * </p>
 * <p>
 *     Example usage to return the name and year of movies starring Alec Guinness since 1960
 *     with the results sorted by year descending:
 * </p>
 * <pre>
 * {@code
 * QueryResult<Movie> movies = db.query(new QueryBuilder(and(
 *   gt("Movie_year", 1960),
 *   eq("Person_name", "Alec Guinness"))).
 *   sort(Sort.desc("Movie_year")).
 *   fields("Movie_name", "Movie_year").
 *   build(), Movie.class);
 * }
 * </pre>
 * @param query    String representation of a JSON object describing criteria used to
 *                 select documents.
 * @param classOfT The class of Java objects to be returned in the {@code docs} field of result.
 * @param <T>      The type of the Java object to be returned in the {@code docs} field of result.
 * @return         A {@link QueryResult} object, containing the documents matching the query
 *                 in the {@code docs} field.
 * @see com.cloudant.client.api.query.QueryBuilder
 * @see <a
 * href="https://console.bluemix.net/docs/services/Cloudant/api/cloudant_query.html#selector-syntax"
 * target="_blank">selector syntax</a>
 */
public <T> QueryResult<T> query(String query, final Class<T> classOfT) {
    URI uri = new DatabaseURIHelper(db.getDBUri()).path("_find").build();
    InputStream stream = null;
    try {
        stream = client.couchDbClient.executeToInputStream(createPost(uri, query, "application/json"));
        Reader reader = new InputStreamReader(stream, "UTF-8");
        Type type = TypeToken.getParameterized(QueryResult.class, classOfT).getType();
        QueryResult<T> result = client.getGson().fromJson(reader, type);
        return result;
    } catch (UnsupportedEncodingException e) {
        // to support UTF-8.
        throw new RuntimeException(e);
    } finally {
        close(stream);
    }
}
Also used : Type(java.lang.reflect.Type) QueryResult(com.cloudant.client.api.query.QueryResult) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) DatabaseURIHelper(com.cloudant.client.internal.DatabaseURIHelper) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) UnsupportedEncodingException(java.io.UnsupportedEncodingException) URI(java.net.URI)

Aggregations

QueryResult (com.cloudant.client.api.query.QueryResult)1 DatabaseURIHelper (com.cloudant.client.internal.DatabaseURIHelper)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Type (java.lang.reflect.Type)1 URI (java.net.URI)1