假设我有一个带有typetimestamp字段的RethinkDB表。 type可以是"good""bad"。我想编写一个RethinkDB查询,该查询在使用compound indextimestamp"good"的同时获取最新type文档的timestamp

这是带有一种解决方案的示例脚本:

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


在运行此脚本之前,我使用以下命令在端口28016上启动了RethinkDB

rethinkdb --port-offset 1


我还使用faker包生成伪造数据。

我使用的结合了betweenorder_bylimit的查询看起来并不特别优雅或简洁,我想知道是否可以为此目的使用max。但是,从文档(https://www.rethinkdb.com/api/python/max/)到现在我还不清楚如何执行此操作。有任何想法吗?

最佳答案

理想情况下,您可以替换查询的这一部分:

.order_by(index=r.desc("type_timestamp")).limit(1)


带有:

.max(index="type_timestamp")


但是,目前尚不可能。见https://github.com/rethinkdb/rethinkdb/issues/5141

关于python - 如何将RethinkDB的最小/最大函数与复合索引一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42676310/

10-12 21:38