Search Tag Data in Cache with SQL
Note
This feature is only available in NCache Enterprise Edition.
NCache provides object queries through which you can search and delete result sets based on the criteria given to the query. To retrieve the data according to your specified criteria, NCache provides you with an extension of SQL. It lets you search the data in your cache based on the criteria on which requirement is based.
A special keyword $Tag$
is used to specify that the condition under consideration uses tags. A query with the searching criteria is executed using ExecuteReader
.
ExecuteReader
processes the query on the server side and then sends the result in chunks (as a dictionary containing keys and values) to the client in the tabular form to ICacheReader
type of instance.
Similar to the retrieve and delete method,the three strategies of querying items on tags (i.e. by a specific tag, any tag or all tags)
can also be adopted for these queries which are explained below.
Prerequisites
- Install the following NuGet package in your application:
- Include the following namespace in your application:
Alachisoft.NCache.Client
Alachisoft.NCache.Runtime.Caching
Alachisoft.NCache.Runtime.Exceptions
- Cache must be running.
- The application must be connected to cache before performing the operation.
- Custom classes/searchable attributes must be indexed as explained in Configuring Query Indexes.
- Make sure that the data being added is serializable.
- For API details refer to: ICache, ICacheReader, QueryCommand, ExecuteReader
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
- To handle any unseen exceptions, refer to the Troubleshooting section.
- Add the following Maven dependencies in your
pom.xml
file:
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- Import the following packages in your application:
import com.alachisoft.ncache.runtime.exceptions.*;
import com.alachisoft.ncache.client.*;
- Cache must be running.
- The application must be connected to cache before performing the operation.
- Custom classes/searchable attributes must be indexed as explained in Configuring Query Indexes.
- Make sure that the data being added is serializable.
- For API details refer to: Cache
, CacheReader, executeReader
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
- To handle any unseen exceptions, refer to the Troubleshooting section.
- Install and include the following module in your application:
- Enterprise:
const ncache = require('ncache-client')
- Cache must be running.
- The application must be connected to cache before performing the operation.
- Custom classes/searchable attributes must be indexed as explained in Configuring Query Indexes.
- For API details refer to: Cache, executeReader
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
- To handle any unseen exceptions, refer to the Troubleshooting section.
- Install the NCache Python client by executing the following command:
# Enterprise Client
pip install ncache-client
- Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
- Import the NCache module in your application.
- Cache must be running.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
- To handle any unseen exceptions, refer to the Troubleshooting section.
- Add the following Maven dependencies in your
pom.xml
file:
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<artifactId>ncache-scala-client</artifactId>
<version>x.x.x</version>
</dependency>
- Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
- Import the following packages in your application:
import com.alachisoft.ncache.scala.client.*;
- Cache must be running.
- The application must be connected to cache before performing the operation.
- 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.
- To handle any unseen exceptions, refer to the Troubleshooting section.
Search Data in Cache with One Tag
Using object queries, a single tag can be used to retrieve all the items associated with that tag.
Syntax
Following example retrieves all the items associated with the tag Beverages using the SQL query.
Warning
Providing Null
tag value for the query will throw an ArgumentNullException or NullPointerException.
try
{
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Search for items with tags
// Use the Fully Qualified Name (FQN) of your own custom class
string query = "Select $Value$ FROM FQN.Customer WHERE $Tag$ = ?";
// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);
queryCommand.Parameters.Add("$Tag$", "Important Customers");
// Executing query
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
Customer result = reader.GetValue<Customer>(1);
}
}
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
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
try
{
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Search for items with tags
// Use the Fully Qualified Name (FQN) of your own custom class
string query = "Select $Value$ FROM FQN.Customer WHERE $Tag$ = ?";
// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);
queryCommand.getParameters().put("$Tag$", "Important Customers");
// Executing query
CacheReader reader = cache.getSearchService().executeReader(queryCommand);
// Check if result set is not empty
if (reader.getFieldCount() > 0)
{
while (reader.read())
{
// Get the value of the result set
Customer result = reader.getValue(1,Customer.class);
}
}
else
{
// Null query result set retrieved
}
}
catch (OperationFailedException ex) {
if (ex.getErrorCode() == NCacheErrorCodes.INCORRECT_FORMAT)
{
// Make sure the query format is correct
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation performed during state transfer
// Operation Timeout
}
}
catch (Exception ex)
{
// Any generic exception like NullPointerException or IllegalArgumentException
}
// This is an async method
try
{
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Search for items with tags
// Use the Fully Qualified Name (FQN) of your own custom class
var query = "Select $Value$ FROM FQN.Customer WHERE $Tag$ = ?";
// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);
queryCommand.getParameters().set("$Tag$", "Important Customers");
// 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);
}
}
else
{
// Null query result set retrieved
}
}
catch(error)
{
// Handle errors
}
try:
# Pre-conditions: Cache is already connected
# Items are already present in the cache with tags
# Custom class is query indexed through NCache Web Manager or config.ncconf
# Search for items with tags
# Use the Fully Qualified Name(FQN) of your own custom class
query = "Select $Value$ FROM FQN.Customer WHERE $Tag$ = ?"
# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)
query_command.set_parameters({"$Tag$": "Important Customers"})
# 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(Customer, 1)
else:
# None query result set retrieved
print("Result set is None")
except Exception as exp:
# Handle errors
try {
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Search for items with tags
// Use the Fully Qualified Name (FQN) of your own custom class
val query = "Select $Value$ FROM FQN.Customer WHERE $Tag$ = ?"
// Use QueryCommand for query execution
val queryCommand = new QueryCommand(query)
queryCommand.setParameters(Map("$Tag$" -> "Important Customers"))
// Executing query
val reader = cache.getSearchService.executeReader(queryCommand)
// Check if result set is not empty
if (reader.getFieldCount > 0) {
while (reader.read) {
// Get the value of the result set
val result = reader.getValue(1, classOf[Customer])
}
}
else {
// Null query result set retrieved
}
}
catch {
case exception: Exception => {
// Handle any errors
}
}
Search Data in Cache with ANY Tag
Using object queries, if multiple tags are provided in the form of a list, items associated with ANY of the tags from the list are retrieved.
Syntax
Following example retrieves all the items associated with any of the tags from the list using the SQL query.
Warning
Providing Null
tag value for the query will throw an ArgumentNullException or NullPointerException.
Note
Use fully-qualified name of the class Customer e.g. Data.Customer
.
try
{
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Finding items associated with any of the tags
// Make sure to use the Fully Qualified Name (FQN)
string query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ IN (?,?,?)";
// If multiple tags are used for query criteria, add tags in an array list
var queryTagList = new ArrayList();
queryTagList.Add("Important Customers");
queryTagList.Add("East Coast Customers");
queryTagList.Add("West Coast Customers");
// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);
queryCommand.Parameters.Add("$Tag$", queryTagList);
// Executing query
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
Customer result = reader.GetValue<Customer>(1);
}
}
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
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
try
{
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Finding items associated with any of the tags
// Make sure to use the Fully Qualified Name (FQN)
string query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ IN (?,?,?)";
// If multiple tags are used for query criteria, add tags in an array list
ArrayList queryTagList = new ArrayList();
queryTagList.add("Important Customers");
queryTagList.add("East Coast Customers");
queryTagList.add("West Coast Customers");
// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);
queryCommand.getParameters().put("$Tag$", queryTagList);
// Executing query
CacheReader reader = cache.getSearchService().executeReader(queryCommand);
// Check if result set is not empty
if (reader.getFieldCount() > 0)
{
while (reader.read())
{
// Get the value of the result set
Customer result = reader.getValue(1,Customer.class);
}
}
else
{
// Null query result set retrieved
}
}
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 NullPointerException or IllegalArgumentException
}
// This is an async method
try
{
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Finding items associated with any of the tags
// Make sure to use the Fully Qualified Name (FQN)
var query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ IN (?,?,?)";
// If multiple tags are used for query criteria, add tags in an array list
var queryTagList = [];
queryTagList.push("Important Customers");
queryTagList.push("East Coast Customers");
queryTagList.push("West Coast Customers");
// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);
queryCommand.getParameters().set("$Tag$", queryTagList);
// 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);
}
}
else
{
// Null query result set retrieved
}
}
catch(error)
{
/// Handle errors
}
try:
# Pre-conditions: Cache is already connected
# Items are already present in the cache with tags
# Custom class is query indexed through NCache Web Manager or config.ncconf
# Search for items with tags
# Use the Fully Qualified Name(FQN) of your own custom class
query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ IN (?,?,?)"
# If multiple tags are used for query criteria, add tags in a list
query_tag_list = [
"Important Customers",
"East Coast Customers",
"West Coast Customers"
]
# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)
query_command.set_parameters({"$Tag$": query_tag_list})
# 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(Customer, 1)
else:
# None query result set retrieved
print("Result set is None")
except Exception as exp:
# Handle errors
try {
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Finding items associated with any of the tags
// Make sure to use the Fully Qualified Name (FQN)
val query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ IN (?,?,?)"
// If multiple tags are used for query criteria, add tags in an array list
var queryTagList: List[Tag] = List()
queryTagList = Tag("Important Customers") :: queryTagList
queryTagList = Tag("East Coast Customers") :: queryTagList
queryTagList = Tag("West Coast Customers") :: queryTagList
// Use QueryCommand for query execution
val queryCommand = new QueryCommand(query)
queryCommand.setParameters(Map("$Tag$" -> queryTagList))
// Executing query
val reader = cache.getSearchService.executeReader(queryCommand)
// Check if result set is not empty
if (reader.getFieldCount > 0) {
while (reader.read) {
// Get the value of the result set
val result = reader.getValue(1, classOf[Customer])
}
}
else {
// Null query result set retrieved
}
}
catch {
case exception: Exception => {
// Handle any errors
}
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Using object queries, if multiple tags are provided in the form of a list, items associated with ALL of the tags from the list are retrieved. It means that an item is not retrieved unless it contains all the tags in the list.
Syntax
Following example retrieves all the items associated with all of the tags from the list using the SQL query.
Warning
Providing Null
tag value for the query will throw an ArgumentNullException or NullPointerException.
Note
Use fully-qualified name of the class Customer e.g. Data.Customer
.
try
{
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Finding items associated with any of the tags
// Make sure to use the Fully Qualified Name (FQN)
string query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ = ? AND $Tag$ = ?";
// If multiple tags are used for query criteria, add tags in an array list
var queryTagList = new ArrayList();
queryTagList.Add("Important Customers");
queryTagList.Add("East Coast Customers");
// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);
queryCommand.Parameters.Add("$Tag$", queryTagList);
// Execute query
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
Customer result = reader.GetValue<Customer>(1);
}
}
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
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
try
{
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Finding items associated with any of the tags
// Make sure to use the Fully Qualified Name (FQN)
string query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ = ? AND $Tag$ = ?";
// If multiple tags are used for query criteria, add tags in an array list
ArrayList queryTagList = new ArrayList();
queryTagList.add("Important Customers");
queryTagList.add("East Coast Customers");
// Use QueryCommand for query execution
QueryCommand queryCommand = new QueryCommand(query);
queryCommand.getParameters().put("$Tag$", queryTagList);
// Execute query
CacheReader reader = cache.getSearchService().executeReader(queryCommand);
// Check if result set is not empty
if (reader.getFieldCount() > 0)
{
while (reader.read())
{
// Get the value of the result set
Customer result = reader.getValue(1,Customer.class);
}
}
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
}
}
catch (Exception ex)
{
// Any generic exception like NullPointerException or IllegalArgumentException
}
// This is an async method
try
{
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Finding items associated with any of the tags
// Make sure to use the Fully Qualified Name (FQN)
var query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ = ? AND $Tag$ = ?";
// If multiple tags are used for query criteria, add tags in an array list
var queryTagList = [];
queryTagList.push("Important Customers");
queryTagList.push("East Coast Customers");
queryTagList.push("West Coast Customers");
// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);
queryCommand.getParameters().set("$Tag$", queryTagList);
// 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);
}
}
else
{
// Null query result set retrieved
}
}
catch(error)
{
// Handle errors
}
try:
# Pre-conditions: Cache is already connected
# Items are already present in the cache with tags
# Custom class is query indexed through NCache Web Manager or config.ncconf
# Search for items with tags
# Use the Fully Qualified Name(FQN) of your own custom class
query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ = ? AND $Tag$ = ?"
# If multiple tags are used for query criteria, add tags in a list
query_tag_list = [
"Important Customers",
"East Coast Customers",
"West Coast Customers"
]
# Use QueryCommand for query execution
query_command = ncache.QueryCommand(query)
query_command.set_parameters({"$Tag$": query_tag_list})
# 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(Customer, 1)
else:
# None query result set retrieved
print("Result set is None")
except Exception as exp:
# Handle errors
try {
// Pre-conditions: Cache is already connected
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Web Manager or config.ncconf
// Finding items associated with any of the tags
// Make sure to use the Fully Qualified Name (FQN)
val query = "SELECT $Value$ FROM FQN.Customer WHERE $Tag$ = ? AND $Tag$ = ?"
// If multiple tags are used for query criteria, add tags in an array list
var queryTagList: List[Tag] = List()
queryTagList = Tag("Important Customers") :: queryTagList
queryTagList = Tag("East Coast Customers") :: queryTagList
// Use QueryCommand for query execution
val queryCommand = new QueryCommand(query)
queryCommand.setParameters(Map("$Tag$" -> queryTagList))
// Execute query
val reader = cache.getSearchService.executeReader(queryCommand)
// Check if result set is not empty
if (reader.getFieldCount > 0) {
while (reader.read) {
// Get the value of the result set
val result = reader.getValue(1, classOf[Customer])
}
}
else {
// Null query result set retrieved
}
}
catch {
case exception: Exception => {
// Handle any errors
}
}
In order to get more detail on NCache queries please refer to the SQL Reference for NCache section.
Additional Resources
NCache provides sample application for Tags on GitHub.
See Also
Using Groups
Add/Update Data in Cache with Tags
Retrieve Cache Data with Tags
Remove Cache Data with Tags
Delete Tag Data from Cache with SQL
Named Tags