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

SQL Like Operator: Syntax and Usage

Note

This feature is only available in NCache Enterprise Edition.

NCache allows you to search for a specific pattern in a column through SQL like query format using LIKE operator.

The two wildcards used with the LIKE operator are:

  1. *: Used as a substitute for zero or more characters in the string.

  2. ?: Used as a substitute for a single character in the string.

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.
  • Searchable objects and their attributes must be indexed by either configuring indexes or defining indexes programmatically.
  • The cache must be running.
  • The application must be connected to cache before performing the operation.
  • For API details, refer to: ICache, ICacheReader, ExecuteReader, SearchService, QueryCommand, ExecuteNonQuery.
  • 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.
  • 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.
  • Searchable objects and their attributes must be indexed by either configuring indexes or defining indexes programmatically.
  • For API details, refer to: Cache, CacheReader, executeReader, getSearchService, QueryCommand, executeNonQuery.
  • 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.
  • Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
  • For API details, refer to: Cache, CacheReader, SearchService, QueryCommand.
  • 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.
  • Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
  • For API details, refer to: Cache, CacheReader, executeReader, getSearchService, QueryCommand, executeNonQuery.
  • 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.
  • Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
  • For API details, refer to: Cache, CacheReader, execute_reader, get_search_service, QueryCommand, execute_non_query.

Syntax

Here's an example that searches the cache and retrieves all the products that have their ProductName starting with the letters Shamp, and Category starting with the letters Househo using ExecuteReader.

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
try
{
    // Pre-condition: Cache is already connected
    // Items are already present in the cache
    // Specify the query with the specified criteria.
    // Use the Fully Qualified Name (FQN) of your own custom class
    string query = "SELECT * FROM FQN.Product WHERE ProductName LIKE ? AND Category LIKE ?";

    // Use QueryCommand for query execution
    var queryCommand = new QueryCommand(query);

    // Providing parameters for query
    queryCommand.Parameters.Add("ProductName", "P*");
    queryCommand.Parameters.Add("Category", "Beverage?");

    // Executing QueryCommand through ICacheReader
    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
        string result = reader.GetValue<string>("ProductID");
        // Perform operations
      }
    }
    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-condition: Cache is already connected
    // Items are already present in the cache
    // Specify the query with the specified criteria.
    // Use the Fully Qualified Name (FQN) of your own custom class
    String query = "SELECT * FROM FQN.Product WHERE ProductName LIKE ? AND Category LIKE ?";

    // Use QueryCommand for query execution
    QueryCommand queryCommand = new QueryCommand(query);

    // Providing parameters for query
    queryCommand.getParameters().put("ProductName", "P*");
    queryCommand.getParameters().put("Category", " Beverage?");

    // Executing QueryCommand through CacheReader
    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
            String result = reader.getValue("productID", String.class);

            // Perform operations
        }
    }
    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 Timeout
        // Operation performed during state transfer
    }

}
catch (Exception ex)
{
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Pre-condition: Cache is already connected
    // Items are already present in the cache
    // Specify the query with the specified criteria.
    // Use the Fully Qualified Name (FQN) of your own custom class
    val query = "SELECT * FROM FQN.Product WHERE ProductName LIKE ? AND Category LIKE ?"

    // Use QueryCommand for query execution
    val queryCommand = new QueryCommand(query)

    // Providing parameters for query
    queryCommand.setParameters(Map("ProductName" -> "Shamp*", "Category" -> "Househo*"))

    // Executing QueryCommand through CacheReader
    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("productID", classOf[String])
      // Perform operations
    }
    else {
      // Null query result set retrieved
    }
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
//This is an async method
try
{
    // Pre-condition: Cache is already connected
    // Items are already present in the cache
    // Specify the query with the specified criteria.
    // Use the Fully Qualified Name (FQN) of your own custom class
    var query = "SELECT * FROM FQN.Product WHERE ProductName LIKE ? AND Category LIKE ?";

    // Use QueryCommand for query execution
    var queryCommand = new ncache.QueryCommand(query);

    // Providing parameters for query
    let parameter1 = new Map();
    parameter1.set("ProductName", "P*");
    queryCommand.setParameters(parameter1);

    let parameter2 = new Map();
    parameter2.set("Category", " Beverage?");
    queryCommand.setParameters(parameter2);

    // Executing QueryCommand through CacheReader
    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())
        {
            var result = reader.getValue(1, Number());
            // Perform operations
        }
    }
    else
    {
        // Null query result set retrieved
    }
}
catch (error)
{
    // Handle errors
}
try:
    # Pre-condition: Cache is already connected
    # Items are already present in the cache

    # Create a query which will be executed on the data set
    query = "SELECT * FROM FQN.Product WHERE product_name LIKE ? AND category LIKE ?"

    # Use QueryCommand for query execution
    query_command = ncache.QueryCommand(query)

    # Providing parameters for query
    parameter1 = {"product_name": "Shamp*"}
    parameter2 = {"category": "Househo*"}
    query_command.set_parameters(parameter1)
    query_command.set_parameters(parameter2)

    # Executing query command through CacheReader
    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():
            result = reader.get_value(str, columnname="product_name")
            # Perform operations
            print(result)
    else:
        # None query results retrieved
        print("Query result is None")
except Exception as exp:
    # Handle errors
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 SQL Searching on GitHub.

See Also

Locking Data For Concurrency Control
SQL Search for Objects
SQL Search for Keys Syntax and Usage
SQL IN Operator Syntax and Usage
SQL GROUP BY Syntax and Usage
Query Operators
Search Cache with LINQ

Back to top Copyright © 2017 Alachisoft