Try Playground
Show / Hide Table of Contents

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