JDog
JDog

Reputation: 51

Azure CosmosDB why isn't the 'id' field automatically added when inserting into Azure CosmosDB?

I have recently started getting this error when I debug my python function app: (BadRequest) Message: {"Errors":["One of the specified inputs is invalid"]}

The function app works perfectly well for my coworkers and they are not getting this error. The error occurs whenever I attempt to access the azure cosmos db.

Sample

item = { "firstname": "John", "lastname": "Doe"}
container.upsert_item(item)

The issue seems to be that insert into the database is missing the "id" field. If I add this field to the item before calling upsert_item(item) it works correctly.

Why did I not originally need to do this (coworkers don't need to) and what setting did I change to stop it from auto adding the id field?

I am using visual studio code, coding in python, installed the azure tools extension. I have tried deleting the code from disk and re-cloning it, removing all the extensions and reinstalling them, and I even completely uninstalled visual studio code. Whatever setting changed is still there.

EDIT

Added the container properties

Container properties {'id': 'person', 'indexingPolicy': {'indexingMode': 'consistent', 'automatic': True, 'includedPaths': [{'path': '/*'}], 'excludedPaths': [{'path': '/"_etag"/?'}]}, 'partitionKey': {'paths': ['/lastname'], 'kind': 'Hash'}, 'uniqueKeyPolicy': {'uniqueKeys': []}, 'conflictResolutionPolicy': {'mode': 'LastWriterWins', 'conflictResolutionPath': '/_ts', 'conflictResolutionProcedure': ''}, 'geospatialConfig': {'type': 'Geography'}, 'analyticalStorageTtl': -1, '_rid': 'O-pDAPQSY5Y=', '_ts': 1654191756, '_self': 'dbs/O-pDAA==/colls/O-pDAPQSY5Y=/', '_etag': '"00003b31-0000-0100-0000-6298f68c0000"', '_docs': 'docs/', '_sprocs': 'sprocs/', '_triggers': 'triggers/', '_udfs': 'udfs/', '_conflicts': 'conflicts/'}

Upvotes: 3

Views: 3897

Answers (2)

Gijs Wobben
Gijs Wobben

Reputation: 2060

If people are still looking for this: You can now add the enable_automatic_id_generation flag to the create_item method.

Example:

result = container.create_item(
    {
        "data": "hello world",
    },
    enable_automatic_id_generation=True,
)

Upvotes: 1

JDog
JDog

Reputation: 51

Found the answer to my issue. I had updated azure cosmos db to the latest version (4.3.0) globaly (which is why it only affected me, should have put it in the requirements.txt instead) which does not allow for the automatic creation of ids.

There is a single line change (from 4.2.0 to 4.3.0) in the upsert_item(...) function that is difficult to spot (worded very similarly) when you are looking at a wall of code.

Azure-Cosmos-4.3.0 github link to the line

Annoyingly this line is hard coded. Why they decided to prevent the user from auto generating ids is beyond me.

Upvotes: 2

Related Questions