Examples: Inserting JSON Documents

This section contains sample code that inserts a JSON document into a MapR Database JSON table. It also shows the MapR Database Shell syntax for inserting documents.

The following code is available at OJAI_002_GetStoreAndInsertDocuments.java.

After you create the JSON document from a JavaBean, call the DocumentStore.insertOrReplace method to insert the document into MapR Database.

/**
 * 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.Document;
import org.ojai.store.Connection;
import org.ojai.store.DocumentStore;
import org.ojai.store.DriverManager;

import com.mapr.ojai.examples.data.Dataset;
import com.mapr.ojai.examples.data.User;

public class OJAI_002_GetStoreAndInsertDocuments {

  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
    final DocumentStore store = connection.getStore("/demo_table");

    for (final User someUser : Dataset.users) {
      // Create an OJAI Document form the Java bean (there are other ways too)
      final Document userDocument = connection.newDocument(someUser);

      System.out.println("\t inserting "+ userDocument.getId());

      // insert the OJAI Document into the DocumentStore
      store.insertOrReplace(userDocument);
    }

    // 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_002_GetStoreAndInsertDocuments.js.

The following code creates a list of JSON objects and then calls the DocumentStore.insertOrReplace method to insert the document into MapR Database.

/*
 * 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;

// Create a connection to data access server
ConnectionManager.getConnection(connectionString)
  .then((conn) => {
    connection = conn;
    // Get a store
    return connection.getStore('/demo_table');
  })
  .then((store) => {
    const documentList = [{'_id': 'user0000',
      'age': 35,
      'firstName': 'John',
      'lastName': 'Doe',
      'address': {
        'street': '350 Hoger Way',
        'city': 'San Jose',
        'state': 'CA',
        'zipCode': 95134
      },
      'phoneNumbers': [
        {'areaCode': 555, 'number': 5555555},
        {'areaCode': '555', 'number': '555-5556'}]
    },
      {'_id': 'user0001',
        'age': 26,
        'firstName': 'Jane',
        'lastName': 'Dupont',
        'address': {
          'street': '320 Blossom Hill Road',
          'city': 'San Jose',
          'state': 'CA',
          'zipCode': 95196
        },
        'phoneNumbers': [
          {'areaCode': 555, 'number': 5553827},
          {'areaCode': '555', 'number': '555-6289'}]
      },
      {'_id': 'user0002',
        'age': 45,
        'firstName': 'Simon',
        'lastName': 'Davis',
        'address': {
          'street': '38 De Mattei Court',
          'city': 'San Jose',
          'state': 'CA',
          'zipCode': 95142
        },
        'phoneNumbers': [
          {'areaCode': 555, 'number': 5425639},
          {'areaCode': '555', 'number': '542-5656'}]
      }
    ];
    const promiseList = documentList.map((doc) => {
      // Print the OJAI Document
      console.log(JSON.stringify(doc));
      // Insert the OJAI Document into the DocumentStore
      return store.insertOrReplace(doc);
    });
    return Promise.all(promiseList);
  })
  .then(() => {
    // close the OJAI connection
    connection.close();
  });

The following code is available at 002_get_store_and_insert_documents.py.

The following code creates a list of JSON dictionary objects, creates Document objects, and calls the DocumentStore.insert_or_replace method to insert the documents into MapR Database.

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
if connection.is_store_exists('/demo_table'):
    store = connection.get_store('/demo_table')
else:
    store = connection.create_store('/demo_table')

document_list = [{'_id': 'user0000',
                  'age': 35,
                  'firstName': 'John',
                  'lastName': 'Doe',
                  'address': {
                      'street': '350 Hoger Way',
                      'city': 'San Jose',
                      'state': 'CA',
                      'zipCode': 95134
                  },
                  'phoneNumbers': [
                      {'areaCode': 555, 'number': 5555555},
                      {'areaCode': '555', 'number': '555-5556'}]
                  },
                 {'_id': 'user0001',
                  'age': 26,
                  'firstName': 'Jane',
                  'lastName': 'Dupont',
                  'address': {
                      'street': '320 Blossom Hill Road',
                      'city': 'San Jose',
                      'state': 'CA',
                      'zipCode': 95196
                  },
                  'phoneNumbers': [
                      {'areaCode': 555, 'number': 5553827},
                      {'areaCode': '555', 'number': '555-6289'}]
                  },
                 {'_id': 'user0002',
                  'age': 45,
                  'firstName': 'Simon',
                  'lastName': 'Davis',
                  'address': {
                      'street': '38 De Mattei Court',
                      'city': 'San Jose',
                      'state': 'CA',
                      'zipCode': 95142
                  },
                  'phoneNumbers': [
                      {'areaCode': 555, 'number': 5425639},
                      {'areaCode': '555', 'number': '542-5656'}]
                  }
                 ]

for doc_dict in document_list:
    # Create new document from json_document
    new_document = connection.new_document(dictionary=doc_dict)
    # Print the OJAI Document
    print(new_document.as_json_str())

    # Insert the OJAI Document into the DocumentStore
    store.insert_or_replace(new_document)

# close the OJAI connection
connection.close()

The following shows the syntax to insert a document with MapR Database Shell. See dbshell insert for more information and examples.

# mapr dbshell
maprdb root:> 
          
// Syntax for inserting a document using the document ID
maprdb root:> insert <table path> --value '{"_id": "<row-key", < table field >}'
          
// Syntax for inserting a document using document value
maprdb root:> insert <table path> --id <row-key> --value '{"_id": "<row-key", < table field >}'