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.

TigrisCollection<Catalog> catalog = tigrisDatabase.getCollection(Catalog.class);

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.

Catalog product = new Catalog("fiona handbag", 99.9, "michael kors", "purses", 8);

InsertResponse<Catalog> response = catalog.insert(product);

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.

Catalog handBag = new Catalog("fiona handbag", 99.9, "michael kors", "purses", 8);
Catalog slingBag = new Catalog("sling bag", 75, "coach", "purses", 9);

catalog.insert(Arrays.asList(handBag, slingBag));

Replace 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.

Catalog product = new Catalog("fiona handbag", 99.9, "michael kors", "purses", 8);
// set primary key
product.setId(3);

InsertOrReplaceResponse<Catalog> response = catalog.insert(product);

Replace 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.

Catalog sneakers = new Catalog("sneakers shoes", 40, "adidas", "shoes", 10);
Catalog runningShoes = new Catalog("running shoes", 89, "coach", "shoes", 10);

catalog.insert(Arrays.asList(sneakers, runningShoes));