如何在复合索引中使用db的min/max函数

2024-05-18 06:34:26 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个带有typetimestamp字段的数据库表。type可以是"good""bad"。我想写一个重新思考的DB查询,它在使用带有typetimestampcompound index时获取最新"good"文档的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端口启动了reinspectdb

rethinkdb --port-offset 1

我还使用faker包生成假数据。你知道吗

我使用的查询组合了betweenorder_bylimit,看起来不是特别优雅或简洁,我想知道是否可以使用max来实现这个目的。但是,从文档(https://www.rethinkdb.com/api/python/max/)中我还不清楚如何做到这一点。有什么想法吗?你知道吗


Tags: therunnameinindextypetableconn