Skip to content

Latest commit

 

History

History
59 lines (49 loc) · 1.29 KB

File metadata and controls

59 lines (49 loc) · 1.29 KB
endpoint create
lang javascript
es_version 9.3
client @elastic/elasticsearch@9.3.0

Elasticsearch 9.3 create endpoint (JavaScript example)

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.

Handling conflicts

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;
  }
}

Auto-generated IDs

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}`);