|
20 | 20 |
|
21 | 21 | import asyncio |
22 | 22 | import logging |
| 23 | +from datetime import datetime, timezone |
23 | 24 | from typing import Any, Dict, Optional |
24 | 25 |
|
25 | 26 | from google.cloud import firestore |
@@ -121,19 +122,32 @@ def _get_from_firestore(): |
121 | 122 | last_update_time=update_timestamp, |
122 | 123 | ) |
123 | 124 |
|
124 | | - # Fetch events without ordering from the database to avoid index requirements. |
| 125 | + # Build the query for events. |
| 126 | + # Note: This requires a composite index in Firestore on the 'timestamp' field. |
125 | 127 | events_ref = session_ref.collection(EVENTS_SUBCOLLECTION) |
126 | | - event_docs = events_ref.stream() |
127 | | - events_list = [_from_firestore_doc_to_event(doc) for doc in event_docs] |
128 | | - # Sort the events in the application code instead. |
129 | | - events_list.sort(key=lambda e: e.timestamp) |
130 | | - session.events = events_list |
131 | | - |
132 | | - if config: |
133 | | - if config.num_recent_events: |
134 | | - session.events = session.events[-config.num_recent_events :] |
135 | | - elif config.after_timestamp: |
136 | | - session.events = [e for e in session.events if e.timestamp > config.after_timestamp] |
| 128 | + query = events_ref |
| 129 | + |
| 130 | + if config and config.num_recent_events: |
| 131 | + query = query.order_by( |
| 132 | + "timestamp", direction=firestore.Query.DESCENDING |
| 133 | + ).limit(config.num_recent_events) |
| 134 | + event_docs = query.stream() |
| 135 | + events_list = [_from_firestore_doc_to_event(doc) for doc in event_docs] |
| 136 | + # Reverse the list to have events in chronological order. |
| 137 | + events_list.reverse() |
| 138 | + session.events = events_list |
| 139 | + else: |
| 140 | + if config and config.after_timestamp: |
| 141 | + # Firestore timestamps can be compared with datetime objects. |
| 142 | + after_dt = datetime.fromtimestamp( |
| 143 | + config.after_timestamp, tz=timezone.utc |
| 144 | + ) |
| 145 | + query = query.where(filter=FieldFilter("timestamp", ">", after_dt)) |
| 146 | + |
| 147 | + query = query.order_by("timestamp", direction=firestore.Query.ASCENDING) |
| 148 | + event_docs = query.stream() |
| 149 | + events_list = [_from_firestore_doc_to_event(doc) for doc in event_docs] |
| 150 | + session.events = events_list |
137 | 151 |
|
138 | 152 | return session |
139 | 153 |
|
|
0 commit comments