0

如何查询包含两个键的 couchbase 视图?第一个是 NSNumber 类型(在下面的示例中称为 created)和 NSString 类型(称为 username)。

CBLView* view = [database viewNamed:@"by_username"];
if (!view.mapBlock)
{
    [view setMapBlock: MAPBLOCK({
        if ( [doc[@"type"] isEqualToString:@"user"] )
        {
            emit(@[doc[@"created"],doc[@"username"]], nil);
        };
    }) version: @"2"];
}

CBLQuery* q = [view createQuery];
q.keys = @[ @[ @{}, @"john" ] ];
// run query

使用上面的查询,我希望所有文档与 doc[@"username"] == @"john" 匹配,无论 doc[@"created"] 的值如何(即我假设 @{ } 相当于通配符)。

但是,尽管存在许多用户名为 @"john" 的文档,但查询返回 0 个匹配项。我一定做错了什么,因此非常感谢任何见解!

4

2 回答 2

1

It appears that you are trying to search backwards, your index should be organized by the first item you want to search by. So, if you don't care about created, you should remove it from the index, because it results in the issue you have here. Understanding that you may need this for some other query, create a new view with this change.

Also, as a general note on your answer, it does absolutely no good to emit the whole doc in an index. It results in doubling the size of storage along with inefficient operation of the view framework.

于 2015-01-22T12:41:43.577 回答
0

进一步的调查提出了在查询数据库时使用 NSSortDescriptior 的可能性,这将我的代码简化为以下内容:

CBLView* view = [database viewNamed:@"by_username"];
if (!view.mapBlock)
{
    [view setMapBlock: MAPBLOCK({
        if ( [doc[@"type"] isEqualToString:@"user"] )
        {
            emit(doc[@"username"], doc[@"created"]);
        };
    }) version: @"2"];
}

CBLQuery* q = [view createQuery];
q.keys = @[ @"john" ];

q.sortDescriptors = @[ [[NSSortDescriptor alloc] initWithKey:@"value" ascending:NO] ];

在这种情况下,sortDescriptors 是一个只有一个 NSSortDescriptor 的数组。请注意,mapBlock 现在发出一个“doc”对象,因此它在 NSSortDescriptor 中显示为“value”键路径,因此“created”可用于排序。希望这对其他人有帮助。

于 2015-01-21T18:05:24.313 回答