在Firebase中按指定子项进行筛选和排序

时间:2017-09-29 00:00:04

标签: swift firebase nested-queries

我正在使用Firebase和Swift构建游戏应用,并存储我的数据。

  while(true)
    {
          // This call waits until a new coherent set of frames is available on a device
        // Calls to get_frame_data(...) and get_frame_timestamp(...) on a device will return stable values until wait_for_frames(...) is called
        dev->wait_for_frames();

        // Retrieve depth data, which was previously configured as a 640 x 480 image of 16-bit depth values
        const uint16_t * depth_frame = reinterpret_cast<const uint16_t *>(dev->get_frame_data(rs::stream::depth));

        Mat depthData(Size(640, 480), CV_16UC1, (void*)dev->get_frame_data(rs::stream::depth), Mat::AUTO_STEP);
        imshow( "WINDOW_DEPTH", depthData );
        cvWaitKey( 1 );

      //  cout<<"\n\n\n\n\n\n\n\n\ndepthData:-------------------->"<<depthData;

        //cal vol
        int Totalintensity = 0;
        for (int i=0; i < depthData.rows; ++i){
          for (int j=0; j < depthData.cols; ++j){
            Totalintensity += (int)depthData.at<uchar>(i, j);
          }
      }
        cout<<"\ntotalVol:"<<Totalintensity;
    }

我需要根据分数进行两个查询:

  • 从单一类别中获得前5名玩家。
  • 获得游戏的前100名玩家。

使用

获取第一个查询的数据没有问题
- (void)splitDicts
{
    // This is just me creating sample data for the "whole" dictionary.
    NSMutableDictionary *whole = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < 10; i++)
    {
        NSString *key = [NSString stringWithFormat:@"%d", i];
        NSString *value = [NSString stringWithFormat:@"Valus is %d", i];
        whole[key] = value;
    }

    NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
    __block BOOL addToDict1 = YES;

    [whole enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if (addToDict1)
        {
            dict1[key] = obj;
        }
        else
        {
            dict2[key] = obj;
        }
        addToDict1 = !addToDict1;
    }];
}

但我无法搞清楚第二个查询。我怎样才能有效地做到这一点?

1 个答案:

答案 0 :(得分:0)

您需要添加其他数据结构以允许第二个查询(这在NoSQL数据库中非常常见)或更改当前结构以允许两个查询。

后者可以通过将数据转换为单个平面列表来实现,具有一些额外的合成属性。 E.g。

players: {
   "playerId": {
     category: "category1"
     name: "Joe", 
     score: 3,
     category_score: "category1_3"
   }
}

使用新的附加属性categorycategory_score,您可以获得以下类别的最佳得分者:

ref.child("players")
   .queryOrdered(byChild: "category_score")
   .queryStarting(atValue:"category1_")
   .queryEnding(atValue("category1_~")
   .queryLimited(toLast:5)

前100名得分总分为:

ref.child("players")
   .queryOrdered(byChild: "score")
   .queryLimited(toLast:100)

有关详细信息,请参阅我的答案:Firebase数据库查询只能对单个属性进行排序/过滤。在许多情况下,可以将要过滤的值组合到单个(合成)属性中。有关此方法和其他方法的示例,请参阅我的答案:http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase