{"id":10349,"date":"2023-06-23T01:43:43","date_gmt":"2023-06-23T08:43:43","guid":{"rendered":"https:\/\/www.couchbase.com\/developers\/tutorials\/python-key-value-operations\/"},"modified":"2023-06-23T01:43:43","modified_gmt":"2023-06-23T08:43:43","slug":"python-key-value-operations","status":"publish","type":"tutorials","link":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/","title":{"rendered":"Key Value Operations with Python"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">In this tutorial, you will learn how to use Key Value operations to create, read, update and delete documents and how to use the CAS value to identify the current state of an item.<\/p>\n\n\n\n<h3 id=\"h-introduction\" class=\"wp-block-heading\">Introduction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Key Value (also known as the Couchbase Data Service) offers the simplest way to retrieve or mutate data where you know the key. A key-value store is a type of <a href=\"https:\/\/www.couchbase.com\/resources\/why-nosql\/?ref=blog\/\">NoSQL Database<\/a> that uses a simple method to store data as a collection of key-value pairs in which a key serves as the unique identifier.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The core interface to Couchbase Server is simple KV operations on full documents. Make sure you\u2019re familiar with the basics of authorization and connecting to a Cluster from the <a href=\"https:\/\/docs.couchbase.com\/python-sdk\/current\/hello-world\/start-using-sdk.html\">Start Using the SDK Section<\/a>. We\u2019re going to expand on the short <em>Upsert<\/em> example we used there, adding options as we move through the various CRUD operations. Here is the <em>Insert<\/em> operation at its simplest:<\/p>\n\n\n\n<h3 id=\"h-insert-operation\" class=\"wp-block-heading\">Insert Operation<\/h3>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code># Insert document\ndocument = {&quot;foo&quot;: &quot;bar&quot;, &quot;bar&quot;: &quot;foo&quot;}\nresult = collection.insert(&quot;document-key&quot;, document)\ncas = result.cas\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Options may be added to operations. It is best practice to use the *Options() class that matches the name of the operation (e.g. GetOptions(), InsertOptions(), etc.). However, keyword arguments can be used as an override to a corresponding value within the options.\nOptions like <em>timeout<\/em> and <em>expiry<\/em> are timedelta objects.<\/p>\n\n\n\n<h4 id=\"h-options\" class=\"wp-block-heading\">Options<\/h4>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code># Insert document with options\ndocument = {&quot;foo&quot;: &quot;bar&quot;, &quot;bar&quot;: &quot;foo&quot;}\nopts = InsertOptions(timeout=timedelta(seconds=5))\nresult = collection.insert(&quot;document-key-opts&quot;,\n                           document,\n                           opts,\n                           expiry=timedelta(seconds=30))\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Expiration sets an explicit time to live (TTL) for a document. We\u2019ll discuss modifying <code>Expiration<\/code> in more details <a href=\"https:\/\/docs.couchbase.com\/python-sdk\/current\/howtos\/kv-operations.html#expiration-ttl\/\">below<\/a>. For a discussion of item (Document) <em>vs<\/em> Bucket expiration, see the <a href=\"https:\/\/docs.couchbase.com\/server\/6.6\/learn\/buckets-memory-and-storage\/expiration.html#expiration-bucket-versus-item\/\">Expiration Overview page<\/a>.<\/p>\n\n\n\n<h3 id=\"h-read-documents\" class=\"wp-block-heading\">Read Documents<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Using the <code>get()<\/code> method with the document key, we can fetch the document:<\/p>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code>result = collection.get(&quot;document-key&quot;)\nprint(result.content_as[dict])\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Timeout can also be set:<\/p>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code>opts = GetOptions(timeout=timedelta(seconds=5))\nresult = collection.get(&quot;document-key&quot;, opts)\nprint(result.content_as[dict])\n\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-updateupsert-document\" class=\"wp-block-heading\">Update\/Upsert Document<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">An upsert operation inserts the document into a collection if they do not already exist, or updates them if they do.<\/p>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code>content = {&quot;foobar&quot;: &quot;barfoo&quot;}\nresult = cb_coll.upsert(&quot;document-key&quot;, content)\n\nupdated_doc = cb_coll.get(&quot;document-key&quot;)\nupserted_doc = updated_doc.content\nprint(f&quot;Upserted Document: {upserted_doc}&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code>document = {&quot;foo&quot;: &quot;bar&quot;, &quot;bar&quot;: &quot;foo&quot;}\nresult = cb_coll.upsert(&quot;document-key-1&quot;, document)\n\n# fetch the new document\ninserted_doc = cb_coll.get(&quot;document-key-1&quot;)\nupserted_doc = inserted_doc.content\nprint(f&quot;Upserted Document: {upserted_doc}&quot;)\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-delete-document\" class=\"wp-block-heading\">Delete Document<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">When removing a document, you will have the same concern for durability as with any additive modification to the Bucket:<\/p>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code># remove document with options\nresult = collection.remove(\n    &quot;document-key&quot;,\n    RemoveOptions(\n        cas=12345,\n        durability=ServerDurability(\n            Durability.MAJORITY)))\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-replace-document\" class=\"wp-block-heading\">Replace Document<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To replace a document\u2026<\/p>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code>result = cb_coll.get(&quot;document-key&quot;)\nprint(f&quot;Document Before Replace: {result.content}&quot;)\n\ndocument = {&quot;foo&quot;: &quot;bar&quot;, &quot;bar&quot;: &quot;foo&quot;}\nresult = cb_coll.replace(&quot;document-key&quot;, document)\n\nresult = cb_coll.get(&quot;document-key&quot;)\nprint(f&quot;Document After Replace: {result.content}&quot;)\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-durability\" class=\"wp-block-heading\">Durability<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Writes in Couchbase are written to a single node, and from there the Couchbase Server will take care of sending that mutation to any configured replicas. The optional durability parameter, which all mutating operations accept, allows the application to wait until this replication (or persistence) is successful before proceeding.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The SDK exposes three durability levels:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Majority &#8211; The server will ensure that the change is available in memory on the majority of configured replicas.<\/li>\n\n\n<li>MajorityAndPersistToActive &#8211; Majority level, plus persisted to disk on the active node.<\/li>\n\n\n<li>PersistToMajority &#8211; Majority level, plus persisted to disk on the majority of configured replicas.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The options are in increasing levels of safety. Note that nothing comes for free &#8211; for a given node, waiting for writes to storage is considerably slower than waiting for it to be available in-memory.<\/p>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code>\n# Upsert with Durability level Majority\n# The tradeoffs associated with durability levels may not be apparent in this example\n# since we are using a single node cluster, but become much more clear on multi-node clusters\n# The error is due to the single node setup\nfrom couchbase.collection import UpsertOptions\nfrom couchbase.durability import Durability, ServerDurability\n\ndocument = dict(foo=&quot;bar&quot;, bar=&quot;foo&quot;)\nopts = UpsertOptions(durability=ServerDurability(Durability.MAJORITY))\ntry:\n    result = cb_coll.upsert(&quot;document-key&quot;, document, opts)\nexcept Exception as e:\n    print(e)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It is possible to perform scoped key-value operations on named Collections with <em>Couchbase Server release<\/em> 7.0. See the <a href=\"https:\/\/docs.couchbase.com\/sdk-api\/couchbase-python-client\/api\/couchbase.html#collection-object\">API docs<\/a> for more information. Here is an example showing an upsert in the <code>users<\/code> collection, which lives in the <code>travel-sample.tenant_agent_00 keyspace<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code>agent_scope = bucket.scope(&quot;tenant_agent_00&quot;);\nusers_collection = agent_scope.collection(&quot;users&quot;);\n\ncontent = {&quot;name&quot;: &quot;John Doe&quot;, &quot;preferred_email&quot;: &quot;johndoe111@test123.test&quot; }\n\nresult = users_collection.upsert(&quot;user-key&quot;, content);\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-compare-and-swap-cas-value\" class=\"wp-block-heading\">Compare and Swap (CAS) Value:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The CAS is a value representing the current state of an item. Each time the item is modified, its CAS changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The CAS value itself is returned as part of a document\u2019s metadata whenever a document is accessed. In the SDK, this is presented as the cas field in the result object from any operation which executes successfully.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">CAS is an acronym for Compare And Swap, and is a form of optimistic locking. The CAS can be supplied as parameters to the replace and remove operations. When applications provide the CAS, server will check the application-provided version of CAS against the CAS of the document on the server:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If the two CAS values match (they compare successfully), then the mutation operation succeeds.<\/li>\n\n\n<li>If the two CAS values differ, then the mutation operation fails.<\/li>\n\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you will learn how to use Key Value operations to create, read, update and delete documents and how to use the CAS value to identify the current state of an item. Introduction Key Value (also known as the Couchbase Data Service) offers the simplest way to retrieve or mutate data where you [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"menu_order":0,"template":"","meta":{"_acf_changed":false,"inline_featured_image":false,"_acf":"","footnotes":""},"tutorial-languages":[606],"tutorial-tags":[557],"tutorial-technologies":[548,554],"tutorial-types":[555],"class_list":["post-10349","tutorials","type-tutorials","status-publish","hentry","tutorial-languages-python","tutorial-tags-data-ingestion","tutorial-technologies-kv","tutorial-technologies-server","tutorial-types-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v28.8 (Yoast SEO v28.9) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Key Value Operations with Python - Couchbase<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/\" \/>\n<meta property=\"og:locale\" content=\"de_DE\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Key Value Operations with Python\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, you will learn how to use Key Value operations to create, read, update and delete documents and how to use the CAS value to identify the current state of an item. Introduction Key Value (also known as the Couchbase Data Service) offers the simplest way to retrieve or mutate data where you [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/\" \/>\n<meta property=\"og:site_name\" content=\"Couchbase\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Couchbase\/\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2548\" \/>\n\t<meta property=\"og:image:height\" content=\"1171\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:site\" content=\"@couchbase\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5\u00a0Minuten\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/python-key-value-operations\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/python-key-value-operations\\\/\",\"name\":\"Key Value Operations with Python - Couchbase\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\"},\"datePublished\":\"2023-06-23T08:43:43+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/python-key-value-operations\\\/#breadcrumb\"},\"inLanguage\":\"de\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/python-key-value-operations\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/python-key-value-operations\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.couchbase.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Key Value Operations with Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"name\":\"Couchbase\",\"description\":\"The Operational Data Platform for AI\u2122\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\"},\"alternateName\":\"Couchbase, Inc.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"de\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\",\"name\":\"Couchbase\",\"alternateName\":\"Couchbase, Inc.\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"de\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"contentUrl\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"width\":1129,\"height\":1129,\"caption\":\"Couchbase\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/Couchbase\\\/\",\"https:\\\/\\\/x.com\\\/couchbase\",\"https:\\\/\\\/www.youtube.com\\\/c\\\/CouchbaseServer\",\"https:\\\/\\\/www.linkedin.com\\\/company\\\/couchbase\\\/\",\"https:\\\/\\\/github.com\\\/couchbase\\\/\",\"https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Couchbase,_Inc.\"],\"description\":\"Couchbase is a database software company headquartered in San Jose, California, providing an operational data platform for AI used by hundreds of global enterprises.\",\"legalName\":\"Couchbase, Inc.\",\"foundingDate\":\"2011-01-01\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Key Value Operations with Python - Couchbase","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/","og_locale":"de_DE","og_type":"article","og_title":"Key Value Operations with Python","og_description":"In this tutorial, you will learn how to use Key Value operations to create, read, update and delete documents and how to use the CAS value to identify the current state of an item. Introduction Key Value (also known as the Couchbase Data Service) offers the simplest way to retrieve or mutate data where you [&hellip;]","og_url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/","og_site_name":"Couchbase","article_publisher":"https:\/\/www.facebook.com\/Couchbase\/","og_image":[{"width":2548,"height":1171,"url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png","type":"image\/png"}],"twitter_card":"summary_large_image","twitter_site":"@couchbase","twitter_misc":{"Est. reading time":"5\u00a0Minuten"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/","url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/","name":"Key Value Operations with Python - Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/de\/#website"},"datePublished":"2023-06-23T08:43:43+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/#breadcrumb"},"inLanguage":"de","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/python-key-value-operations\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/"},{"@type":"ListItem","position":2,"name":"Key Value Operations with Python"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/de\/#website","url":"https:\/\/www.couchbase.com\/de\/","name":"Couchbase","description":"The Operational Data Platform for AI\u2122","publisher":{"@id":"https:\/\/www.couchbase.com\/de\/#organization"},"alternateName":"Couchbase, Inc.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/de\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"de"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/de\/#organization","name":"Couchbase","alternateName":"Couchbase, Inc.","url":"https:\/\/www.couchbase.com\/de\/","logo":{"@type":"ImageObject","inLanguage":"de","@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/","url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","contentUrl":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","width":1129,"height":1129,"caption":"Couchbase"},"image":{"@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Couchbase\/","https:\/\/x.com\/couchbase","https:\/\/www.youtube.com\/c\/CouchbaseServer","https:\/\/www.linkedin.com\/company\/couchbase\/","https:\/\/github.com\/couchbase\/","https:\/\/en.wikipedia.org\/wiki\/Couchbase,_Inc."],"description":"Couchbase ist ein in San Jose, Kalifornien, ans\u00e4ssiges Unternehmen f\u00fcr Datenbanksoftware, das eine operative Datenplattform f\u00fcr KI bereitstellt, die von Hunderten von globalen Unternehmen eingesetzt wird.","legalName":"Couchbase, Inc.","foundingDate":"2011-01-01"}]}},"acf":[],"permalink_manager":null,"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10349","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials"}],"about":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/types\/tutorials"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10349\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/media?parent=10349"}],"wp:term":[{"taxonomy":"tutorial-languages","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-languages?post=10349"},{"taxonomy":"tutorial-tags","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-tags?post=10349"},{"taxonomy":"tutorial-technologies","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-technologies?post=10349"},{"taxonomy":"tutorial-types","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-types?post=10349"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}