LogicGoInfotechSpaces commited on
Commit
defc757
·
1 Parent(s): 0f645e3

Improve media_clicks insert: use find_one_and_update and attempt to drop old index automatically

Browse files
Files changed (1) hide show
  1. app.py +65 -32
app.py CHANGED
@@ -8,7 +8,7 @@ from fastapi import FastAPI, File, Form, UploadFile, Query, Depends, Request
8
  from fastapi.responses import FileResponse, JSONResponse
9
  from huggingface_hub import InferenceClient
10
  from PIL import Image
11
- from pymongo import MongoClient
12
  from pymongo.errors import DuplicateKeyError
13
  from bson import ObjectId
14
  from typing import Optional
@@ -337,9 +337,9 @@ def save_media_click(user_id: Optional[int], category_id: str):
337
  print(f"[MongoDB] Added new category - userId: {user_object_id}, categoryId: {category_object_id}")
338
  else:
339
  # Document doesn't exist, try to create new document
340
- # Use try-except to handle potential duplicate key errors from old index
341
  try:
342
- result = collection.update_one(
343
  {"userId": user_object_id},
344
  {
345
  "$setOnInsert": {
@@ -357,36 +357,69 @@ def save_media_click(user_id: Optional[int], category_id: str):
357
  "updatedAt": now
358
  }
359
  },
360
- upsert=True
 
361
  )
362
- if result.upserted_id:
363
- print(f"[MongoDB] Inserted new document - userId: {user_object_id}, categoryId: {category_object_id}, ID: {result.upserted_id}")
364
- else:
365
- print(f"[MongoDB] Updated document - userId: {user_object_id}, categoryId: {category_object_id}")
366
- except DuplicateKeyError:
367
- # If duplicate key error, document might have been created by another request
368
- # Try to find it and update it
369
- print(f"[MongoDB] Duplicate key error on insert, checking if document exists...")
370
- existing = collection.find_one({"userId": user_object_id})
371
- if existing:
372
- # Document exists now, add category
373
- result = collection.update_one(
374
- {"userId": user_object_id},
375
- {
376
- "$push": {
377
- "categories": {
378
- "categoryId": category_object_id,
379
- "click_count": 1,
380
- "lastClickedAt": now
381
- }
382
- },
383
- "$set": {"updatedAt": now}
384
- }
385
- )
386
- print(f"[MongoDB] Added category to existing document - userId: {user_object_id}, categoryId: {category_object_id}")
387
- else:
388
- # Still doesn't exist, might be old index conflict - skip for now
389
- print(f"[MongoDB] WARNING: Could not create document due to old index conflict. Skipping media_clicks logging.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
  return False
391
 
392
  return True
 
8
  from fastapi.responses import FileResponse, JSONResponse
9
  from huggingface_hub import InferenceClient
10
  from PIL import Image
11
+ from pymongo import MongoClient, ReturnDocument
12
  from pymongo.errors import DuplicateKeyError
13
  from bson import ObjectId
14
  from typing import Optional
 
337
  print(f"[MongoDB] Added new category - userId: {user_object_id}, categoryId: {category_object_id}")
338
  else:
339
  # Document doesn't exist, try to create new document
340
+ # Use find_one_and_update with upsert which handles conflicts better
341
  try:
342
+ result = collection.find_one_and_update(
343
  {"userId": user_object_id},
344
  {
345
  "$setOnInsert": {
 
357
  "updatedAt": now
358
  }
359
  },
360
+ upsert=True,
361
+ return_document=ReturnDocument.AFTER
362
  )
363
+ if result:
364
+ print(f"[MongoDB] Inserted/Updated document - userId: {user_object_id}, categoryId: {category_object_id}, ID: {result.get('_id')}")
365
+ except DuplicateKeyError as dke:
366
+ # If duplicate key error, try to find existing document and update it
367
+ print(f"[MongoDB] Duplicate key error on insert: {str(dke)[:200]}")
368
+ print(f"[MongoDB] Attempting to find and update existing document...")
369
+ try:
370
+ existing = collection.find_one({"userId": user_object_id})
371
+ if existing:
372
+ # Document exists, add category
373
+ result = collection.update_one(
374
+ {"userId": user_object_id},
375
+ {
376
+ "$push": {
377
+ "categories": {
378
+ "categoryId": category_object_id,
379
+ "click_count": 1,
380
+ "lastClickedAt": now
381
+ }
382
+ },
383
+ "$set": {"updatedAt": now}
384
+ }
385
+ )
386
+ print(f"[MongoDB] Added category to existing document - userId: {user_object_id}, categoryId: {category_object_id}")
387
+ else:
388
+ # Document doesn't exist but index conflict - try to drop old index programmatically
389
+ print(f"[MongoDB] WARNING: Old index conflict detected. Attempting to handle...")
390
+ try:
391
+ # Try to drop the problematic index
392
+ collection.drop_index("user_id_1_header_1_media_id_1")
393
+ print(f"[MongoDB] Successfully dropped old index. Retrying insert...")
394
+ # Retry the insert
395
+ result = collection.find_one_and_update(
396
+ {"userId": user_object_id},
397
+ {
398
+ "$setOnInsert": {
399
+ "userId": user_object_id,
400
+ "createdAt": now
401
+ },
402
+ "$push": {
403
+ "categories": {
404
+ "categoryId": category_object_id,
405
+ "click_count": 1,
406
+ "lastClickedAt": now
407
+ }
408
+ },
409
+ "$set": {
410
+ "updatedAt": now
411
+ }
412
+ },
413
+ upsert=True,
414
+ return_document=ReturnDocument.AFTER
415
+ )
416
+ print(f"[MongoDB] Successfully inserted after dropping old index - userId: {user_object_id}, categoryId: {category_object_id}")
417
+ except Exception as drop_error:
418
+ print(f"[MongoDB] Could not drop index (may not have permissions): {str(drop_error)[:200]}")
419
+ print(f"[MongoDB] ERROR: Cannot create document due to old index. Please drop index 'user_id_1_header_1_media_id_1' manually in MongoDB.")
420
+ return False
421
+ except Exception as find_error:
422
+ print(f"[MongoDB] Error finding existing document: {str(find_error)[:200]}")
423
  return False
424
 
425
  return True