Sample OJAI Code for Creating JSON Documents

The sample code in this section shows you how to create a JSON document.

The code is available at OJAI_001_GetConnectionCreateDocument.java.

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

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

public class OJAI_001_GetConnectionCreateDocument {

  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:");

    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);

      // Print the OJAI Document
      System.out.println(
          userDocument.asJsonString(           // serialize the OJAI Document to JSON string
              new JsonOptions().pretty()       // in pretty format
      ));      
    }

    // close the OJAI connection and release any resources held by the connection
    connection.close();

    System.out.println("==== End Application ===");
  }

}

The code is available at OJAI_001_GetConnectionCreateDocument.js.

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

// Create a connection to data access server
ConnectionManager.getConnection(connectionString)
  .then((connection) => {
    // create new document as a JavaScript object
    const newDocument = {
      "_id": "id001",
      "name": "Joe",
      "age": 50,
      "address": {
        "street": "555 Moon Way",
        "city": "Gotham"
      }
    };

    // Print the OJAI Document
    console.log(JSON.stringify(newDocument));

    // close the OJAI connection and release any resources held by the connection
    connection.close();
  });

The code is available at 001_get_connection_create_document.py.

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)

# Json string or json dictionary
json_dict = {"_id": "id001",
             "name": "Joe",
             "age": 50,
             "address": {
                 "street": "555 Moon Way",
                 "city": "Gotham"}
             }

# Create new document from json_document
new_document = connection.new_document(dictionary=json_dict)

# Print the OJAI Document
print(new_document.as_json_str())

# close the OJAI connection
connection.close()

The code is available at 001_GetConnectionCreateDocument.cs.

using System;
using MapRDB.Driver;

public class GetConnectionCreateDocument
{
    public void GetConnectionCreateDocument()
    {
        // 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);

        // Json string
        var jsonStr =
            @"{" +
                @"""_id"":""id001""," +
                @"""name"":""Joe""," +
                @"""age"":{""$numberInt"":""50""}," +
                @"""address"":" +
                    @"{" +
                        @"""street"":""555 Moon Way""," +
                        @"""city"":""Gotham""" +
                    @"}" +
            @"}";

        // Create a document from jsonStr
        var documentJson = connection.NewDocument(jsonStr);

        // Print the OJAI Document
        Console.WriteLine(documentJson.ToJsonString());

        // Create new document with the same fields using constructor
        var documentConstructed = connection.NewDocument()
            .SetID("id001")
            .Set("name", "Joe")
            .Set("age", 50)
            .Set("address.street", "555 Moon Way")
            .Set("address.city", "Gotham");

        // Print the OJAI Document
        Console.WriteLine(documentConstructed.ToJsonString());

        // Close the OJAI connection
        connection.Close();
    }
}

The code is available at 001_get_connection_create_document.go.

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"

	// Create a connection to data access server
	connection, err := client.MakeConnection(connectionString)
	if err != nil {
		panic(err)
	}

	// Json string or map from which the Document will be created
	newMap := map[string]interface{}{
		"_id":  "id001",
		"name": "Joe",
		"age":  50,
		"address": map[string]interface{}{
			"street": "555 Moon Way",
			"city":   "Gotham",
		},
	}

	// Create new document from json_document
	newDocument := connection.CreateDocumentFromMap(newMap)

	// Print the new OJAI Document
	fmt.Println(newDocument.AsJsonString())

	// Close connection
	connection.Close()
}