java - 可以使用 Lightcouch 按过滤器查询文档吗?
问题描述
我将 lightcouch 用于我的 spring boot 应用程序,并且我需要能够根据提供的过滤器查询我的 CouchDb 数据库中的文档。由于这些过滤器总是不同的,我不能使用预设视图。我正在寻找可以以与正常查找类似的方式工作的东西,如下所示:
public List<MyEntity> getEntities(MyFilter myFilter)
{
return dbClient.find(resourceFilter, MyEntity.class);
}
myFilter 将是一个 Map 对象,我将使用它来根据此地图中提供的某些值查询文档。可能吗?有没有办法实现我想要的?谢谢
解决方案
LightCouch
内部 API 允许对数据库执行用户定义的原始 HTTP 请求。这可以通过 CouchDbClient#executeRequest方法来完成。
我没有LightCouch
在我的 Java 项目中使用,而是在Apache HTTPClient和GSON中使用。下面的示例假设CouchDB
安装在您的本地计算机上,并且用户和密码都是“admin”。它可以很容易地适应使用CouchDbClient#executeRequest
。
方法中的mangoSelector
参数find
必须符合CouchDB 选择器语法。
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
}
推荐阅读
- javascript - 在 JS 中突出显示纯 html
- mysql - MySQL 在日期之间搜索,但也在时间范围之间搜索
- javascript - 使用 requestAnimationFrame 而不是 setInterval
- php - 如何更改和抑制 JSON 结果中的某些字段键名?
- postgresql - 如何完全删除postgres?
- ios - 从 SWIFT 4.1 中的 Firebase 检索数据时,“下标”的模糊使用和无法调用非函数类型“AnyObject”的值错误
- python - 对于在文本中搜索单词的快速 python 包有什么建议吗?
- crystal-reports - Crystal Reports:两个表并排,来自一个查询 BEx
- rest - 如何让 PowerBI 使用受访问令牌保护的我的 RESTful 服务?
- twitter-bootstrap - 电话上的引导网格系统意外结果