• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Client Side API Programming
  • SQL Query
  • Query with ExecuteReader and ExecuteScalar
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Server
      • Oracle
      • OleDB with Polling
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Topics
      • Publish Messages
      • Subscribe to a Topic
      • Pub/Sub Events
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Clear Cache
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • NCache Extension for SignalR Core
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

SQL Query Data in Cache

NCache provides you with the ability to query indexed cache data through its own SQL-like querying mechanism. It lets you search for keys fulfilling the given criteria and then returns the keys of the result set. You can use ExecuteReader() or ExecuteScalar() to retrieve this data.

Note

No matter which projections you use in your query, the result set will only return keys when getdata is set to false.

Using SQL Query Prerequisites

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • Searchable objects and their attributes must be indexed by either configuring indexes or defining indexes programmatically.
  • For API details, refer to: ICache, ICacheReader, ExecuteReader, QueryCommand, SearchService.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • Searchable objects and their attributes must be indexed by either configuring indexes or defining indexes programmatically.
  • For API details, refer to: Cache, CacheReader, executeReader, getSearchService, QueryCommand, executeNonQuery.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
  • For API details, refer to: Cache, CacheReader, execute_reader, get_search_service, QueryCommand, execute_non_query.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
  • For API details, refer to: Cache, CacheReader, executeReader, getSearchService, QueryCommand, executeNonQuery.
  • Create a new Console Application.
  • Make sure that the data being added is serializable.
  • Add NCache References by locating %NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
  • Ensure the searchable objects and their attributes are indexed and added in the cache using the basic NCache API.
  • Include the Alachisoft.NCache.Web.Caching namespace in your application.
Note

NCache also supports escape sequences including \n,\b, \t, and wild cards * and ? as characters for all NCache-supported SQL operators. To learn more about these escape sequences, refer to the NCache SQL-Like syntax guide.

Using ExecuteReader To Query Data in Cache

The ExecuteReader performs queries on the cache based on the user-specified criteria. It returns a list of key-value pairs in a data reader which fulfills the query criteria. This key-value pair has a cache key and its respective values.

SQL Query For Keys

Here is a query sample that returns the keys fulfilling the criteria based on ProductID.

Important

Make sure the instance of ICacheReader is always closed after execution, as it is necessary to clean the resources.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
// Items are already present in the cache
// Create a query which will be executed on the dataset
// Use the Fully Qualified Name (FQN) of your own custom class
string query = "SELECT * FROM FQN.Product WHERE ProductID > ?";

// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);

// Providing parameters for query
queryCommand.Parameters.Add("ProductID",50000);

// Executing QueryCommand through ICacheReader
ICacheReader reader = cache.SearchService.ExecuteReader(queryCommand, false, 0);


// Check if the result set is not empty
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
        string result = reader.GetValue<string>(0);
        // Perform operations using the retrieved keys
    }
}
else
{
    // Null query result set retrieved
}
// Precondition: Cache is already connected
// Items are already present in the cache

// Create a query that will be executed on the dataset
// Use the Fully Qualified Name (FQN) of your own custom class
String query = "SELECT * FROM FQN.Product WHERE ProductID > ?";

// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);

// Providing parameters for query
HashMap<String, Object> parameters = new HashMap<>();
parameters.put("ProductID", 50000);
queryCommand.getParameters().putAll(parameters);

// Executing QueryCommand through CacheReader
CacheReader cacheReader = cache.getSearchService().executeReader(queryCommand);

// Check if the result set is not empty
if (cacheReader.getFieldCount() > 0) {
    while (cacheReader.read()) {
        cacheReader.getString(0);
        // Perform operations using the retrieved keys
    }
}
# Precondition: Cache is already connected
# Items are already present in the cache

# Create a query which will be executed on the dataset
query = "SELECT * FROM FQN.Product WHERE product_id > ?"

# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)

# Providing parameters for query
parameter = {"product_id": 50000}
query_command.set_parameters(parameter)

# Executing query command through CacheReader
search_service = cache.get_search_service()
reader = search_service.execute_reader(query_command)

# Check if result set is not empty
if reader.get_field_count() > 0:
    while reader.read():
        result = reader.get_value(str, 1)
        # Perform operations using the retrieved keys
        print(result)
else:
    # None query results retrieved
    print("Query result is None")
// This is an async method
// Precondition: Cache is already connected
// Items are already present in the cache
// Create a query which will be executed on the dataset
// Use the Fully Qualified Name (FQN) of your own custom class
var query = "SELECT * FROM FQN.Product WHERE ProductID > ?";

// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);

//Providing parameters for query
let parameter = new Map();
parameter.set("ProductID", 50000);
queryCommand.setParameters(parameter);

//Executing query command through CacheReader
var searchService = await this.cache.getSearchService();
var reader = await searchService.executeReader(queryCommand, false, 0);

//Check if result set is not empty
if (reader.getFieldCount() > 0)
{
    while (reader.read())
    {
        var result = reader.getValue(0, Number());
        // Perform operations using the retrieved keys
    }
}
else
{
    // Null query results retrieved
}
string query = "SELECT Product where this.ProductID = ?";
Hashtable values = new Hashtable();
values.Add("ProductID", 1001);

ICacheReader reader = cache.ExecuteReader(query, values);
if (reader.FieldCount > 0){
    while (reader.Read()){
        Product result = (Product)reader.GetValue(1); //perform operations
        }
}
else{
    //no record exists
}
reader.Close();
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

Using the SQL IN Operator

To query the cache using this SQL-like query format with the IN operator, you can specify multiple attribute values after the IN keyword. Here's an example that retrieves ProductName and UnitsInStock from the cache having either 10, 20, or 30 UnitsInStock using ExecuteReader.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
string query = "SELECT ProductName, UnitsInStock From FQN.Product WHERE UnitsInStock IN (?, ?, ?)";

// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);

ArrayList unitsArray = new ArrayList();
unitsArray.Add(10);
unitsArray.Add(20);
unitsArray.Add(30);

queryCommand.Parameters.Add("UnitsInStock", unitsArray);

// Executing QueryCommand through ICacheReader
ICacheReader reader = cache.SearchService.ExecuteReader(queryCommand);

// Read results if result set is not empty
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
        string productName = reader.GetValue<string>("ProductName");
        int unitsInStock = reader.GetValue<int>("UnitsInStock");

        Console.WriteLine($"Product '{productName}' has {unitsInStock} Units In Stock.");
    }
}
// Items are already present in the cache

// Create a query that will be executed on the dataset
// Use the Fully Qualified Name (FQN) of your own custom class
String query = "SELECT ProductName, UnitsInStock FROM FQN.Product WHERE UnitsInStock IN (?, ?, ?)";

// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);

// Create a list for UnitsInStock values
ArrayList<Integer> unitsArray = new ArrayList<>();
unitsArray.add(10);
unitsArray.add(20);
unitsArray.add(30);

queryCommand.getParameters().put("UnitsInStock", unitsArray);

// Executing QueryCommand through CacheReader
CacheReader cacheReader = cache.getSearchService().executeReader(queryCommand);

// Read results if result set is not empty
if (cacheReader.getFieldCount() > 0) {
    while (cacheReader.read()) {
        // Get the product name
        String productName = null;
        productName = cacheReader.getValue("ProductName", String.class);


        // Get the units in stock
        Integer unitsInStock = null;
        unitsInStock = cacheReader.getValue("UnitsInStock", Integer.class);
        System.out.println("Product '" + productName + "' has " + unitsInStock + " Units In Stock.");
    }
}
query = "SELECT product_name, units_in_stock From FQN.Product WHERE units_in_stock IN (10,20,30)"

# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)

# Executing query command through CacheReader
search_service = cache.get_search_service()
reader = search_service.execute_reader(query_command)

# Check if result set is not empty
if reader.get_field_count() > 0:
    while reader.read():
        product_name = reader.get_value(str, 1)
        units_available = reader.get_value(int, 2)
        # Perform operations
        print("Name: " + str(product_name))
        print("Units: " + str(units_available))
else:
    # None query results retrieved
    print("Query result is None")
var query = "SELECT productName, UnitsInStock From FQN.Product WHERE UnitsInStock IN (?,?,?)";
// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);
//Adding Parameters
let units = [10, 15, 20, 25];
let parameter = new Map();
parameter.set("UnitsInStock", units);
queryCommand.setParameters(parameter);

// Executing QueryCommand through CacheReader
var searchService = await this.cache.getSearchService();
var reader = await searchService.executeReader(queryCommand);

// Check if result set is not empty
if (reader.getFieldCount() > 0)
{
    while (reader.read())
    {
        // Get the value of the result set
        var ProductName = reader.getValue(1, Number());
        var UnitsAvailable = reader.getValue(2, Number());
    }
}
    else
    {
    // Null query result set retrieved
}
string query = "SELECT Product where this.ProductID IN (?,?,?)";
ArrayList idList = new ArrayList();
idList.Add(1001);
idList.Add(100);
idList.Add(500);Hashtable values = new Hashtable();
values.Add("ProductID", idList);

ICacheReader reader = cache.ExecuteReader(query, values);
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
    Product result = (Product)reader.GetValue(1);    //perform operations
    }
}
else
{
    //no record exists
}
reader.Close();

Using the SQL LIKE Operator

NCache allows you to query for a specific pattern in a column through SQL-like query format using the LIKE operator. The two wildcards used with the LIKE operator are:

  1. *: Used as a substitute for zero or more characters in the string.
  2. ?: Used as a substitute for a single character in the string.

Here is an example that searches the cache and retrieves ProductName and UnitPrice using ExecuteReader.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
string query = "SELECT ProductName, UnitPrice From FQN.Product WHERE ProductName LIKE ?";

// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);

queryCommand.Parameters.Add("ProductName", "choco*");

// Executing QueryCommand through ICacheReader
ICacheReader reader = cache.SearchService.ExecuteReader(queryCommand);

// Read results if result set is not empty
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
        string productName = reader.GetValue<string>("ProductName");
        double unitPrice = reader.GetValue<double>("UnitPrice");

        Console.WriteLine($"Product: {productName}, Unit Price: {unitPrice}");
    }
}
else
{
    Console.WriteLine($"No product found having a name that starts with 'choco'.");
}
// Items are already present in the cache

// Create a query that will be executed on the dataset
// Use the Fully Qualified Name (FQN) of your own custom class
String query = "SELECT ProductName, UnitPrice FROM FQN.Product WHERE ProductName LIKE ?";

// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);

// Setting the parameter for the LIKE operator
HashMap<String, Object> parameters = new HashMap<>();
parameters.put("ProductName", "choco*");
queryCommand.getParameters().putAll(parameters);

// Executing QueryCommand through CacheReader
CacheReader cacheReader = cache.getSearchService().executeReader(queryCommand);

// Read results if result set is not empty
if (cacheReader.getFieldCount() > 0) {
    while (cacheReader.read()) {
        String productName = cacheReader.getValue("ProductName", String.class);
        Double unitPrice = cacheReader.getValue("UnitPrice", Double.class);

        System.out.println("Product: " + productName + ", Unit Price: " + unitPrice);
    }
} else {
    System.out.println("No product found having a name that starts with 'choco'.");
}
query = "SELECT * FROM FQN.Product WHERE product_name LIKE ? AND category LIKE ?"

# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)

# Providing parameters for query
parameter1 = {"product_name": "Shamp*"}
parameter2 = {"category": "Househo*"}
query_command.set_parameters(parameter1)
query_command.set_parameters(parameter2)

# Executing query command through CacheReader
search_service = cache.get_search_service()
reader = search_service.execute_reader(query_command)

# Check if result set is not empty
if reader.get_field_count() > 0:
    while reader.read():
        result = reader.get_value(str, columnname="product_name")
        # Perform operations
        print(result)
else:
    # None query results retrieved
    print("Query result is None")
var query = "SELECT * FROM FQN.Product WHERE ProductName LIKE ? AND Category LIKE ?";

// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);

// Providing parameters for query
let parameter1 = new Map();
parameter1.set("ProductName", "P*");
queryCommand.setParameters(parameter1);

let parameter2 = new Map();
parameter2.set("Category", " Beverage?");
queryCommand.setParameters(parameter2);

// Executing QueryCommand through CacheReader
var searchService = await this.cache.getSearchService();
var reader = await searchService.executeReader(queryCommand);

// Check if result set is not empty
if (reader.getFieldCount() > 0)
{
    while (reader.read())
    {
        var result = reader.getValue(1, Number());
        // Perform operations
    }
}
else
{
    // Null query result set retrieved
}
string query = "SELECT Product where this.ProductName LIKE ?";
ArrayList list = new ArrayList();
list.Add("Ch*");

Hashtable values = new Hashtable();
values.Add("ProductName", list);
ICacheReader reader = cache.ExecuteReader(query, values);
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
    Product result = (Product)reader.GetValue(1);    //perform operations
    }
}
else
{
    //no record exists
}
reader.Close();

Using the SQL GROUP BY Operator

NCache provides you with the ability to group data according to a given criteria through this SQL-like query format using the GROUP BY clause.

Important

Note that the GROUP BY clause cannot be used without an Aggregate function.

The following example retrieves all the products based on their UnitPrice and groups them according to their Category and Count.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
string query = "SELECT Category, COUNT(*) FROM FQN.Product WHERE UnitPrice < ? Group By Category";

// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);
queryCommand.Parameters.Add("UnitPrice", 100.0);

// Executing QueryCommand through ICacheReader
ICacheReader reader = cache.SearchService.ExecuteReader(queryCommand);

// Check if result set is not empty
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
        // Get the value of the result set
        string category = reader.GetValue<string>("Category");
        int count = reader.GetValue<int>("COUNT()");

        Console.WriteLine($"Category '{category}' has '{count}' affordable products.");
    }
}
else
{
    Console.WriteLine($"No category contains affordable products.");
}
// Items are already present in the cache

// Create a query that will be executed on the dataset
// Use the Fully Qualified Name (FQN) of your own custom class
String query = "SELECT Category, COUNT(*) FROM FQN.Product WHERE UnitPrice < ? GROUP BY Category";

// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);

// Setting the parameter
HashMap<String, Object> parameters = new HashMap<>();
parameters.put("UnitPrice", 100.0);
queryCommand.getParameters().putAll(parameters);

// Executing QueryCommand through CacheReader
CacheReader cacheReader = cache.getSearchService().executeReader(queryCommand);

// Read results if result set is not empty
if (cacheReader.getFieldCount() > 0) {
    while (cacheReader.read()) {

        String productName = cacheReader.getValue("Category", String.class);
        Double unitPrice = cacheReader.getValue("COUNT(*)", Double.class);


        System.out.println("Category '" + category + "' has '" + count + "' affordable products.");
    }
} else {
    System.out.println("No category contains affordable products.");
}
query = "SELECT category, COUNT(*) FROM FQN.Product WHERE unit_price > 5 Group By category"

# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)

# Executing query command through CacheReader
search_service = cache.get_search_service()
reader = search_service.execute_reader(query_command)

# Check if result set is not empty
if reader.get_field_count() > 0:
    while reader.read():
        result = reader.get_value(int, 1)
        category = reader.get_value(str, 0)
        # Perform operations
        print("Count: " + str(result))
        print("Category: " + str(category))
else:
    # None query results retrieved
    print("Query result is None")
var query = "SELECT Category, COUNT(*) FROM FQN.Product WHERE UnitPrice > ? Group By Category";

// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);

//Adding Parameters
let parameter = new Map();
parameter.set("UnitPrice", 10);
queryCommand.setParameters(parameter);

// Executing QueryCommand through CacheReader
var searchService = await this.cache.getSearchService();
var reader = await searchService.executeReader(queryCommand);

// Check if result set is not empty
if (reader.getFieldCount() > 0)
{
    while (reader.read())
    {
        // Get the value of the result set
        var result =  reader.getValue(1, ncache.JsonDataType.Object);
        var category =  reader.getValue(0, Number());
    }
}
else
{
    // Null query result set retrieved
}
string query = "SELECT this.Category, COUNT(Product) WHERE this.ProductID > ? GROUP BY this.Category";

Hashtable values = new Hashtable();
values.Add("ProductID", 5);
ICacheReader reader = cache.ExecuteReader(query, values);
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
    object category = reader.GetOrdinal("Category");    object result = reader.GetValue(1);    //perform operations
    }
}
else
{
    //no record exists
}
reader.Close();

Using the SQL ORDER BY Operator

NCache provides you with the ability to sort the data in ascending or descending order, according to the given criteria, through SQL-like query format using the ORDER BY clause. The following example retrieves ProductName and UnitPrice, where ProductName is greater than 100 and sorts them in descending order using ExecuteReader.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
string query = "SELECT ProductName,UnitPrice FROM FQN.Product WHERE UnitPrice < ? ORDER BY UnitPrice DESC";

// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);
queryCommand.Parameters.Add("UnitPrice", 100.0);

// Executing QueryCommand through ICacheReader
ICacheReader reader = cache.SearchService.ExecuteReader(queryCommand);

// Check if result set is not empty
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
        // Get the value of the result set
        string productName = reader.GetValue<string>("ProductName");
        string unitPrice = reader.GetValue<string>("UnitPrice");

        Console.WriteLine($"Product: {productName}, Unit Price: {unitPrice}");
    }
}
else
{
    Console.WriteLine($"No products found which are cheaper than 100.");
}
// Items are already present in the cache

// Create a query that will be executed on the dataset
// Use the Fully Qualified Name (FQN) of your own custom class
String query = "SELECT ProductName, UnitPrice FROM FQN.Product WHERE UnitPrice < ? ORDER BY UnitPrice DESC";

// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);

// Setting the parameter
HashMap<String, Object> parameters = new HashMap<>();
parameters.put("UnitPrice", 100.0);
queryCommand.getParameters().putAll(parameters);

// Executing QueryCommand through CacheReader
CacheReader cacheReader = cache.getSearchService().executeReader(queryCommand);

// Read results if result set is not empty
if (cacheReader.getFieldCount() > 0) {
    while (cacheReader.read()) {

        String productName = cacheReader.getValue("ProductName", String.class);
        Double unitPrice = cacheReader.getValue("UnitPrice", Double.class);

        System.out.println("Product: " + productName + ", Unit Price: " + unitPrice);
    }
} else {
    System.out.println("No products found which are cheaper than 100.");
}
query = "SELECT * FROM FQN.Product WHERE unit_price > 100 ORDER BY units_in_stock DESC"

# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)

# Executing query command through CacheReader
search_service = cache.get_search_service()
reader = search_service.execute_reader(query_command)

# Check if result set is not empty
if reader.get_field_count() > 0:
    while reader.read():
        result = reader.get_value(int, columnname="units_in_stock")
        # Perform operations
        print("Units: " + str(result))
else:
    # None query results retrieved
    print("Query result is None")
var query = "SELECT * FROM FQN.Product WHERE UnitPrice > ? ORDER BY UnitsInStock DESC";

// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);

//Providing parameters for query
let parameter = new Map();
parameter.set("UnitPrice", 100);
queryCommand.setParameters(parameter);

// Executing QueryCommand through CacheReader
var searchService = await this.cache.getSearchService();
var reader = await searchService.executeReader(queryCommand);

// Check if result set is not empty
if (reader.getFieldCount() > 0)
{
    while (reader.read())
    {
        // Get the value of the result set
        var result = reader.getValue(1, Number());
    }
}
else
{
    // Null query result set retrieved
}
string query = "SELECT Product ORDER BY by this.ProductID = ?";

//OR

string query = "SELECT Product WHERE this.Category = ? ORDER BY this.Category";

Hashtable values = new Hashtable();
values.Add("ProductID", 1001);

ICacheReader reader = cache.ExecuteReader(query, values);
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {     Product result = (Product)reader.GetValue(1);
        //perform operations
    }
}
else
{
    //no record exists
}
reader.Close();

Using the SQL DateTime Operator

NCache provides you with ease of searching the cache by providing parameters in various formats. You can use many functions in a single query for faster cache searching. DateTime can be used in your query to search the cache concerning a particular date or time. For more details on date formats, please refer to the Microsoft DateTime Struct Docs.

Note

Make sure that you specify the date in the correct format.

The following example executes a query that searches for all the orders in the cache whose OrderDate is as specified using ExecuteReader.

  • .NET
  • Java
  • Python
  • Node.js
string query = "SELECT OrderID FROM FQN.Order WHERE OrderDate = ?";

// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);

// Define order date
DateTime orderDate = new DateTime(2022, 01, 01);

// Providing parameters to query
queryCommand.Parameters.Add("OrderDate", orderDate);

// Executing QueryCommand through ICacheReader
ICacheReader reader = cache.SearchService.ExecuteReader(queryCommand);

// Read results if result set is not empty
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
        // Get the value of the result set
        int orderID = reader.GetValue<int>("OrderID");
        Console.WriteLine($"Order: {orderID} was placed on 1st January, 2022.");
    }
}
else
{
    Console.WriteLine($"No orders were placed on 1st January 2022.");
}
// Items are already present in the cache

// Create a query that will be executed on the dataset
// Use the Fully Qualified Name (FQN) of your own custom class
String query = "SELECT OrderID FROM FQN.Order WHERE OrderDate = ?";

// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);

// Define order date in Java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date orderDate;
orderDate = sdf.parse("2022-01-01");


// Providing parameters to query
HashMap<String, Object> parameters = new HashMap<>();
parameters.put("OrderDate", orderDate);
queryCommand.getParameters().putAll(parameters);

// Executing QueryCommand through CacheReader
CacheReader cacheReader = cache.getSearchService().executeReader(queryCommand);

// Read results if result set is not empty
if (cacheReader.getFieldCount() > 0) {
    while (cacheReader.read()) {

        int orderID = cacheReader.getInt(cacheReader.getOrdinal("OrderID"));
        System.out.println("Order: " + orderID + " was placed on 1st January, 2022.");
    }
} else {
    System.out.println("No orders were placed on 1st January 2022.");
}
query = "SELECT * FROM FQN.Order WHERE order_date < ?"

# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)

# Providing parameters for query
parameter = {"order_date": datetime.strptime('Jan 1 2022  1:33PM', '%b %d %Y %I:%M%p')}
query_command.set_parameters(parameter)

# Executing query command through CacheReader
search_service = cache.get_search_service()
reader = search_service.execute_reader(query_command)

# Check if result set is not empty
if reader.get_field_count() > 0:
    while reader.read():
        order_id = reader.get_value(int, 1)
        # Perform operations
        print("Order ID: " + str(order_id))
else:
    # None query results retrieved
    print("Query result is None")
// Use the Fully Qualified Name (FQN) of your own custom class
var query = "SELECT * FROM FQN.Order WHERE OrderDate < ?";

// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);

// Providing parameters to query
var date = new Date("2021-02-10");
let map = new Map();
var parameters = map.set("orderDate", date);
queryCommand.setParameters(parameters);

// Executing QueryCommand through CacheReader
var searchService = await this.cache.getSearchService();
var reader = await searchService.executeReader(queryCommand);

// Check if the result set is not empty
if (reader.getFieldCount() > 0)
{
    while (reader.read())
    {
        // Get the value of the result set
        var result = reader.getValue(1, Number());

        // Perform operations
    }
}
else
{
    // Null query result set retrieved
}

Using the SQL Logical Operator

NCache provides the user with the AND, OR, and NOT logical operators to specify more than one condition after the operator in these queries through this SQL-like query format. Here's an example showing how to use the combination of AND and OR operators in a single query within the WHERE clause using ExecuteReader.

  • .NET
  • Java
  • Python
  • Node.js
string query = "SELECT * FROM FQN.Product WHERE (Category = ? AND UnitsInStock > ?) OR (Category = ? AND UnitPrice > ?)";

// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);

// Adding Parameters
ArrayList categoryList = new ArrayList();
categoryList.Add("Beverages");
categoryList.Add("Produce");
queryCommand.Parameters.Add("Category", categoryList);
queryCommand.Parameters.Add("UnitsInStock", 100);
queryCommand.Parameters.Add("UnitPrice", 100);

// Executing QueryCommand through ICacheReader
ICacheReader reader = _cache.SearchService.ExecuteReader(queryCommand);

// Check if the result set is not empty
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
        // Get the value of the result set
        string result = reader.GetValue<string>("ProductID");
    }
}
else
{
    // Null query result set retrieved
}

catch (OperationFailedException ex)

if (ex.ErrorCode == NCacheErrorCodes.INCORRECT_FORMAT)
{
    // Make sure that the query format is correct
}
else
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
// Items are already present in the cache

// Create a query that will be executed on the dataset
// Use the Fully Qualified Name (FQN) of your own custom class
String query = "SELECT * FROM FQN.Product WHERE (Category = ? AND UnitsInStock > ?) OR (Category = ? AND UnitPrice > ?)";

// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);

// Adding Parameters
ArrayList<String> categoryList = new ArrayList<>();
categoryList.add("Beverages");
categoryList.add("Produce");

HashMap<String, Object> parameters = new HashMap<>();
parameters.put("Category1", categoryList.get(0));
parameters.put("Category2", categoryList.get(1));
parameters.put("UnitsInStock", 100);
parameters.put("UnitPrice", 100.0);
queryCommand.getParameters().putAll(parameters);

// Executing QueryCommand through CacheReader
CacheReader cacheReader = cache.getSearchService().executeReader(queryCommand);

// Check if the result set is not empty
if (cacheReader.getFieldCount() > 0) {
    while (cacheReader.read()) {
        // Get the value of the result set
        String result = cacheReader.getString(cacheReader.getOrdinal("ProductID"));
    }
} else {
    // Null query result set retrieved
}
query = "SELECT * FROM FQN.Product WHERE (category = 'Beverages' AND units_in_stock > 0) OR (category = 'Produce' AND unit_price > 100)"

# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)

# Executing query command through CacheReader
search_service = cache.get_search_service()
reader = search_service.execute_reader(query_command)

# Check if result set is not empty
if reader.get_field_count() > 0:
    while reader.read():
        product_id = reader.get_value(str, 1)
        # Perform operations
        print("Product ID: " + str(product_id))
else:
    # None query results retrieved
    print("Query result is None")
var query = "SELECT * FROM FQN.Product WHERE (Category = ? AND UnitsInStock > ?) OR (Category = ? AND UnitPrice > ?)";

// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);

//Add parameters
let categoryList = Array();
categoryList.push("Produce");
categoryList.push("Beverages");
let parameter = new Map();
parameter.set("Category", categories);
parameter.set("UnitsInStock", 100);
parameter.set("UnitPrice", 100);
queryCommand.setParameters(parameter);

// Executing QueryCommand through CacheReader
var searchService = await this.cache.getSearchService();
var reader = await searchService.executeReader(queryCommand);

// Check if the result set is not empty
if (reader.getFieldCount() > 0)
{
    while (reader.read())
    {
        // Get the value of the result set
        var result = reader.getValue(1, Number());
    }
}
else
{
    // Null query result set retrieved
}

Using ExecuteScalar to Search Data in Cache

The ExecuteScalar executes user queries and returns the first column of the first row in the result set, any additional columns or rows are ignored.

  • .NET
  • Java
string query = "SELECT AVG(UnitPrice) FROM FQN.Product WHERE Category = ?";

// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);
queryCommand.Parameters.Add("Category", "Beverages");

// Executing QueryCommand through ICacheReader
decimal average = (decimal)cache.SearchService.ExecuteScalar(queryCommand);

Console.WriteLine($"Average price of Beverages is {average}.");
// Create a query that will be executed on the dataset
String query = "SELECT AVG(UnitPrice) FROM FQN.Product WHERE Category = ?";

// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);
queryCommand.getParameters().put("Category", "Beverages");

// Executing QueryCommand through ExecuteScalar
Double average = cache.getSearchService().executeScalar(queryCommand, Double.class);

if (average != null) {
    System.out.println("Average price of Beverages is " + average + ".");
} else {
    System.out.println("No data found for Beverages.");
}

Additional Resources

NCache provides sample application for SQL Queries on GitHub.

See Also

.NET: Alachisoft.NCache.Client.Services namespace.
Java: com.alachisoft.ncache.runtime.caching namespace.
Python: ncache.client.services class.
Node.js: Cache class.

In This Article
  • Using SQL Query Prerequisites
  • Using ExecuteReader To Query Data in Cache
    • SQL Query For Keys
    • Using the SQL IN Operator
    • Using the SQL LIKE Operator
    • Using the SQL GROUP BY Operator
    • Using the SQL ORDER BY Operator
    • Using the SQL DateTime Operator
  • Using the SQL Logical Operator
  • Using ExecuteScalar to Search Data in Cache
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top