Querying with Select and Conditions

The examples in this section query a document store and return specific fields from documents that have specific conditions.

For more information about how to specify query conditions in OJAI, see Query Conditions in OJAI Applications.

Note: You can improve the performance of queries with conditions by using secondary indexes. See Queries that Benefit from Secondary Indexes for more details.

The following example shows how to return the name, address.zipCode, age, and phoneNumber fields from documents that have address.zipCode equal to 95196. It uses the Query.select and Query.where methods, specifying the query condition as a JSON string.

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

public class OJAI_009_FindQueryWithSelectAndCondition {

  public static void main(final 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");

    // Build an OJAI query with the condition specified as a JSON string
    final Query query = connection.newQuery()
        .select("name", "address.zipCode").select("age").select("phoneNumbers[0]")
        .where("{\"$eq\": {\"address.zipCode\": 95196}}")
        .build();

    // fetch all OJAI Documents from this store
    final DocumentStream stream = store.find(query);

    for (final Document userDocument : stream) {
      // Print the OJAI Document
      System.out.println(userDocument.asJsonString());
    }

    // 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 example shows how to return the name, address.zipCode, age, and phoneNumber fields from documents that have address.zipCode equal to 95196. It uses an OJAI query and condition.

/*
 * 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) => {
    // Create an OJAI query
    const query = {"$select": ["name",
        "adress.zipCode",
        "age",
        "phoneNumbers[0]"],
      "$where": {"$eq": {"address.zipCode": 95196}}};
    // fetch OJAI Documents by query
    return store.find(query);
  })
  .then((queryResult) => {
    queryResult.on('data', (document) => {
      // Print OJAI Documents from document stream
      console.log(document);
    });
    queryResult.on('end', () => {
      // close the OJAI connection
      connection.close();
    });
  });

The following example shows how to return the name, address.zipCode, age, and phoneNumber fields from documents that have address.zipCode equal to 95196. It uses an OJAI query and condition.

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

# Create an OJAI query
query = {"$select": ["name",
                     "adress.zipCode",
                     "age",
                     "phoneNumbers[0]"],
         "$where": {"$eq": {"address.zipCode": 95196}}}

# options for find request
options = {
    'ojai.mapr.query.result-as-document': True
    }

# fetch OJAI Documents by query
query_result = store.find(query,
                          options=options)

# Print OJAI Documents from document stream
for doc in query_result:
    print(doc.as_dictionary())

# close the OJAI connection
connection.close()

The following two dbshell commands are equivalent to the code examples. See dbshell find or findbyid for more details about the syntax dbshell provides.

find /demo_table --query {
   "$select":["name","address.zipCode","age","phoneNumber[0]"],
   "$where":{"$eq":{"address.zipCode":95196}}
}

find /demo_table 
   --fields name,address.zipCode,age,phoneNumber[0]
   --where {"$eq":{"address.zipCode":95196}}  
Note: The commands are shown split across multiple lines for readability. When using dbshell, you must enter them in a single line.