首页 > 解决方案 > 可以使用 Lightcouch 按过滤器查询文档吗?

问题描述

我将 lightcouch 用于我的 spring boot 应用程序,并且我需要能够根据提供的过滤器查询我的 CouchDb 数据库中的文档。由于这些过滤器总是不同的,我不能使用预设视图。我正在寻找可以以与正常查找类似的方式工作的东西,如下所示:

public List<MyEntity> getEntities(MyFilter myFilter)
{
   return dbClient.find(resourceFilter, MyEntity.class);
}

myFilter 将是一个 Map 对象,我将使用它来根据此地图中提供的某些值查询文档。可能吗?有没有办法实现我想要的?谢谢

标签: javaspring-bootcouchdb

解决方案


LightCouch内部 API 允许对数据库执行用户定义的原始 HTTP 请求。这可以通过 CouchDbClient#executeRequest方法来完成。

我没有LightCouch在我的 Java 项目中使用,而是在Apache HTTPClientGSON中使用。下面的示例假设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
}

推荐阅读