按日期分组的{RethinkDB查询

时间:2015-08-24 01:05:25

标签: rethinkdb

我存储了以下文件:

{
    "date": 1437429603126,
    "id": "7c578fe6-5eeb-466c-a79a-628784fd0d16",
    "quote": {
        "c": "+2.45",
        "c_fix": "2.45",
        "ccol": "chg",
        "cp": "1.89",
        "cp_fix": "1.89",
        "div": "0.52",
        "e": "NASDAQ",
        "ec": "+0.58",
        "ec_fix": "0.58",
        "eccol": "chg",
        "ecp": "0.44",
        "ecp_fix": "0.44",
        "el": "132.65",
        "el_cur": "132.65",
        "el_fix": "132.65",
        "elt": "Jul 20, 5:59PM EDT",
        "id": "22144",
        "l": "132.07",
        "l_cur": "132.07",
        "l_fix": "132.07",
        "lt": "Jul 20, 4:09PM EDT",
        "lt_dts": "2015-07-20T16:09:40Z",
        "ltt": "4:09PM EDT",
        "pcls_fix": "129.62",
        "s": "2",
        "t": "AAPL",
        "yld": "1.57"
    }
}

并希望运行一个选择字段quote.tquote.lquote.cquote.cp tAAPL date的查询{ {1}}。缺少的部分是在同一天通过多个文档进行分组。我需要的逻辑是将最早的文档放在quote.t = AAPL。所以基本上每天只返回一个文档,该文档应该有最大的date

到目前为止,这是我在一天内错过了多个文档的分组。

r.db('macd').table('daily_closes').filter({
    'quote': {
        't': 'AAPL'
    }
}).orderBy('date').pluck('date', {
    'quote': [
        't',
        'l',
        'c',
        'cp'
    ]
})

另外,我有二级索引,如何在查询中使用它们?

1 个答案:

答案 0 :(得分:3)

您需要按日期分组,但您将日期存储为纪元时间。所以你需要一种方法将它变成白天和小组。然后我们可以group使用该值,并按desc顺序对reduce数组进行排序,然后使用nth获取该数组的第一个元素。

r.table('daily_closes').filter({
    'quote': {
        't': 'AAPL'
    }
}).orderBy('date')
.pluck('date', {
    'quote': [
        't',
        'l',
        'c',
        'cp'
    ]
}).group(r.epochTime(r.row('date').div(1000)).date()).orderBy(r.desc('date')).nth(0)

你可能会遇到这样的事情:

{
"group": Mon Jul 20 2015 00:00:00 GMT+00:00 ,
"reduction": {
"_date": Mon Jul 20 2015 00:00:00 GMT+00:00 ,
"date": 1437429603126 ,
"quote": {
"c":  "+2.45" ,
"cp":  "1.89" ,
"l":  "132.07" ,
"t":  "AAPL"
}
}
}

因此,让我们减少噪音,我们会ungroup它。基本上没有ungroup,您在每个组的子流上运行,当您ungroup时,它们就会成为单个文档。我们也只关心reduction内的数据,因为它包含单个第一个文档。这是最终查询:

r.table('daily_closes').filter({
    'quote': {
        't': 'AAPL'
    }
}).orderBy('date')
.pluck('date', {
    'quote': [
        't',
        'l',
        'c',
        'cp'
    ]
})
.group(r.epochTime(r.row('date').div(1000)).date()).orderBy(r.desc('date')).nth(0)
.ungroup()
.getField('reduction')

现在,让我们使用索引。

首先,filter速度很慢,限制为100k文档,没有索引的order速度很慢。让我们用索引切换到getAll。但我们不能order索引后跟getAll。所以我们将使用这个技巧:

为这两个值创建索引并使用between

r.table('daily_closes').indexCreate('quote_date', [r.row('quote')('t'),r.row('date')])

现在,我们使用:

r.table('daily_closes')
.between(['AAPL', r.minval], ['AAPL', r.maxval],{index: 'quote_date'})
.pluck('date', {
    'quote': [
        't',
        'l',
        'c',
        'cp'
    ]
})
.group(r.epochTime(r.row('date').div(1000)).date())
.orderBy(r.desc('date')).nth(0)
.ungroup()
.getField('reduction')

我希望这会有所帮助。

相关问题