Read, update and delete documents
Source(name).Doc gives you CRUD on single documents. Every document has an id, returned by create.
const { Doc } = sdk.asAdmin().Insights().Source('Orders')
Create and remember the id
const { result } = await Doc.create({ orderId: 'ORD-3001', status: 'paid', total: 19.9 })
const id = result.id
With { return: true } the response contains the stored document:
const { result: { id, doc } } = await Doc.create({ orderId: 'ORD-3002', total: 9.5 }, { return: true })
Read
const { result } = await Doc.get(id)
// { id: '…', doc: { orderId: 'ORD-3001', … } }
Unknown ids answer 404 doc/not-found.
Update
// Replace the document completely
await Doc.update(id, { orderId: 'ORD-3001', status: 'shipped', total: 19.9 })
// Merge fields into the existing raw document
await Doc.update(id, { status: 'delivered' }, { update: true })
update: true performs a shallow merge over the raw document and re-indexes it. Without it, the document is replaced.
Delete
await Doc.delete(id) // 204
await Doc.delete(id, { return: true }) // { id, doc }
The document is removed from both the raw and the main index.
Look up across sources
Sources([...]).Docs.find finds documents with equal field values across several sources at once.
const insights = sdk.asAdmin().Insights()
const { result } = await insights.Sources(['Orders', 'Sensor readings']).Docs.find(
{ status: 'paid' },
{ size: 20 }
)
// { total: 12, Orders: [ … ], 'Sensor readings': [] }
The size is capped at 1000. Only equality filters are available. For anything else use aggregate per source.
Update or insert by business key
Documents do not have a lookup by field. Two ways to get "upsert":
- Set the source's duplicate control to field on your key (such as
orderId) and useDoc.create. Sending the same key again updates the document. - Search for the id first:
const source = sdk.asAdmin().Insights().Source('Orders')
const { result } = await source.aggregate({
size: 1,
filter: [{ term: { 'orderId.keyword': 'ORD-3001' } }],
fields: ['orderId']
})
const id = result.rows[0]?._id
Option 1 is simpler and atomic.