using NRedisStack.RedisStackCommands;
using NRedisStack.Search;
using NRedisStack.Search.Aggregation;
using NRedisStack.Search.Literals.Enums;
using StackExchange.Redis;
public class HomeJsonExample
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
var user1 = new
{
name = "Paul John",
email = "paul.john@example.com",
age = 42,
city = "London"
};
var user2 = new
{
name = "Eden Zamir",
email = "eden.zamir@example.com",
age = 29,
city = "Tel Aviv"
};
var user3 = new
{
name = "Paul Zamir",
email = "paul.zamir@example.com",
age = 35,
city = "Tel Aviv"
};
var schema = new Schema()
.AddTextField(new FieldName("$.name", "name"))
.AddTagField(new FieldName("$.city", "city"))
.AddNumericField(new FieldName("$.age", "age"));
bool indexCreated = db.FT().Create(
"idx:users",
new FTCreateParams()
.On(IndexDataType.JSON)
.Prefix("user:"),
schema
);
// Tests for 'make_index' step.
bool user1Set = db.JSON().Set("user:1", "$", user1);
bool user2Set = db.JSON().Set("user:2", "$", user2);
bool user3Set = db.JSON().Set("user:3", "$", user3);
// Tests for 'add_data' step.
SearchResult findPaulResult = db.FT().Search(
"idx:users",
new Query("Paul @age:[30 40]")
);
Console.WriteLine(string.Join(
", ",
findPaulResult.Documents.Select(x => x["json"])
));
// >>> {"name":"Paul Zamir","email":"paul.zamir@example.com", ...
// Tests for 'query1' step.
var citiesResult = db.FT().Search(
"idx:users",
new Query("Paul")
.ReturnFields(new FieldName("$.city", "city"))
);
Console.WriteLine(string.Join(
", ",
citiesResult.Documents.Select(x => x["city"]).OrderBy(x => x)
));
// >>> London, Tel Aviv
// Tests for 'query2' step.
AggregationRequest aggRequest = new AggregationRequest("*")
.GroupBy("@city", Reducers.Count().As("count"));
AggregationResult aggResult = db.FT().Aggregate("idx:users", aggRequest);
IReadOnlyList<Dictionary<string, RedisValue>> resultsList =
aggResult.GetResults();
for (var i = 0; i < resultsList.Count; i++)
{
Dictionary<string, RedisValue> item = resultsList.ElementAt(i);
Console.WriteLine($"{item["city"]} - {item["count"]}");
}
// >>> London - 1
// >>> Tel Aviv - 2
// Tests for 'query3' step.
}
}