1
假设我有一个RethinkDB表,其中有type
和timestamp
字段。 type
可以是"good"
或"bad"
。我想写一个RethinkDB查询,获取最近的"good"
文档的timestamp
,同时使用compound index和type
和timestamp
。如何使用RethinkDB的复合索引的最小/最大函数
这里是用一种溶液的示例脚本:
import faker
import rethinkdb as r
import dateutil.parser
import dateutil.tz
fake = faker.Faker()
fake.seed(0) # Seed the Faker() for reproducible results
conn = r.connect('localhost', 28016) # The RethinkDB server needs to have been launched with 'rethinkdb --port-offset 1' at the command line
# Create and clear a table
table_name = 'foo' # Arbitrary table name
if table_name not in r.table_list().run(conn):
r.table_create(table_name).run(conn)
r.table(table_name).delete().run(conn) # Start on a clean slate
# Create fake data and insert it into the table
N = 5 # Half the number of fake documents
good_documents = [{'type':'good', 'timestamp': dateutil.parser.parse(fake.time()).replace(tzinfo=dateutil.tz.tzutc())} for _ in range(N)]
bad_documents = [{'type':'bad', 'timestamp': dateutil.parser.parse(fake.time()).replace(tzinfo=dateutil.tz.tzutc())} for _ in range(N)]
documents = good_documents + bad_documents
r.table(table_name).insert(documents).run(conn)
# Create compound index with 'type' and 'timestamp' fields
if 'type_timestamp' not in r.table(table_name).index_list().run(conn):
r.table(table_name).index_create("type_timestamp", [r.row["type"], r.row["timestamp"]]).run(conn)
r.table(table_name).index_wait("type_timestamp").run(conn)
# Get the latest 'good' timestamp in Python
good_documents = [doc for doc in documents if doc['type'] == "good"]
latest_good_timestamp_Python = max(good_documents, key=lambda doc: doc['timestamp'])['timestamp']
# Get the latest 'good' timestamp in RethinkDB
cursor = r.table(table_name).between(["good", r.minval], ["good", r.maxval], index="type_timestamp").order_by(index=r.desc("type_timestamp")).limit(1).run(conn)
document = next(cursor)
latest_good_timestamp_RethinkDB = document['timestamp']
# Assert that the Python and RethinkDB 'queries' return the same thing
assert latest_good_timestamp_Python == latest_good_timestamp_RethinkDB
之前运行此脚本,我使用命令
rethinkdb --port-offset 1
我也使用faker包以产生发射RethinkDB在端口28016假数据。
,我使用的查询,它结合了between
,order_by
和limit
,似乎并不特别优雅或简洁,我想知道是否可以使用max
用于此目的。但是,从文档(https://www.rethinkdb.com/api/python/max/)中我不清楚如何执行此操作。有任何想法吗?
不幸的是这一点让'rethinkdb.errors.ReqlQueryLogicError:预期类型表却发现TABLE_SLICE:([ '好',R之间 r.table( '富'): 选择的表(富)。 .minval],['good',r.maxval],index ='type_timestamp').max(index ='type_timestamp')'。 –
我的建议确实无效。我已经更新了答案 – AtnNn