Examples: Updating JSON Documents

This section contains sample code that updates a JSON document in a MapR Database JSON table using an OJAI mutation. It also shows the MapR 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:

/**
 * 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:
/*
 * 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:
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:
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}}