Skip to content

Commit

Permalink
Fix for upserting of documents
Browse files Browse the repository at this point in the history
  • Loading branch information
erichare committed Nov 15, 2023
1 parent 3edb6c1 commit d9f5746
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 16 deletions.
20 changes: 7 additions & 13 deletions astrapy/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,24 +635,18 @@ def upsert(self, document):
str: The _id of the inserted or updated document.
"""
# Attempt to insert the given document
result = self.insert_one(document)

# Check if we hit an error
if (
"errors" in result
and "errorCode" in result["errors"][0]
and result["errors"][0]["errorCode"] == "DOCUMENT_ALREADY_EXISTS"
):
try:
self.insert_one(document)
except Exception as e:
logger.debug(e)

# Now we attempt to update
result = self.find_one_and_replace(
self.find_one_and_replace(
filter={"_id": document["_id"]},
replacement=document,
)
upserted_id = result["data"]["document"]["_id"]
else:
upserted_id = result["status"]["insertedIds"][0]

return upserted_id
return document["_id"]


class AstraDB:
Expand Down
6 changes: 3 additions & 3 deletions tests/astrapy/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,7 @@ def test_vector_find_projection(projection_collection):


@pytest.mark.describe("upsert a document")
def test_upsert_document(collection, cliff_uuid):
def test_upsert_document(collection):
new_uuid = str(uuid.uuid4())

collection.upsert(
Expand All @@ -624,12 +624,12 @@ def test_upsert_document(collection, cliff_uuid):

collection.upsert(
{
"_id": cliff_uuid,
"_id": new_uuid,
"addresses": {"work": {"city": "Everett", "state": "WA", "country": "USA"}},
}
)

document = collection.find_one(filter={"_id": cliff_uuid})
document = collection.find_one(filter={"_id": new_uuid})

assert document is not None
assert document["data"]["document"]["addresses"]["work"]["city"] == "Everett"
Expand Down

0 comments on commit d9f5746

Please sign in to comment.