• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Client Side API Programming
  • Data Structures
  • Query on Data Structures
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Server
      • Oracle
      • OleDB with Polling
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Topics
      • Publish Messages
      • Subscribe to a Topic
      • Pub/Sub Events
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Clear Cache
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • NCache Extension for SignalR Core
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

Query on Data Structures

The data structures can be queried in the cache if they have searchable attributes associated with them during data structure creation. These searchable attributes include:

  • Groups
  • Tags
  • Named Tags

Prerequisites

  • .NET
  • Java
  • Python
  • Node.js
  • 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.
  • For API details, refer to: ICache, QueryCommand, ICacheReader, SearchService, ExecuteReader, GetValue, IDistributedList, GetGroupData, FieldCount, IDistributedDictionary, GetByTag.
  • 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.
  • For API details, refer to: Cache, QueryCommand, CacheReader, getSearchService, executeReader, getFieldCount, getValue, DistributedList, getGroupData, DataStructureAttributes, DistributedMap, getByTag.
  • 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.
  • For API details, refer to: Cache, QueryCommand, CacheReader, execute_reader, SearchService, get_search_service, DataStructureAttributes, get_field_count, get_value, get_group_data, get_by_tag.
  • 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.
  • For API details, refer to: Cache, QueryCommand, SearchService, getSearchService, executeReader, getFieldCount, getValue, getGroupData, CacheReader, DataStructureAttributes, getByTag.

Search Data Structures by Groups

SQL Query

The following code sample fetches all items from the cache that have been associated with a specified Group, Electronics. The Group can be associated using DataTypeAttributes class during data structure creation.

Important
  • If there are multiple lists specified against the group, all of them will be returned in one result, granted that their data structures are similar.
  • For multiple cache items, for example, if a CacheItem and a list belong to the same group, you need to ensure that the data is handled accordingly.
  • .NET
  • Java
  • Node.js
  • Python
// Preconditions: Cache is already connected

// Items with groups exist in cache
// Custom class is query indexed through the NCache Management Center or config.ncconf
// Search for items with group
// Provide Fully Qualified Name (FQN) of your custom class
string query = "SELECT ProductID FROM FQN.Customer WHERE $Group$ = ?";

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

// Providing parameters for query
queryCommand.Parameters.Add("$Group$", "Electronics");

// Executing QueryCommand through ICacheReader
ICacheReader reader = cache.SearchService.ExecuteReader(queryCommand);

// Check if the result set is not empty
if (reader.FieldCount > 0)
{
    while (reader.Read())
    {
        string ProductID = reader.GetValue<string>(1);

        // Perform operations
    }
}
else
{
    // Null query result set retrieved
}
// Preconditions: Cache is already connected

// Items with groups exist in cache
// Custom class is query indexed through NCache Management Center or config.ncconf
// Search for items with group
// Provide Fully Qualified Name (FQN) of your custom class
String query = "SELECT productID FROM FQN.Customer WHERE $Group$ = ?";

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

// Providing parameters for query
queryCommand.getParameters().put("$Group$", "Electronics");

// Executing QueryCommand through CacheReader
CacheReader reader = cache.getSearchService().executeReader(queryCommand);

// Check if the result set is not empty
if (reader.getFieldCount() > 0) {
    while (reader.read()) {
        String productID = reader.getValue(1, String.class);

        // Perform operations
    }
} else {
    // Null query result set retrieved
}
// This is an async method
// Preconditions: Cache is already connected

// Items with groups exist in cache
// Custom class is query indexed through the NCache Management Center or config.ncconf
// Search for items with group
// Provide Fully Qualified Name (FQN) of your custom class
var query = "SELECT productID FROM FQN.Customer WHERE $Group$ = ?";

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

// Providing parameters for query
let map = new Map();
var parameters = map.set("$Group$", "Electronics");
queryCommand.setParameters(parameters);

// Executing QueryCommand through CacheReader
var searchService = await this.cache.getSearchService();
var reader = await searchService.executeReader(queryCommand);

// Check if the result set is not empty
if (reader.getFieldCount() > 0) {
while (reader.read()) {
    var productID = reader.getValue(1, Number());

    // Perform operations
}
} else {
// Null query result set retrieved
}
# Preconditions: Cache is already connected
# Items with groups exist in cache
# Custom class is query indexed through NCache Management Center or config.ncconf
# Search for items with group
# Provide Fully Qualified Name (FQN) of your custom class
query = "SELECT product_id FROM FQN.Customer WHERE $Group$ = ?"

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

# Providing parameters for query
parameters = {"$Group$": "Electronics"}
query_command.set_parameters(parameters)

# Executing QueryCommand through CacheReader
search_service = cache.get_search_service()
reader = search_service.execute_reader(query_command)

# Check if the result set is not empty
if reader.get_field_count() > 0:
    while reader.read():
        product_id = reader.get_value(str, 1)
        # Perform operations
else:
    # None query result set retrieved
    print("Query result is None")

Group API

The following code sample fetches all the lists from the cache that have been associated with a specified group, Electronics. The group can be associated using DataTypeAttributes class during the data structure creation.

  • .NET
  • Java
  • Node.js
  • Python
// List with this group already exists in cache
string groupName = "Electronics";
IDictionary<string, IDistributedList<Product>> result = cache.SearchService.GetGroupData<IDistributedList<Product>>(groupName);

if (result != null && result.Count > 0)
{
    // Iterate over list
    foreach (var item in result)
    {
        foreach (var i in item.Value)
        {
            // Perform operations
        }
    }
}
else
{
    // No data against the group found
}
// Precondition: Cache is already connected

// List with this group already exists in the cache
String groupName = "Electronics";
Map<String, DistributedList<Product>> result = cache.getSearchService().getGroupData(groupName);

if (result != null && result.size() > 0) {
    // Iterate over list
    for (var item : result.entrySet()) {
        // Perform operations
    }
} else {
    // No data against the group found
}
// This is an async method
// Precondition: Cache is already connected

// List with this group already exists in the cache
var groupName = "Electronics";
var result = await (
await this.cache.getSearchService()
).getGroupData(groupName);

if (result != null && result.size() > 0) {
// Iterate over list
for (var item in result.entrySet()) {
    // Perform operations
}
} else {
// No data against the group found
}
# Precondition: Cache is already connected
# List with this group already exists in the cache
group_name = "Electronics"

result = cache.get_search_service().get_group_data(group_name)

if result is not None and len(result) > 0:
    # Iterate over list
    for item in result:
        # Perform operations
        print(item)
else:
    # No data against the group found
    print("No data found")
Note

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

Search Data Structures by Tags

SQL Query

The following code sample fetches the items from the cache that have been associated with a specified tag, Stainless Steel. The tag can be associated using DataTypeAttributes class during the data structure creation.

  • .NET
  • Java
  • Python
  • Node.js
// Items are already present in the cache with tags
// Custom class is query indexed through NCache Management Center 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.Product WHERE $Tag$ = ?";

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

// 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
        Product result = reader.GetValue<Product>(1);
    }
}
else
{
    // Null query result set retrieved
}
// Pre-conditions: Cache is already connected

// Items are already present in the cache with tags
// Custom class is query indexed through NCache Management Center 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.Product WHERE $Tag$ = ?";

// Use QueryCommand for query execution
var queryCommand = new QueryCommand(query);
queryCommand.getParameters().put("$Tag$", "Stainless Steel");

// 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
        Product result = reader.getValue(1, Product.class);
    }
} else {
    // Null query result set retrieved
}
# Pre-conditions: Cache is already connected
# Items are already present in the cache with tags
# Custom class is query indexed through NCache Management Center or config.ncconf
# Search for items with tags
# Use the Fully Qualified Name (FQN) of your own custom class
query = "Select $Value$ FROM FQN.Product WHERE $Tag$ = ?"

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

parameters = {"$Tag$": "Stainless Steel"}

query_command.set_parameters(parameters)

# 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(Product, 1)
        # Perform operations
else:
    # Null query result set retrieved
    print("Query result is None")
// This is an async method
// Pre-conditions: Cache is already connected

// Items are already present in the cache with tags
// Custom class is query indexed through NCache Management Center 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.Product WHERE $Tag$ = ?";

// Use QueryCommand for query execution
var queryCommand = new ncache.QueryCommand(query);
var map = new Map();
var parameters = map.set("$Tag$", "Stainless Steel");
queryCommand.setParameters(parameters);

// 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, ncache.JsonDataType.Object);
    // Perform operations
}
} else {
// Null query result set retrieved
}

Tag API

The following code sample fetches all the dictionary instances from the cache that have been associated with a specified tag, Stainless Steel. The tag can be associated using the DataTypeAttributes class during the data structure creation.

  • .NET
  • Java
  • Python
  • Node.js
// Items against this tag exist in cache
Tag tag = new Tag("Stainless Steel");

// Get dictionary against tag
IDictionary<string, IDistributedDictionary<string, Product>> result = cache.SearchService.GetByTag<IDistributedDictionary<string, Product>>(tag);

if (result != null && result.Count > 0)
{
    foreach (var item in result)
    {
        // Perform operations
    }
}
else
{
    // Dictionary does not exist against tag
}
// Precondition: Cache is already connected

// Items against this tag already exist in the cache
Tag tag = new Tag("Stainless steel");

// Get map against tag
Map<String, DistributedMap<String, Product>> result = cache.getSearchService().getByTag(tag);

if (result != null && result.size() > 0) {
    for (var item : result.entrySet()) {
        // Perform operations
    }
} else {
    // Dictionary does not exist against tag
}
# Precondition: Cache is already connected
# Items against this tag already exist in the cache
tag = ncache.Tag("Stainless steel")

# Get map against tag
result = cache.get_search_service().get_by_tag(tag)

if result is not None and len(result) > 0:
    for item in result:
        # Perform operations
        print(item)
else:
    # Dictionary does not exist against tag
    print("Dictionary not found")
// This is an async method
// Precondition: Cache is already connected

// Items against this tag already exist in the cache
var tag = [new ncache.Tag("Stainless steel")];

// Get map against tag
var result = await (await this.cache.getSearchService()).getByTag(tag);

if (result != null && result.size() > 0) {
for (var item in result.entrySet()) {
    // Perform operations
}
} else {
// Dictionary does not exist against tag
}

Search Data Structures by Named Tags

NCache uses the $DataType$ keyword that will fetch all the data structures with the specified Named Tag. The following code assumes a list has been added with Named Tag Discount with a value 0.4 and fetches it using queries.

  • .NET
  • Java
  • Python
  • Node.js
// Data Structures exist with NamedTag Discount and value 0.4
// Create query
string query = "SELECT * FROM $DataType$ WHERE Discount = 0.4";

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

// Execute Query to search cache
ICacheReader queryResult = cache.SearchService.ExecuteReader(queryCommand);

// queryResult contains all the keys and metadata of result
if (queryResult.FieldCount > 0)
{
    while (queryResult.Read())
    {
        // Key of list can be fetched through
        queryResult.GetValue<DistributedList>(1);
    }
}
else
{
    // Null query result set retrieved
}
// Pre-conditions: Cache is already connected

// Data Structures exist with NamedTag "Discount" and value 0.4
// Create query
String query = "SELECT * FROM $DataType$ WHERE Discount = 0.4";

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

// Execute Query to search cache
CacheReader queryResult = cache.getSearchService().executeReader(queryCommand);

// queryResult contains all the keys and metadata of result
if (queryResult.getFieldCount() > 0) {
    while (queryResult.read()) {
        // Key of list can be fetched through
        queryResult.getValue(0, DistributedList.class);
        // Perform operations
    }
} else {
    // Null query result set retrieved
}
# Pre-conditions: Cache is already connected
# Data Structures exist with NamedTag "Discount" and value 0.4
# Create query
query = "SELECT * FROM $DataType$ WHERE discount = 0.4"

query_command = ncache.QueryCommand(query)

# Execute Query to search cache
search_service = cache.get_search_service()
query_result = search_service.execute_reader(query_command)

# queryResult contains all the keys and metadata of result
if query_result.get_field_count() > 0:
    while query_result.read():
        # Key of list can be fetched through
        query_result.get_value(int, 1)
        # Perform operations
else:
    # No data containing the named tag(s) exist
    print("Data not found")
// This is an async method
// Pre-conditions: Cache is already connected

// Data Structures exist with NamedTag "Discount" and value 0.4
// Create query
var query = "SELECT * FROM $DataType$ WHERE Discount = 0.4";

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

// Execute Query to search cache
var searchService = await this.cache.getSearchService();
var queryResult = await searchService.executeReader(queryCommand);

// queryResult contains all the keys and metadata of result
if (queryResult.getFieldCount() > 0) {
while (queryResult.read()) {
    // Key of list can be fetched through
    queryResult.getValue(0, Number());
    // Perform operations
}
} else {
// Null query result set retrieved
}

Additional Resources

NCache provides a sample application for querying data structures on GitHub.

See Also

.NET: Alachisoft.NCache.Client.DataTypes namespace.
Java: com.alachisoft.ncache.client.datastructures namespace.
Python: ncache.client.datastructures class.
Node.js: DataStructureManager class.

In This Article
  • Prerequisites
  • Search Data Structures by Groups
    • SQL Query
    • Group API
  • Search Data Structures by Tags
    • SQL Query
    • Tag API
  • Search Data Structures by Named Tags
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top