• 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
  • Node.js
  • Python
  • Scala
  • Install the following NuGet package in your application:
    • Enterprise: Alachisoft.NCache.SDK
  • Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
  • Include the following namespaces in your application:
    • Alachisoft.NCache.Client
    • Alachisoft.NCache.Runtime.Caching
    • Alachisoft.NCache.Client.Services
    • Alachisoft.NCache.Runtime.Exceptions
  • 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.
  • 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.
  • Add the following Maven dependency in your pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <artifactId>ncache-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.client.*;
    • import com.alachisoft.ncache.runtime.exceptions.*;
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • For API details, refer to: Cache, CacheReader, executeReader, getSearchService(), QueryCommand.
  • 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.
  • Indexing for searchable objects and their attributes need to be configured first as explained in Configuring Query Indexes in Administrator's Guide.
  • 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.
  • For API details, refer to: Cache, CacheReader, executeReader, getSearchService(), QueryCommand.
  • 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.*;
    • import com.alachisoft.ncache.scala.runtime.caching.*;
  • 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.

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
  • Node.js
  • Python
  • Scala
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", "Shamp*");
    queryCommand.Parameters.Add("Category", "Househo*");

    // 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", "Shamp*");
    queryCommand.getParameters().put("Category", "Househo*");

    // 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
}
//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", "Shamp*");
    queryCommand.setParameters(parameter1);

    let parameter2 = new Map();
    parameter2.set("Category", "Househo*");
    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
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
    }
}

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