• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Client Side API Programming
  • Tags
  • Add/Update Data with Tags
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

Add/Update Tags in Data Cache

NCache allows the user to create tags and then add items to the cache with tags. The user can also add a tag as a CacheItem. Moreover, you can update and append new tags to an already existing tag list.

Prerequisites to Add/Update Tags in Data Cache

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
  • 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, CacheItem, CacheItemVersion, Tag, Insert, Add,Tags, Count, Contains.
  • 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, CacheItem, CacheItemVersion, getCacheItem, Tag, insert, add, getTags, setTags.
  • 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, CacheItem, get_cacheitem, get_tags, set_tags, add, insert.
  • 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, CacheItem, CacheItemVersion, getCacheItem, Tag, insert, add, getTags, setTags.
  • Create a new Console Application.
  • Make sure that the data being added is serializable.
  • Add NCache References by locating %NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
  • Include the Alachisoft.NCache.Runtime.Caching namespace in your application.

Tag Data

CacheItem is a custom class provided by NCache which can be used to add data to the cache. CacheItem also lets you set additional specifications associated with an object as a property of the Tags class.

Warning
  • If the key already exists, an exception will be thrown.
  • Providing a Null tag array will throw an ArgumentNullException.

The following example adds a CacheItem containing the object customer to the cache using the Add API. It then sets an additional tag property against it by adding the tags.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
// A VIP Customer from the East Coast region has logged into an e-commerce website.
// The customer will be added to the cache according to the category tags.

string customerKey = $"Customer:ALFKI";
Customer customer = cache.Get<Customer>(customerKey);

// Get customer from database if not found in cache
if (customer == null)
{
    // Get customer from database
    customer = FetchCustomerFromDB("ALFKI");

    // Create a new CacheItem
    var cacheItem = new CacheItem(customer);

    // Create an array of tags assigned to customer
    Tag[] tags = new Tag[2];
    tags[0] = new Tag("East Coast Customers");
    tags[1] = new Tag("VIP Customers");

    // Setting the tag property of the cacheItem
    cacheItem.Tags = tags;

    cache.Add(customerKey, cacheItem);
    // CacheItem added successfully
}
// Precondition: Cache is already connected
// A VIP Customer from the East Coast region has logged into an e-commerce website.
// The customer will be added to the cache according to the category tags.

String customerKey = "Customer:ALFKI";
Customer customer = null;
customer = cache.get(customerKey, Customer.class);


// Get customer from database if not found in cache
if (customer == null) {
    // Get customer from database
    customer = Customer.fetchCustomerFromDB("Customer:ALFKI");
}
// Create a new CacheItem
CacheItem cacheItem = new CacheItem(customer);

// Create an array of tags assigned to customer
Tag[] tags = new Tag[2];
tags[0] = new Tag("East Coast Customers");
tags[1] = new Tag("VIP Customers");

// Setting the tag property of the cacheItem
cacheItem.setTags(List.of(tags));

cache.insert(customerKey, cacheItem);
System.out.println("CacheItem added successfully");
# Precondition: Cache is already connected

# Get customer from database
customer = fetch_customer_from_db("ALFKI")

# Create a unique cache key for this customer.
key = "Customers:" + customer.get_customer_id()

# Specify tags
tags = [
    ncache.Tag("East Coast Customers"),
    ncache.Tag("Important Customers")
]

# Create a new CacheItem
cache_item = ncache.CacheItem(customer)

# Setting the tag property of the cacheItem
cache_item.set_tags(tags)

# Add customer object to cache
version = cache.add(key, cache_item)

# CacheItem added successfully
// Precondition: Cache is already connected
// This is an async method

// Get customer from database against given customer ID
var customer = this.fetchCustomerFromDB("ALFKI");

// Create a unique cache key for this customer.
var key = "Customers:" + customer.getCustomerID();

// Specify tags
var tags = new ncache.Tag[2];
tags[0] = new ncache.Tag("East Coast Customers");
tags[1] = new ncache.Tag("Important Customers");

// Create a new CacheItem
var cacheItem = new ncache.CacheItem(customer);

// Setting the tag property of the cacheItem
cacheItem.setTags(tags);

// Add customer object to cache
var version = await this.cache.add(key, cacheItem);

// CacheItem added successfully
// Create a Tag array and specify tags.
Tag[] productTags = new Tag[2];
productTags[0] = new Tag("Product");
productTags[1] = new Tag("Beverages");

Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";

string key = "Product:" + product.ProductID;

CacheItem cacheItem = new CacheItem(product);
cacheItem.Tags = productTags;

cache.Add(key, cacheItem);
Note

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

Update Data with Tags

Updating tags through CacheItem requires the item to be first fetched, its tags to be modified, and then re-inserted into the cache using the Insert method.

The following example first fetches the CacheItem, creates a tag list with the new tags, and then reinserts the CacheItem in the cache along with the modified tag list. Hence, overrides the value of existing tags.

  • .NET
  • Java
  • Python
  • Node.js
// A VIP Customer has logged into an e-commerce website from a different region, i.e., West Coast.
// This customer will be added to the cache according to the category tags

// Create an array of new tags assigned to customer with different regiom
Tag[] tags = new Tag[2];
tags[0] = new Tag("West Coast Customers");
tags[1] = new Tag("VIP Customers");

// Set the tag property of the cacheItem with a new updated array.
cacheItem.Tags = tags;

// Reinserts the updated cacheItem into cache with different tags
cache.Insert(customerKey, cacheItem);
// A VIP Customer has logged into an e-commerce website from a different region i.e. West Coast.
// This customer will be added to the cache according to the category tags.

String customerKey = "Customer:ALFKI";

// Fetch the customer from the cache
CacheItem cacheItem = null;
cacheItem = cache.getCacheItem(customerKey);

if (cacheItem != null) {
    // Create an array of new tags assigned to customer with different region
    Tag[] tags = new Tag[2];
    tags[0] = new Tag("West Coast Customers");
    tags[1] = new Tag("VIP Customers");

    // Set the tag property of the cacheItem with the new updated array
    cacheItem.setTags(List.of(tags));

    // Reinsert the updated cacheItem into cache with different tags
    cache.insert(customerKey, cacheItem);
    System.out.println("CacheItem updated successfully");

}
# Get cache item from cache against given key
key = "ALFKI"
cache_item = cache.get_cacheitem(key)

# Create new Tag array
new_tags = [
    ncache.Tag("US Customers"),
    ncache.Tag("VIP Customers")
]

# Updates the tags with the new tags
# Overrides the value of the existing tags
cache_item.set_tags(new_tags)

# Re-insert the cache_item into cache with modified tags
cache.insert(key, cache_item)
// This is an async method
// Get cache item from cache against given key
var key = "ALFKI";
var cacheItem = this.cache.getCacheItem(key);

// Create new Tag array
var newTags = new ncache.Tag[2];
newTags[0] = new ncache.Tag("US Customers");
newTags[1] = new ncache.Tag("VIP Customers");

// Updates the tags with the new tags
// Overrides the value of the existing tags
cacheItem.setTags(newTags);

//Reinserts the cacheItem into cache with modified tags
await this.cache.insert(key, cacheItem);

Append Tags to Already Existing Tags

If there is a need to append a new tag to the already present tags or if a tag needs to be removed from the already present tags, the operation will require manipulating the tags array. For this purpose, create a new list with the tags to append and copy that list to the array containing the tags already. This way a new tag would be added to the array containing the tags previously created without affecting them.

The following example appends new tags to an already existing tag list Tags.

  • .NET
  • Java
  • Python
  • Node.js
// A customer has logged in from the US who wants to add tags for the country and region.
string customerKey = $"Customer:ALFKI";

// Get CacheItem from Cache
CacheItem cachedCustomer = cache.GetCacheItem(customerKey);

// Create new List for tags
var customerTags = new List<Tag>();

// Initialize the list with existing tags
customerTags = new List<Tag>(cachedCustomer.Tags);

// Add new tags to existing list of tags
customerTags.Add(new Tag("US Customers"));

// Assign newly built tag list to the cached customer object.
cachedCustomer.Tags = customerTags.ToArray();

// Update the modified customer object in cache
cache.Insert(customerKey, cachedCustomer);
// A customer has logged in from the US who wants to add tags for the country and region.
String customerKey = "Customer:ALFKI";

// Get CacheItem from Cache
CacheItem cachedCustomer = cache.getCacheItem(customerKey);

if (cachedCustomer != null) {
    // Initialize a list with existing tags
    List<Tag> customerTags = new ArrayList<>(cachedCustomer.getTags());

    // Add new tags to existing list of tags
    customerTags.add(new Tag("US Customers"));

    // Assign the newly built tag list to the cached customer object
    cachedCustomer.setTags(customerTags);

    // Update the modified customer object in cache
    cache.insert(customerKey, cachedCustomer);
}
# Get customer from database
key = "ALFKI"
cached_customer = cache.get_cacheitem(key)

# Create new Tag array and initialize the list with existing tags
customer_tags = cached_customer.get_tags()

# Add new tags to existing list of tags
customer_tags.append(ncache.Tag("VIP Customers"))
customer_tags.append(ncache.Tag("US Customers"))

# Assign newly built tag list to the cached customer object.
cached_customer.set_tags(customer_tags)

# Update the modified customer object in cache
cache.insert(key, cached_customer)
// This is an async method
// Get customer from database against the given key
var key = "ALFKI";
var cachedCustomer = this.cache.getCacheItem(key);

// Create new Tag array
var customerTags = [];

// Initialize the list with existing tags
customerTags = [cachedCustomer.getTags()];

// Add new tags to existing list of tags
customerTags.fill(new ncache.Tag("VIP Cutsomers"));
customerTags.fill(new ncache.Tag("US Customers"));

// Assign newly built tag list to the cached customer object.
cachedCustomer.setTags(customerTags);

// Update the modified customer object in cache
await this.cache.insert(key, cachedCustomer);

Additional Resources

NCache provides sample application for Tags on GitHub.

See Also

.NET: Alachisoft.NCache.Runtime.Caching namespace.
Java: com.alachisoft.ncache.runtime.caching namespace.
Python: ncache.runtime.caching class.
Node.js: Tag class.

In This Article
  • Prerequisites to Add/Update Tags in Data Cache
  • Tag Data
  • Update Data with Tags
  • Append Tags to Already Existing 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