Querying for Tags
This example illustrates how to associate one or more tags (arbitrary string metadata values) with an object in the ScaleOut Service and then perform a basic query against a cache based on tag values.
Adding Tag Metadata
Methods on the Cache<TKey, TValue> class that add or update an
object can also accept an optional tags
argument, an
enumerable collection of strings to associate with the object being
added/updated. The following example illustrates how to set tags on an
object using the
AddAsync
method:
var conn = await GridConnection.ConnectAsync("bootstrapGateways=localhost:721");
var cache = new CacheBuilder<int, string>("presidents", conn).Build();
// Add presidents, tagged with party affiliation and state where born:
await cache.AddAsync(12, "Zachary Taylor", tags: new[]{ "Whig", "Virgina" });
await cache.AddAsync(13, "Millard Fillmore", tags: new[]{ "Whig", "New York" });
await cache.AddAsync(14, "Franklin Pierce", tags: new[]{ "Democratic", "New Hampshire" });
Querying for Tag Values
To query for objects with tag values, use the
QueryObjects() method to get an
IQueryable
- WithAllTags<T>(IQueryable<T>, params string[])
- WithAnyTag<T>(IQueryable<T>, params string[])
- WithTags<T>(IQueryable<T>, IEnumerable<string>, IEnumerable<string>)
A simple, tag-based query based on the two objects added above would look like this:
// Find president(s) affiliated with Whig party:
var whigQuery = cache.QueryObjects().WithAllTags("Whig");
foreach (var pres in whigQuery)
Console.WriteLine(pres);
// Output: Millard Fillmore
// Zachary Taylor
If you would rather have the query retrieve just the keys to the objects rather than the objects themselves, apply the SelectKeys operator to the query:
// Find keys to presidents born in New Hampshire:
var nhQuery = cache.QueryObjects().WithAllTags("New Hampshire")
.SelectKeys(cache);
foreach (var cacheKey in nhQuery)
Console.WriteLine(cacheKey);
// Output: 14