Search Data with Named Tags using SQL
You can also use Object Queries to retrieve items from the cache by specifying Named Tags as your query criteria. The query, when executed, will search 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
- 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.
- Custom classes/searchable attributes must be indexed as explained in Configuring Query Indexes.
- For API details, refer to: ICache, ICacheReader, QueryCommand, ExecuteReader, SearchService.
The following example retrieves the Customers from the cache where the values of Named Tags match the provided value.
// 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 Alachisoft.NCache.Samples.Data.Customer WHERE VIP_Membership_Discount = 0.12 ";
// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);
// 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");
}
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.