Search Data in Cache with SQL and Named Tags
Object queries can also be used to retrieve items from cache with your query criteria being Named Tags. The query when executed will search the cache according to the Named Tag provided in the SQL query.
Pre-Requisites
- Include the following namespace in your application:
Alachisoft.NCache.Web.Caching
Alachisoft.NCache.Runtime
- The application must be connected to cache before performing the operation.
- Cache must be running.
- Make sure that the data being added is serializable.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
The following example retrieves the Products from the cache where the values of Named Tags match the provided value. Make sure that item is added in the cache with the Named Tags. Refer to the Add Items with Named Tags section to get a detail on creating and adding Named Tags.
Note
Use fully-qualified name of the class Product e.g. Data.Product
.
try
{
// Pre-condition: Cache is already connected
// Create SQL Query with the specified criteria
// Make sure to use the fully qualified class name
string query = "SELECT Data.Product WHERE this.FlashSaleDiscount = ?";
// Create a new hashtable
Hashtable values = new Hashtable();
// Add the name(s) and value(s) of Named Tags in the hashtable for
// query searching values
values.Add("FlashSaleDiscount", 0.5);
// Passing true will return keys and items in result set
// Passing false will return only keys
// ExecuteReader processes the queryValue and sends the result to the client
using (ICacheReader queryResult = cache.ExecuteReader(query, values))
{
// QueryResult contains all the keys and values related to both tags.
if (queryResult.FieldCount > 0)
{
while (queryResult.Read())
{
// Perform operation according to your logic
}
}
else
{
// No data containing the named tag(s) exist
}
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation performed during state transfer
// Operation Timeout
}
catch (Exception ex)
{
// Any other generic exception like ArgumentNullException or ArgumentException
}
Recommendation: 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 are sharing the same cache and all of them are supposed to add Named Tags, then make sure that same Named Tags have homogenous data types. E.g. If one client is adding Named Tag ProductID with String data type then all other clients should add values of ProductID only in String format for same cache.
In order to get more detail on object queries please refer to the SQL Reference for NCache section.
See Also
Using Tags
Data Expiration
Add Items with NamedTags
SQL Delete with NamedTags