| endpoint | create |
|---|---|
| lang | javascript |
| es_version | 9.3 |
| client | @elastic/elasticsearch@9.3.0 |
Use client.create() to index a document only if it does not already
exist. This guarantees no accidental overwrites.
const response = await 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,
},
});
console.log(`${response.result} document ${response._id}`);Unlike index, this will never replace an existing document.
If a document with the same id already exists, a ResponseError
with status 409 is thrown:
try {
await client.create({ index: "products", id: "prod-1", document: { name: "Duplicate" } });
} catch (err) {
if (err.statusCode === 409) {
console.log("Document prod-1 already exists");
} else {
throw err;
}
}Omit the id parameter to let Elasticsearch assign a unique ID:
const response = await client.index({
index: "products",
document: { name: "New Product", price: 49.99 },
op_type: "create",
});
console.log(`Created with ID: ${response._id}`);