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);
}
}
Aggregations