You can use Object Queries to retrieve items from the distributed cache by specifying Named Tags as your query criteria. NCache provides a high-performance SQL-like querying mechanism that searches the cache according to the Named Tag provided in the SQL query. Before searching, make sure that the item is added to the cache with the Named Tags. Refer to the Add Items with Named Tags section to get details on creating and adding Named Tags.
Prerequisites
Before using the NCache Client-side APIs, ensure that the following prerequisites are fulfilled:
- Add the following Maven dependencies for your Java client application in
pom.xml file:
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<!--for NCache Enterprise-->
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- Install either of the following NuGet packages in your .NET client application:
- Enterprise:
Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
- 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.
- Include the
Alachisoft.NCache.Web.Caching namespace in your application.
- To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.
The following example retrieves the Customers from the cache where the values of Named Tags match the provided value.
try
{
// Precondition: Cache is already connected
// Create an SQL Query with the specified criteria
// Make sure to use the Fully Qualified Name for custom class
string query = "SELECT CustomerID,ContactName FROM FQN.Customer WHERE VIP_Membership_Discount = 0.12 ";
// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);https://file+.vscode-resource.vscode-cdn.net/d%3A/Repos/Documentation/NCache-ENT/prog-guide/sql-with-namedtags.md#tab/net1
// Executing the Query
ICacheReader reader = cache.SearchService.ExecuteReader(queryCommand);
// Read results if the result set is not empty
if (reader.FieldCount > 0)
{
while (reader.Read())
{
// Get the value of the result set
string customerID = reader.GetValue<string>("CustomerID");
string customerName = reader.GetValue<string>("ContactName");
Console.WriteLine($"Customer '{customerName}' with ID '{customerID}' has VIP membership discount.");
}
}
else
{
Console.WriteLine($"No VIP members found");
}
}
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
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
try
{
// Precondition: Cache is already connected
// Create an SQL Query with the specified criteria
// Make sure to use the Fully Qualified Name for custom class
// Create an SQL Query with the specified criteria
String query = "SELECT customerID,contactName FROM FQN.Customer WHERE VIP_Membership_Discount = 0.12";
// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);
// Executing the Query
CacheReader reader = cache.getSearchService().executeReader(queryCommand);
// Read results if the result set is not empty
if (reader.getFieldCount() > 0)
{
while (reader.read()) {
// Get the value of the result set
String customerID = reader.getValue("customerID", String.class);
String customerName = reader.getValue("contactName", String.class);
System.out.println("Customer '" + customerName + "' with ID '" + customerID + "' has VIP membership discount.");
}
}
else
{
System.out.println("No VIP members found");
}
}
catch (OperationFailedException ex)
{
if (ex.getErrorCode() == 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
}
}
catch (Exception ex)
{
// Any generic exception like IllegalArgumentException or NullPointerException
}
try:
# Precondition: Cache is already connected
# Items are already present in the cache with Named Tags
# Custom class is query indexed through the NCache Management Center or config.ncconf
# Create SQL Query with the specified criteria
# Make sure to use the Fully Qualified Name(FQN)
query = "SELECT $Value$ FROM FQN.Customer WHERE VIP_Membership_Discount = 0.12 "
# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)
parameter = {"VIP_Membership_Discount": 0.12}
query_command.set_parameters(parameter)
# Executing query
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():
# Get the value of the result set
result = reader.get_value(Product, 1)
else:
# None query result set retrieved
print("Query result is None")
except Exception as error:
# Exception can occur due to:
# Connection Failures
# Operation Timeout
# Operation during state transfer
print("An error occurred:", str(error))
try
{
// This is an async method
// Precondition: Cache is already connected
// Items are already present in the cache with Named Tags
// Custom class is query indexed through the NCache Management Center or config.ncconf
// Create SQL Query with the specified criteria
// Make sure to use the Fully Qualified Name (FQN)
var query = "SELECT $Value$ FROM FQN.Customer WHERE VIP_Membership_Discount = 0.12 ";
// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);
let parameter = new Map();
parameter.set("FlashSaleDiscount", 0.5);
queryCommand.setParameters(parameter);
// Executing query
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);
}
}
else
{
// Null query result set retrieved
}
}
catch (error)
{
// Handle errors
}
// Using NCache Enterprise 4.9.1
try
{
// Precondition: Cache is already connected
// Create an SQL Query with the specified criteria
// Make sure to use the Fully Qualified Name for custom class
string query = "SELECT FQN.Customer WHERE this.VIP_Membership_Discount = ?";
// Create a parameter list using Hashtable
Hashtable values = new Hashtable();
values.Add("VIP_Membership_Discount", 0.12);
// Executing the query
ICacheReader queryResult = cache.ExecuteReader(query, values, true);
// Read results if the result set is not empty
if (queryResult.FieldCount > 0)
{
while (queryResult.Read())
{
// Get the value of the result set
string customerID = (string)queryResult["CustomerID"];
string customerName = (string)queryResult["ContactName"];
Console.WriteLine($"Customer '{customerName}' with ID '{customerID}' has VIP membership discount.");
}
}
else
{
Console.WriteLine("No VIP members found");
}
}
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
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Warning
If you have multiple applications that share the same cache and all of them are supposed to add Named Tags, then make sure that the same Named Tags have homogenous data types. For example, if one client is adding a Named Tag CustomerID with a string data type, then all other clients should add values of CustomerID only in a string format for the same cache.
To get more detail on object queries please refer to the SQL Reference for NCache section.
Additional Resources
NCache provides a sample application for Tags on GitHub.
See Also
.NET: Alachisoft.NCache.Runtime.Caching namespace.
Java: com.alachisoft.ncache.runtime.caching namespace.
Node.js: NamedTagsDictionary class.
Python: ncache.runtime.caching class.