[server]: Update return_all_coordinates
This commit is contained in:
@ -1,26 +1,51 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import boto3
|
import boto3
|
||||||
|
from boto3.dynamodb.conditions import Attr
|
||||||
|
|
||||||
os.environ.setdefault('AWS_DEFAULT_REGION', 'us-east-1')
|
os.environ.setdefault('AWS_DEFAULT_REGION', 'us-east-1')
|
||||||
dynamodb = boto3.resource('dynamodb')
|
dynamodb = boto3.resource('dynamodb')
|
||||||
|
|
||||||
|
|
||||||
def lambda_handler(event, context):
|
def lambda_handler(event, context):
|
||||||
table = dynamodb.Table(os.environ['TABLE_NAME'])
|
table = dynamodb.Table(os.environ['TABLE_NAME'])
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Scan entire table and only extract latitude and longitude
|
# Step 1: Retrieve the latest timestamp
|
||||||
|
items = []
|
||||||
|
response = table.scan(
|
||||||
|
ProjectionExpression="#ts",
|
||||||
|
ExpressionAttributeNames={"#ts": "timestamp"}
|
||||||
|
)
|
||||||
|
items.extend(response.get('Items', []))
|
||||||
|
|
||||||
|
while 'LastEvaluatedKey' in response:
|
||||||
|
response = table.scan(
|
||||||
|
ProjectionExpression="#ts",
|
||||||
|
ExpressionAttributeNames={"#ts": "timestamp"},
|
||||||
|
ExclusiveStartKey=response['LastEvaluatedKey']
|
||||||
|
)
|
||||||
|
items.extend(response.get('Items', []))
|
||||||
|
|
||||||
|
if not items:
|
||||||
|
return {'statusCode': 200, 'body': json.dumps({'coordinates': []})}
|
||||||
|
|
||||||
|
newest_timestamp = max(int(item['timestamp']) for item in items)
|
||||||
|
|
||||||
|
# Step 2: Get only items with that latest timestamp
|
||||||
coordinates = []
|
coordinates = []
|
||||||
response = table.scan()
|
response = table.scan(
|
||||||
|
FilterExpression=Attr('timestamp').eq(newest_timestamp)
|
||||||
|
)
|
||||||
|
|
||||||
for item in response.get('Items', []):
|
for item in response.get('Items', []):
|
||||||
if 'latitude' in item and 'longitude' in item:
|
if 'latitude' in item and 'longitude' in item:
|
||||||
coordinates.append([item['latitude'], item['longitude']])
|
coordinates.append([item['latitude'], item['longitude']])
|
||||||
|
|
||||||
# Handle pagination
|
|
||||||
while 'LastEvaluatedKey' in response:
|
while 'LastEvaluatedKey' in response:
|
||||||
response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
|
response = table.scan(
|
||||||
|
FilterExpression=Attr('timestamp').eq(newest_timestamp),
|
||||||
|
ExclusiveStartKey=response['LastEvaluatedKey']
|
||||||
|
)
|
||||||
for item in response.get('Items', []):
|
for item in response.get('Items', []):
|
||||||
if 'latitude' in item and 'longitude' in item:
|
if 'latitude' in item and 'longitude' in item:
|
||||||
coordinates.append([item['latitude'], item['longitude']])
|
coordinates.append([item['latitude'], item['longitude']])
|
||||||
|
Reference in New Issue
Block a user