Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Pipeline & Transaction + Examples #68

Merged
merged 10 commits into from
Feb 7, 2023
19 changes: 19 additions & 0 deletions Examples/AsyncExample.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@

# Async Example

## All methods have sync and async implementations. The async methods end with the suffix Async(...), and are fully await-able. See the example below:

Connect to a Redis server, and retrieve an instance that can run JSON commands:

```csharp
var redis = await ConnectionMultiplexer.ConnectAsync("localhost");
var db = redis.GetDatabase();
var json = db.JSON();
```

Store and retrieve data, async:

```csharp
await json.SetAsync("key", "$", new { name = "John", age = 30, city = "New York" });
var john = await json.GetAsync("key");
```
60 changes: 60 additions & 0 deletions Examples/CombinationModulesPipeline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Combination modules Pipeline

## An example of pipelines mixing a pipeline with a combination of module commands with JSON & Search

Connect to the Redis server:

```csharp
var redis = ConnectionMultiplexer.Connect("localhost");
```

Setup pipeline connection

```csharp
var db = redis.GetDatabase();
var pipeline = new Pipeline(db);
```

## JSON

Add JSON data to the pipeline.

```csharp
pipeline.Json.SetAsync("person:01", "$", new { name = "John", age = 30, city = "New York" });
pipeline.Json.SetAsync("person:02", "$", new { name = "Joy", age = 25, city = "Los Angeles" });
pipeline.Json.SetAsync("person:03", "$", new { name = "Mark", age = 21, city = "Chicago" });
pipeline.Json.SetAsync("person:04", "$", new { name = "Steve", age = 24, city = "Phoenix" });
pipeline.Json.SetAsync("person:05", "$", new { name = "Michael", age = 55, city = "San Antonio" });
```

## Search

Create the schema to index name as text field, age as a numeric field and city as tag field.

```csharp
var schema = new Schema().AddTextField("name").AddNumericField("age", true).AddTagField("city");
```

Create a search index, that only retrieves JSON objects from keys prefixed *person*.

```csharp
var parameters = FTCreateParams.CreateParams().On(IndexDataType.JSON).Prefix("person:");
```

Create a search index, on our stored data:

```csharp
pipeline.Ft.CreateAsync("person-idx", parameters, schema);
```

Execute the pipeline

```csharp
pipeline.Execute();
```

Search for all indexed person records

```csharp
var getAllPersons = db.FT().SearchAsync("person-idx", new Query());
```
60 changes: 60 additions & 0 deletions Examples/HsetAndSearch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# HSET and Search
## An example of mixing Redis open source command (HSET) with Redis Stack Redis commands (FT.CREATE & FT.SEARCH)

Connect to the Redis server:
```csharp
var redis = ConnectionMultiplexer.Connect("localhost");
```
Get a reference to the database and for search commands:
```csharp
var db = redis.GetDatabase();
var ft = db.FT();
```
Use HSET to add a field-value pair to a hash:
```csharp
db.HashSet("profesor:5555", new HashEntry[] { new("first", "Albert"), new("last", "Blue"), new("age", "55") });
db.HashSet("student:1111", new HashEntry[] { new("first", "Joe"), new("last", "Dod"), new("age", "18") });
db.HashSet("pupil:2222", new HashEntry[] { new("first", "Jen"), new("last", "Rod"), new("age", "14") });
db.HashSet("student:3333", new HashEntry[] { new("first", "El"), new("last", "Mark"), new("age", "17") });
db.HashSet("pupil:4444", new HashEntry[] { new("first", "Pat"), new("last", "Shu"), new("age", "21") });
db.HashSet("student:5555", new HashEntry[] { new("first", "Joen"), new("last", "Ko"), new("age", "20") });
db.HashSet("teacher:6666", new HashEntry[] { new("first", "Pat"), new("last", "Rod"), new("age", "20") });
```

Create the schema indexing the text fields ```first``` and ```last```, and ```age``` as a numeric field:
```csharp
var schema = new Schema().AddTextField("first").AddTextField("last").AddNumericField("age");
```
Filter the index to only include hashes with an age greater than 16, and prefix of 'student:' or 'pupil:'
```csharp
var parameters = FTCreateParams.CreateParams().Filter("@age>16").Prefix("student:", "pupil:");
```
Create the index:
```csharp
ft.Create("example_index", parameters, schema);
```
## Search Examples:

Search all hashes in the index:
```csharp
var noFilters = ft.Search("example_index", new Query());
```
_noFilters_ now contains: _student:1111_, _student:5555_, _pupil:4444_, _student:3333_.<br /><br />

Search for hashes with a first name starting with Jo
```csharp
var startWithJo = ft.Search("example_index", new Query("@first:Jo*"));
```
_startWithJo_ now contains: _student:1111_ (Joe), _student:5555_ (Joen).<br /><br />

Search for hashes with first name of Pat
```csharp
var namedPat = ft.Search("example_index", new Query("@first:Pat"));
```
_namedPat_ now contains _pupil:4444_ (Pat). _teacher:6666_ (Pat) is not included because it does not have a prefix of 'student:' or 'pupil:'<br /><br />

Search for hashes with last name of Rod
```csharp
var lastNameRod = ft.Search("example_index", new Query("@last:Rod"));
```
_lastNameRod_ is empty because there are no hashes with a last name of Rod that match the index definition.
52 changes: 52 additions & 0 deletions Examples/PipelineExample.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Pipeline
## An example of pipelines Redis Stack Redis commands (JSON.SET & JSON.CLEAR & JSON.GET)

Connect to the Redis server and Setup new Pipeline
```csharp
IDatabase db = redisFixture.Redis.GetDatabase();
var pipeline = new Pipeline(db);
```


Add JSON data to pipeline
```csharp
pipeline.Json.SetAsync("person", "$", new { name = "John", age = 30, city = "New York", nicknames = new[] { "John", "Johny", "Jo" } });
```

Increase age by 2
```csharp
pipeline.Json.NumIncrbyAsync("person", "$.age", 2);
```

Remove the ```nicknames``` field from the JSON object
```csharp
pipeline.Json.ClearAsync("person", "$.nicknames");
```

Delete the nicknames
```csharp
pipeline.Json.DelAsync("person", "$.nicknames");
```

Retrieve the JSON response
```csharp
var getResponse = pipeline.Json.GetAsync("person");
```

Execute pipeline
```csharp
pipeline.Execute();
```

Access the result of the JSON response
```csharp
var result = getResponse.Result;
```
now result is:
```json
{
"name": "John",
"age": 32,
"city": "New York"
}
```
72 changes: 72 additions & 0 deletions Examples/PipelineWithAsync.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Pipeline With Async
## An example of pipelines Redis Stack Redis commands (JSON.SET & JSON.CLEAR & JSON.GET)

Connect to the Redis server
```csharp
var redis = ConnectionMultiplexer.Connect("localhost");
```

Get a reference to the database
```csharp
var db = redis.GetDatabase();
```

Setup pipeline connection
```csharp
var pipeline = new Pipeline(db);
```

Create metadata labels for a TimeSeries object:

```csharp
TimeSeriesLabel label1 = new TimeSeriesLabel("temp", "TLV");
TimeSeriesLabel label2 = new TimeSeriesLabel("temp", "JLM");
var labels1 = new List<TimeSeriesLabel> { label1 };
var labels2 = new List<TimeSeriesLabel> { label2 };
```

Create a new time-series object:

```csharp
pipeline.Ts.CreateAsync("temp:TLV", labels: labels1);
pipeline.Ts.CreateAsync("temp:JLM", labels: labels2);
```

Create the TimeSeries objects, and store them in Redis:

```csharp
List<(string, TimeStamp, double)> sequence1 = new List<(string, TimeStamp, double)>()
{
("temp:TLV",1000,30),
("temp:TLV", 1010 ,35),
("temp:TLV", 1020, 9999),
("temp:TLV", 1030, 40)
};
List<(string, TimeStamp, double)> sequence2 = new List<(string, TimeStamp, double)>()
{
("temp:JLM",1005,30),
("temp:JLM", 1015 ,35),
("temp:JLM", 1025, 9999),
("temp:JLM", 1035, 40)
};

pipeline.Ts.MAddAsync(sequence1);
pipeline.Ts.MAddAsync(sequence2);

```

Execute the pipeline:

```csharp
pipeline.Execute();
```

Get a reference to the database and for TimeSeries commands:
```csharp
var ts = db.TS();
```

Get only the location label for each last sample, use SELECTED_LABELS.
```csharp
var respons = await ts.MGetAsync(new List<string> { "temp=JLM" }, selectedLabels: new List<string> { "location" });
```
55 changes: 55 additions & 0 deletions Examples/TransactionsExample.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Transaction

## An example of transaction with Redis modules (JSON.SET, JSON.GET & JSON.NUMINCRBY)

Connect to the Redis server:

```cs
var redis = await ConnectionMultiplexer.ConnectAsync("localhost");
var db = redis.GetDatabase();
```

Create the transaction:

```cs
var tran = new Transaction(db);
```

Store the account details as JSON:

```csharp
tran.Json.SetAsync("accdetails:Jeeva", "$", new { name = "Jeeva", totalAmount= 1000, bankName = "City" });
tran.Json.SetAsync("accdetails:Shachar", "$", new { name = "Shachar", totalAmount = 1000, bankName = "City" });
```

Retrieve the responses

```csharp
var getShachar = tran.Json.GetAsync("accdetails:Shachar");
var getJeeva = tran.Json.GetAsync("accdetails:Jeeva");
```

Debit 200 from Jeeva

```cs
tran.Json.NumIncrbyAsync("accdetails:Jeeva", "$.totalAmount", -200);
```

Credit 200 from Shachar

```cs
tran.Json.NumIncrbyAsync("accdetails:Shachar", "$.totalAmount", 200);
```

Get total amount for both Jeeva = 800 & Shachar = 1200

```cs
var totalAmtOfJeeva = tran.Json.GetAsync("accdetails:Jeeva", path:"$.totalAmount");
var totalAmtOfShachar = tran.Json.GetAsync("accdetails:Shachar", path:"$.totalAmount");
```

Execute the transaction

```cs
var condition = tran.ExecuteAsync();
```
19 changes: 14 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,13 @@ IJsonCommands json = db.JSON();
ITimeSeriesCommands ts = db.TS();
```
Then, that variable will allow you to call all the commands of that module.

## Examples
### Set JSON object to Redis
Set a json object to Redis:

### Store a JSON object in Redis

To store a json object in Redis:

```csharp
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
Expand All @@ -76,17 +80,20 @@ IJsonCommands json = db.JSON();
var key = "myKey";
json.Set(key, "$", new Person() { Age = 35, Name = "Alice" });
```

### Index and search
We will see an example that shows how you can create an index, add a document to it and search it using NRedisStack.
Now, to execute a search for objects, we need to index them on the server, and run a query:

Setup:

```csharp
using NRedisStack;
...
IDatabase db = redisFixture.Redis.GetDatabase();
ISearchCommands ft = db.FT();
IJsonCommands json = db.JSON();
```

Create an index with fields and weights:
```csharp
// FT.CREATE myIdx ON HASH PREFIX 1 doc: SCHEMA title TEXT WEIGHT 5.0 body TEXT url TEXT
Expand All @@ -97,8 +104,7 @@ ft.Create("myIndex", new FTCreateParams().On(IndexDataType.Hash)
.AddTextField("url"));
```

After you create the index, any new hash documents with the doc: prefix are automatically indexed upon creation.

After creating the index, future documents with the ```doc:``` prefix will be automatically indexed when created or modified.

To create a new hash document and add it to the index, use the HSET command:
```csharp
Expand All @@ -117,6 +123,9 @@ Drop the index:
// FT.DROPINDEX myIndex
ft.DropIndex("myIndex");
```

More examples can be found in the [examples folder](/blob/master/Examples).

------

### Author
Expand Down
Loading