我正在将lightcouch用于我的spring boot应用程序,并且我需要能够基于提供的过滤器在CouchDb数据库中查询文档。由于这些过滤器始终可以不同,因此无法使用预设视图。我正在寻找一种可以像下面正常查找一样工作的东西:
public List<MyEntity> getEntities(MyFilter myFilter)
{
return dbClient.find(resourceFilter, MyEntity.class);
}
myFilter将是一个Map对象,我将根据该地图中提供的某些值来查询文档。可能吗?有没有实现我想要的方法?谢谢
答案 0 :(得分:1)
LightCouch
内部API允许用户定义的原始HTTP请求针对数据库执行。这可以通过CouchDbClient#executeRequest方法来完成。
我不在Java项目中使用LightCouch
,而是将Apache HTTPClient和GSON一起使用。以下示例假定您的本地计算机上安装了CouchDB
,并且用户名和密码均为“ admin”。可以很容易地使用CouchDbClient#executeRequest
。
mangoSelector
方法中的find
参数必须符合CouchDB selector syntax。
public class CouchDBAccess {
private static final String BASE_URL = "http://localhost:5984/";
private static final Gson GSON = new GsonBuilder().create();
private final Header[] httpHeaders;
public CouchDBAccess() {
this.httpHeaders = new Header[] { //
new BasicHeader("Accept", "application/json"), //
new BasicHeader("Content-type", "application/json"), //
new BasicHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("admin:admin".getBytes())) //
};
}
FindResult find(String dbName, String mangoSelector) throws IOException {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpPost httpPost = new HttpPost(BASE_URL + dbName + "/_find");
httpPost.setHeaders(httpHeaders);
httpPost.setEntity(new StringEntity(mangoSelector, ContentType.APPLICATION_JSON));
HttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
return GSON.fromJson(extractContent(response), FindResult.class);
} else {
// handle invalid response
}
}
}
private String extractContent(HttpResponse response) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(response.getEntity().getContent(), writer, defaultCharset());
return writer.toString();
}
}
class FindResult {
MyEntity[] docs;
}
相应的jUnit测试方法如下所示:
@Test
public void testFind() throws IOException {
String mangoSelector = "{\"selector\": {\"Host\": \"local drive\"}}";
FindResult findResult = couchDBAccess.find("data_1", mangoSelector);
assertEquals(100, findResult.docs.length); // or whatever you expect
}
答案 1 :(得分:1)
LightCouch提供了使用芒果选择器查询CouchDB的方法。
/**
* Find documents using a declarative JSON querying syntax.
* @param <T> The class type.
* @param jsonQuery The JSON query string.
* @param classOfT The class of type T.
* @return The result of the query as a {@code List<T> }
* @throws CouchDbException If the query failed to execute or the request is invalid.
*/
public <T> List<T> findDocs(String jsonQuery, Class<T> classOfT) { ...