如何在 Android 的 Couchbase-lite 中实现 "WHERE" 条件

How to implement "WHERE" condition in Couchbase-lite in Android

我想查找特定键具有相同给定值的所有文档。在 SQL 中,这可以使用 WHERE 子句来实现。在 Mongo 中,我可以使用 find()。但我不确定如何在 Android 的 Couchbase-lite 中实现它。如果有人可以帮助解决这个问题,那就太好了。谢谢你。

Couchbase Lite 不使用查询语言;它使用 map/reduce。听起来好像您以前没有遇到过。我们有关于 how map/reduce views work 以及如何查询它们的文档。

CouchbaseLite 基于 Map/Reduce 的概念。你必须在你的数据库上定义一个 View,然后设置它的 Map 函数,它将 运行 遍历数据库中的每个文档并为所需的查询创建索引。例如:

View userView= database.getView("User");
userView.setMap(new Mapper() {
    @Override
    public void map(Map<String, Object> document, Emitter emitter) {
        // Your Logic here
        String Id = document.get("Id").toString();
        if (Id != null && Id.contains("John")) {
            emitter.emit(Id, document);
        }
    }
}, "1");
Query query = userView.createQuery();
QueryEnumerator result = query.run();
for (Iterator<QueryRow> it = result; it.hasNext(); ) {
    QueryRow row = it.next();
    Log.e("myDocument", row.getDocument().toString())
}

不幸的是,CouchbaseLite 尚不支持 N1QL,但我已在他们未来的路线图上看到它。

这就是我解决问题的方法。

创建和初始化视图的代码:

com.couchbase.lite.View dateTimeView = database.getView("dateTimeView");
dateTimeView.setMap(new Mapper() {
    @Override
    public void map(Map<String, Object> document, Emitter emitter) {
        String dateTime = (String) document.get(QuickstartPreferences.DATE_TIME); // String for Key
        emitter.emit(dateTime, null);        
    }
}, "1");

上述视图查询代码:

Query query = database.getView("dateTimeView").createQuery();
query.setLimit(100);
query.setStartKey(date_time); //to retreive records for a given date_time value
query.setEndKey(date_time); 
QueryEnumerator result = null;
try {
    result = query.run();    
    for (Iterator<QueryRow> it = result; it.hasNext(); ) {
        QueryRow row = it.next();
        <String, Object> map = row.getDocument().getProperties();
        String employeeName = map.get(QuickstartPreferences.EMPLOYEE_NAME).toString(); // String for Key
        if(employeeName.equalsIgnoreCase(employee_name)) {
            // other logic
        }
    }
} catch (CouchbaseLiteException e) {
    e.printStackTrace();
}

这里的重点是当你为视图设置Map时,查询字段的值必须设置为Key(而不是Value)。 value 可能是 null。然后,您可以轻松使用 setStartKey & setEndKey 函数。

理解 map reduce 的一件重要事情是 map 和 reduce 都不是编写 where 子句的正确位置。

只有View不存在才会调用map函数。因此,当由于数据同步或用户操作而导致数据发生变化时,它会被调用。将某些文档 属性 与用户在 map 函数中传递的值进行比较是根本错误的。

正确的方法是将 map 用作 select 子句,仅具有独立于值的过滤(如果有)。之后,当我们从视图接收到查询对象时,我们可以执行基于值的检查。