| endpoint | create |
|---|---|
| lang | python |
| es_version | 9.3 |
| client | elasticsearch==9.3.0 |
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.
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:
raiseTo 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']}")