Examples: Updating JSON Documents
This section contains sample code that updates a JSON document in a HPE Ezmeral Data Fabric Database JSON table using an OJAI mutation. It also shows the HPE Ezmeral Data Fabric Database Shell syntax for updating documents.
See Using OJAI Mutation Syntax for more details about OJAI mutations.
The following code is available at OJAI_012_UpdateDocument.java. It does the following:
- Finds a document using the DocumentStore.findById method
- Creates a DocumentMutation that updates a field
- Updates the document by calling the DocumentStore.update method
/** * Copyright (c) 2017 MapR, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mapr.ojai.examples; import org.ojai.store.Connection; import org.ojai.store.DocumentMutation; import org.ojai.store.DocumentStore; import org.ojai.store.DriverManager; public class OJAI_012_UpdateDocument { public static void main(String[] args) { System.out.println("==== Start Application ==="); // Create an OJAI connection to MapR cluster final Connection connection = DriverManager.getConnection("ojai:mapr:"); // Get an instance of OJAI DocumentStore final DocumentStore store = connection.getStore("/demo_table"); String docId = "user0002"; // Print the document before update System.out.println( "\t"+ store.findById(docId).getMap("address").toString() ); // Create a DocumentMutation to update the zipCode field DocumentMutation mutation = connection.newMutation() .set("address.zipCode", 95196L); System.out.println("\tUpdating document "+ docId); // Update the Document with '_id' = "user0002" store.update(docId, mutation); // Print the document after update System.out.println( "\t"+ store.findById(docId).getMap("address").toString() ); // Close this instance of OJAI DocumentStore store.close(); // close the OJAI connection and release any resources held by the connection connection.close(); System.out.println("==== End Application ==="); } }
The following code is available at OJAI_011_UpdateDocument.js. It does the following:
- Finds a document using the DocumentStore.findById method
- Creates an OJAI mutation that updates a field
- Updates the document by calling the DocumentStore.update method
/* * Copyright (c) 2018 MapR, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const { ConnectionManager } = require('node-maprdb'); const connectionString = 'localhost:5678?' + 'auth=basic;' + 'user=mapr;' + 'password=mapr;' + 'ssl=true;' + 'sslCA=/opt/mapr/conf/ssl_truststore.pem;' + 'sslTargetNameOverride=node1.mapr.com'; let connection; let store; const docId = 'user0002'; // Create a connection to data access server ConnectionManager.getConnection(connectionString) .then((conn) => { connection = conn; // Get a store return connection.getStore('/demo_table'); }) .then((newStore) => { // Get a store and assign it as a DocumentStore object store = newStore; // Find the document before update return store.findById(docId); }) .then((docBeforeUpdate) => { // Print the document before update console.log(`Document with id ${docId} before update`) console.log(docBeforeUpdate); const mutation = {'$put': {'address.zipCode': 95196}}; return store.update(docId, mutation); }) .then(() => { // Find the document after update return store.findById(docId); }) .then((docAfterUpdate) => { // Print the document after update console.log(`Document with id ${docId} before update`) console.log(docAfterUpdate); });
The following code is available at OJAI_012_CheckAndUpdateDocument.js. It does the following:
- Finds a document using the DocumentStore.findById method
- Creates an OJAI mutation that updates a field
- Creates an OJAI condition to apply in the check and update
- Performs the check and update on the document by calling the DocumentStore.checkAndUpdate method
/* * Copyright (c) 2018 MapR, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const { ConnectionManager } = require('node-maprdb'); const connectionString = 'localhost:5678?' + 'auth=basic;' + 'user=mapr;' + 'password=mapr;' + 'ssl=true;' + 'sslCA=/opt/mapr/conf/ssl_truststore.pem;' + 'sslTargetNameOverride=node1.mapr.com'; let connection; let store; const docId = 'user0002'; // Create a connection to data access server ConnectionManager.getConnection(connectionString) .then((conn) => { connection = conn; // Get a store return connection.getStore('/demo_table'); }) .then((newStore) => { // Get a store and assign it as a DocumentStore object store = newStore; // Find the document before update return store.findById(docId); }) .then((docBeforeUpdate) => { // Print the document before update console.log(`Document with id ${docId} before update`) console.log(docBeforeUpdate); const mutation = {'$put': {'address.zipCode': 95196}}; const condition = {'$eq': {'address.street': '320 Blossom Hill Road'}} return store.checkAndUpdate(docId, mutation, condition); }) .then((updateResult) => { console.log(updateResult); // Find the document after update return store.findById(docId); }) .then((docAfterUpdate) => { // Print the document after update console.log(`Document with id ${docId} before update`) console.log(docAfterUpdate); });
The following code is available at 012_update_document.py. It does the following:
- Finds a document using the DocumentStore.find_by_id method
- Creates an OJAI mutation that updates a field
- Updates the document by calling the DocumentStore.update method
from mapr.ojai.storage.ConnectionFactory import ConnectionFactory # Create a connection to data access server connection_str = "localhost:5678?auth=basic;user=mapr;password=mapr;" \ "ssl=true;" \ "sslCA=/opt/mapr/conf/ssl_truststore.pem;" \ "sslTargetNameOverride=node1.mapr.com" connection = ConnectionFactory.get_connection(connection_str=connection_str) # Get a store and assign it as a DocumentStore object store = connection.get_store('/demo_table') doc_id = 'user0002' # Print the document before update document_before_update = store.find_by_id(doc_id) print("Document with id {0} before update".format(doc_id)) print(document_before_update) # Create mutation to update the zipCode field mutation = {'$set': {'address.zipCode': 95196}} # Execute update store.update(_id=doc_id, mutation=mutation) document_after_update = store.find_by_id(doc_id) print('Document with id {0} after update'.format(doc_id)) print(document_after_update)
The following code is available at 013_check_and_update_document.py. It does the
following:
- Finds a document using the DocumentStore.find_by_id method
- Creates an OJAI mutation that updates a field
- Creates an OJAI condition to apply in the check and update
- Performs the check and update on the document by calling the DocumentStore.check_and_update method
from mapr.ojai.storage.ConnectionFactory import ConnectionFactory # Create a connection to data access server connection_str = "localhost:5678?auth=basic;user=mapr;password=mapr;" \ "ssl=true;" \ "sslCA=/opt/mapr/conf/ssl_truststore.pem;" \ "sslTargetNameOverride=node1.mapr.com" connection = ConnectionFactory.get_connection(connection_str=connection_str) # Get a store and assign it as a DocumentStore object store = connection.get_store('/demo_table') doc_id = 'user0001' # Print the document before update document_before_update = store.find_by_id(doc_id) print("Document with id {0} before update".format(doc_id)) print(document_before_update) # Create mutation to update the zipCode field mutation = {'$put': {'address.zipCode': 99999}} # Create condition condition = {'$eq': {'address.street': '320 Blossom Hill Road'}} # Execute check_and_update. # Returns True if condition True and document was updated. update_result = store.check_and_update(_id=doc_id, mutation=mutation, query_condition=condition) print(update_result) document_after_update = store.find_by_id(doc_id) print('Document with id {0} after update'.format(doc_id)) print(document_after_update)
The following dbshell command is equivalent to the code examples. See dbshell update for more information and examples.
# mapr dbshell
maprdb root:> update /demo_table --id user002 --m {"$set":{"address.zipCode":95196}}
The following code is available at 012_UpdateDocument.cs. It does the following:
- Finds a document using the
DocumentStore.FindById
method to print the document before update. - Creates an OJAI mutation that updates a field.
- Updates the document by calling the
DocumentStore.Update
method.
using System; using MapRDB.Driver; public class UpdateDocument { public void UpdateDocument() { // Create a connection to data access server var connectionStr = $"localhost:5678?auth=basic;" + $"user=mapr;" + $"password=mapr;" + $"ssl=true;" + $"sslCA=/opt/mapr/conf/ssl_truststore.pem;" + $"sslTargetNameOverride=node1.mapr.com"; var connection = ConnectionFactory.CreateConnection(connectionStr); // Get a store and assign it as a DocumentStore object var store = connection.GetStore("/demo_table"); var docId = "user0002"; // Print the document before update var documentBeforeUpdate = store.FindById(docId); Console.WriteLine($"Document with id {docId} before update:"); Console.WriteLine(documentBeforeUpdate); // Create mutation to update the zipCode field var mutation = connection.NewDocumentMutation().Set("address.zipCode", (long)95196); // Execute update store.Update(docId, mutation); // Print the document after update var documentAfterUpdate = store.FindById(docId); Console.WriteLine($"Document with id {docId} after update:"); Console.WriteLine(documentAfterUpdate); // Close the OJAI connection connection.Close(); } }
The following code is available at 013_CheckAndUpdateDocument.cs. It does the
following:
- Finds a document using the
DocumentStore.FindById
method to print the document before update. - Creates an OJAI mutation that updates a field.
- Creates an OJAI condition to apply in the check and update.
- Performs the check and update on the document by calling the
DocumentStore.CheckAndUpdate
method.
using System; using MapRDB.Driver; using MapRDB.Driver.Ojai; public class CheckAndUpdateDocument { public void CheckAndUpdateDocument() { // Create a connection to data access server var connectionStr = $"localhost:5678?auth=basic;" + $"user=mapr;" + $"password=mapr;" + $"ssl=true;" + $"sslCA=/opt/mapr/conf/ssl_truststore.pem;" + $"sslTargetNameOverride=node1.mapr.com"; var connection = ConnectionFactory.CreateConnection(connectionStr); // Get a store and assign it as a DocumentStore object var store = connection.GetStore("/demo_table"); var docId = "user0001"; // Print the document before update var documentBeforeUpdate = store.FindById(docId); Console.WriteLine($"Document with id {docId} before update:"); Console.WriteLine(documentBeforeUpdate); // Create mutation to update the zipCode field var mutation = connection.NewDocumentMutation().SetOrReplace("address.zipCode", 99999); // Create condition var condition = connection .NewQueryCondition() .Is("address.street", QueryOp.EQUAL, "320 Blossom Hill Road") .Close() .Build(); // Execute CheckAndUpdate. // Returns True if condition True and document was updated var updateResult = store.CheckAndUpdate(docId, condition, mutation); Console.WriteLine(updateResult); // Print the document after update var documentAfterUpdate = store.FindById(docId); Console.WriteLine($"Document with id {docId} after update:"); Console.WriteLine(documentAfterUpdate); // Close the OJAI connection connection.Close(); } }
The following code is available at 012_update_document.go. It does the following:
- Finds a document using the
DocumentStore.FindByIdString
function to print the document before update - Creates an OJAI mutation that updates a field
- Updates the document by calling the
DocumentStore.Update
function
package main import ( "fmt" client "github.com/mapr/private-maprdb-go-client" ) func main() { // Create connection string connectionString := "192.168.33.11:5678?" + "auth=basic;" + "user=mapr;" + "password=mapr;" + "ssl=true;" + "sslCA=/opt/mapr/conf/ssl_truststore.pem;" + "sslTargetNameOverride=node1.cluster.com" storeName := "/demo_table" documentId := "user0002" // Create a connection to DAG connection, err := client.MakeConnection(connectionString) if err != nil { panic(err) } // Get a store and assign it as a DocumentStore struct store, err := connection.GetStore(storeName) if err != nil { panic(err) } // Print the document before update documentBeforeUpdate, err := store.FindByIdString(documentId) if err != nil { panic(err) } fmt.Printf("Document with id %v before update.\n %v", documentId, documentBeforeUpdate.AsJsonString()) // Create mutation to update the zipCode field mutation := map[string]interface{}{"$set": map[string]interface{}{"address.zipCode": 95196}} // Execute update err = store.Update(client.BosiFromString(documentId), client.MosmFromMap(mutation)) if err != nil { panic(err) } // Print the document after update documentAfterUpdate, err := store.FindByIdString(documentId) if err != nil { panic(err) } fmt.Printf("Document with id %v after update.\n %v", documentId, documentAfterUpdate.AsJsonString()) // Close connection connection.Close() }
The following code is available at 013_check_and_update_document.go. It does the
following:
- Finds a document using the DocumentStore.FindByIdString function to print the document before update
- Creates an OJAI mutation that updates a field
- Creates an OJAI condition to apply in the check and update
- Performs the check and update on the document by calling the
DocumentStore.CheckAndUpdate
function
package main import ( "fmt" client "github.com/mapr/private-maprdb-go-client" ) func main() { // Create connection string connectionString := "192.168.33.11:5678?" + "auth=basic;" + "user=mapr;" + "password=mapr;" + "ssl=true;" + "sslCA=/opt/mapr/conf/ssl_truststore.pem;" + "sslTargetNameOverride=node1.cluster.com" storeName := "/demo_table" documentId := "user0001" // Create a connection to DAG connection, err := client.MakeConnection(connectionString) if err != nil { panic(err) } // Get a store and assign it as a DocumentStore struct store, err := connection.GetStore(storeName) if err != nil { panic(err) } // Print the document before update documentBeforeUpdate, err := store.FindByIdString(documentId) if err != nil { panic(err) } fmt.Printf("Document with id %v before update.\n %v\n", documentId, documentBeforeUpdate.AsJsonString()) // Create mutation to update the zipCode field mutation := map[string]interface{}{"$put": map[string]interface{}{"address.zipCode": 99999}} // Create condition condition := map[string]interface{}{"$eq": map[string]interface{}{"address.street": "320 Blossom Hill Road"}} // Execute update // Returns True if condition True and document was updated. res, err := store.CheckAndUpdate( client.BosiFromString(documentId), client.MoscFromMap(condition), client.MosmFromMap(mutation)) if err != nil { panic(err) } // Print the document after update documentAfterUpdate, err := store.FindByIdString(documentId) if err != nil { panic(err) } fmt.Printf("Update result: %v.\nDocument with id %v after update.\n %v\n", res, documentId, documentAfterUpdate.AsJsonString()) // Close connection connection.Close() }