• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Try Free
Show / Hide Table of Contents

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 of the the requirement.

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 the ICacheReader type of instance.

You can query an item having a specific tag as explained below.

Prerequisites

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
  • 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.
  • 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: Cache , CacheReader, executeReader, QueryCommand, getSearchService.
  • 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: Cache, 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.
  • Custom classes/searchable attributes must be indexed as explained in Configuring Query Indexes.
  • For API details refer to: Cache, executeReader, QueryCommand, CacheReader, getSearchService.
  • 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: Cache, CacheReader, execute_reader, get_search_service, QueryCommand.

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 VIP Customers using the SQL query.

Note

Use fully-qualified name of the class Customer e.g. Data.Customer

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
try
{
    // Pre-conditions: Cache is already connected

    // Create a query for search
    // Use the Fully Qualified Name (FQN) of your own custom class   
    string query = "Select CustomerID,ContactName FROM 
    Alachisoft.NCache.Samples.Data.Customer WHERE $Tag$ = ?";

    // Use QueryCommand for query execution
    var queryCommand = new QueryCommand(query);
    queryCommand.Parameters.Add("$Tag$", "VIP Customers");

    // Executing Query
    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
            string customerID = reader.GetValue<string>
            ("CustomerID");
            string contactName = reader.GetValue<string>
            ("ContactName");

            Console.WriteLine($"Customer '{contactName}' having 
            ID '{customerID}' is a VIP Customer.");
        }
    }
    else
    {
        Console.WriteLine($"No VIP Customers 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
{
    // 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
}
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
    }
}
// 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
Warning

Providing Null tag value for the query will throw an ArgumentNullException or NullPointerException. In order to get more detail on NCache queries please refer to the SQL Reference for NCache section.

Note

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

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

Back to top Copyright © 2017 Alachisoft