couchbase lite Android 客户端的 where 子句中的多个 and() 条件

Multiple and() conditions in where clause for couchbase lite Android client

在我的 Android 应用程序中,我们使用 couchbase lite 数据库版本 2.8.6

我运行三个数据库查询。

QueryBuilder.select(
    SelectResult.property("id"),
    SelectResult.property("timestamp"),
    SelectResult.property("rating"))
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string(DOC_TYPE)))

在结果中,我看到从数据库打印到控制台的三个项目。不出所料。下面的格式是 id|timestamp|rating

4e39f79c-9e11-4aba-9fb6-95d910f46cd9|0|-2147483648
e95646ee-ba3a-4978-b2a8-5383f31be2f1|0|-2147483648
e02d0eb3-6c9b-4942-b43c-a752eefc77a8|1630525956184|2147483647
QueryBuilder.select(
    SelectResult.property("id"),
    SelectResult.property("timestamp"),
    SelectResult.property("rating"))
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string(DOC_TYPE))
   .and(Expression.property("rating").lessThan(Expression.intValue(1))
)

结果符合预期,因为我们用 rating < 1 搜索所有内容,第三项被过滤掉了。

4e39f79c-9e11-4aba-9fb6-95d910f46cd9|0|-2147483648
e95646ee-ba3a-4978-b2a8-5383f31be2f1|0|-2147483648
QueryBuilder.select(
    SelectResult.property("id"),
    SelectResult.property("timestamp"),
    SelectResult.property("rating"))
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string(DOC_TYPE))
   .and(Expression.property("rating").lessThan(Expression.intValue(1))
       .and(Expression.property("timestamp")).lessThanOrEqualTo (Expression.longValue(1))
                    )
            )

现在结果真的很奇怪,因为我从数据库中收到了三个项目。第三个 timestamp 比查询中的 1 大得多。

4e39f79c-9e11-4aba-9fb6-95d910f46cd9|0|-2147483648
e95646ee-ba3a-4978-b2a8-5383f31be2f1|0|-2147483648
e02d0eb3-6c9b-4942-b43c-a752eefc77a8|1630525956184|2147483647

关于如何让它与多个 and() 一起工作有什么想法吗?如果我尝试删除第二个 and() 并保留第三个,一切都会按预期进行。

经过深入调查,我发现我的代码存在几个问题:

  • .and() 应该在“子”条件结束时调用,而不是在“父”级别调用。

对于这样的条件

val condition1 = Expression.property("type").equalTo(Expression.string(DOC_TYPE))
val condition2 = Expression.property("rating").lessThan(Expression.intValue(1))
val condition3 = Expression.property("timestamp")).lessThanOrEqualTo (Expression.longValue(1))

正确的方法是

.where(condition1.and(
            condition2.and(
                condition3.and(
                    ...
                )
            )
        )

但不像我试过的那样

.where(condition1.and(condition2)
                 .and(condition3)
                 .and(...)
      )
  • 为了创建对象,我使用了一个代码,在保存到 couchbase 之前将对象转换为 Map<String, Any>。一切似乎都很好,直到我意识到 Long 被转换为 Double.
  • 最后一点,我有很多复杂的查询,其中一个我不小心使用了 .add() 而不是 .and()。没有评论。

希望这有助于节省一些时间。

我希望查询会像您原来那样:

.where(condition1.and(条件2) .和(条件3) .and(...))

我觉得这里多了一个括号好像是错的:

.and(Expression.property("时间戳"))