Skip to main content

Insert or Replace Documents

To insert one or more documents in Tigris, you can use Insert or Replace API.

Example collection

The first step is to set up the collection object. All the operations on the collection are performed through this collection object.

catalogs := tigris.GetCollection[Catalog](catalogdb)

Insert a Single Document

Insert API can be used to insert one or more documents into the collection. Since the id field is marked as autoGenerate, you don't need to specify a value for it and Tigris will automatically generate it for you.

_, err := catalogs.Insert(ctx,
&Catalog{Name: "fiona handbag", Price: 99.9, Brand: "michael kors", Labels: "purses", Popularity: 8})
if err != nil {
// handle error
}

The insert API maintains the uniqueness of the field marked as the primary key, for example, the field id in the example above. If the document with the same primary key value already exists in the collection, the operation will fail by throwing an HTTP status code 409 with the message "duplicate key value, violates key constraint"

Insert Multiple Documents

Similar, to a single row insert, you can also insert multiple documents by passing an array of documents.

_, err := catalogs.Insert(ctx,
&Catalog{Name: "tote bag", Price: 49, Brand: "coach", Labels: "handbags", Popularity: 9},
&Catalog{Name: "sling bag", Price: 75, Brand: "coach", Labels: "purses", Popularity: 9})
if err != nil {
// handle error
}

Upsert a Single Document

Insert or replace operation can be used to insert a new document or replace an existing document with the same primary key value. This API is useful when there is no need for a uniqueness check on the primary key, and it is fine to replace documents that already exist. The following is an example when the row with an id 3 already exists so the below operation will replace the document with the newly provided data.

_, err := catalogs.InsertOrReplace(ctx,
&Catalog{Id: 3, Name: "sling bag", Price: 99, Brand: "coach", Labels: "purses", Popularity: 9})
if err != nil {
// handle error
}

Upsert Multiple Documents

As the API can also be used when the document doesn't exist. The following is an example of when these two documents are inserted because there are no corresponding ids.

_, err := catalogs.InsertOrReplace(ctx,
&Catalog{Name: "sneakers shoes", Price: 40, Brand: "adidas", Labels: "shoes", Popularity: 10},
&Catalog{Name: "running shoes", Price: 89, Brand: "coach", Labels: "shoes", Popularity: 10})
if err != nil {
// handle error
}