Skip to content

Latest commit

 

History

History
60 lines (49 loc) · 1.29 KB

File metadata and controls

60 lines (49 loc) · 1.29 KB
endpoint create
lang python
es_version 9.3
client elasticsearch==9.3.0

Elasticsearch 9.3 create endpoint (Python example)

Use client.create() to index a document only if it does not already exist. This guarantees no accidental overwrites.

response = client.create(
    index="products",
    id="prod-1",
    document={
        "name": "Espresso Machine Pro",
        "brand": "BrewMaster",
        "price": 899.99,
        "category": "appliances",
        "in_stock": True,
        "rating": 4.7,
    },
)
print(f"{response['result']} document {response['_id']}")

Unlike index, this will never replace an existing document.

Handling conflicts

If a document with the same id already exists, a ConflictError is raised:

from elastic_transport import ApiError

try:
    client.create(index="products", id="prod-1", document={"name": "Duplicate"})
except ApiError as e:
    if e.status_code == 409:
        print(f"Document prod-1 already exists")
    else:
        raise

Auto-generated IDs

To let Elasticsearch assign a unique ID, use index with op_type="create" instead:

response = client.index(
    index="products",
    document={"name": "New Product", "price": 49.99},
    op_type="create",
)
print(f"Created with ID: {response['_id']}")