Skip to content

Commit 2357c55

Browse files
authored
Convert SearchResult to JSON (#87)
* Add ToJson() in SearchResult + example & test * add Where not null * add assertion * fixes
1 parent 7504d71 commit 2357c55

File tree

3 files changed

+66
-3
lines changed

3 files changed

+66
-3
lines changed

Examples/ConvertSearchResultToJson.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Converting Search Result to JSON
2+
## This example shows how to convert Redis search results to JSON format using NRedisStack.
3+
4+
Connect to the Redis server:
5+
```csharp
6+
var redis = ConnectionMultiplexer.Connect("localhost");
7+
```
8+
Get a reference to the database and for search and json commands:
9+
```csharp
10+
var db = redis.GetDatabase();
11+
var ft = db.FT();
12+
var json = db.JSON();
13+
```
14+
Create a search index with a JSON field:
15+
```csharp
16+
ft.Create("test", new FTCreateParams().On(IndexDataType.JSON).Prefix("doc:"),
17+
new Schema().AddTagField(new FieldName("$.name", "name")));
18+
```
19+
Insert 10 JSON documents into the index:
20+
```csharp
21+
for (int i = 0; i < 10; i++)
22+
{
23+
json.Set("doc:" + i, "$", "{\"name\":\"foo\"}");
24+
}
25+
```
26+
Execute a search query and convert the results to JSON:
27+
```csharp
28+
var res = ft.Search("test", new Query("@name:{foo}"));
29+
var docs = res.ToJson();
30+
```
31+
Now the `docs` variable contains a JSON list (IEnumerable) of the search results.

src/NRedisStack/Search/SearchResult.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ public class SearchResult
1212
public long TotalResults { get; }
1313
public List<Document> Documents { get; }
1414

15+
/// <summary>
16+
/// Converts the documents to a list of json strings. only works on a json documents index.
17+
/// </summary>
18+
public IEnumerable<string>? ToJson() => Documents.Select(x => x["json"].ToString())
19+
.Where(x => !string.IsNullOrEmpty(x));
20+
1521
internal SearchResult(RedisResult[] resp, bool hasContent, bool hasScores, bool hasPayloads/*, bool shouldExplainScore*/)
1622
{
1723
// Calculate the step distance to walk over the results.

tests/NRedisStack.Tests/Examples/ExamplesTests.cs

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ public void HSETandSearch()
6161
// Search for hashes with last name of Rod
6262
var lastNameRod = ft.Search("example_index", new Query("@last:Rod"));
6363
// lastNameRod is empty because there are no hashes with a last name of Rod that match the index definition
64+
Assert.Equal(4, noFilters.TotalResults);
65+
Assert.Equal(2, startWithJo.TotalResults);
66+
Assert.Equal(1, namedPat.TotalResults);
67+
Assert.Equal(0, lastNameRod.TotalResults);
6468
}
6569

6670
[Fact]
@@ -226,7 +230,7 @@ public async Task TransactionExample()
226230
var tran = new Transaction(db);
227231

228232
// Add account details with Json.Set to transaction
229-
tran.Json.SetAsync("accdetails:Jeeva", "$", new { name = "Jeeva", totalAmount= 1000, bankName = "City" });
233+
tran.Json.SetAsync("accdetails:Jeeva", "$", new { name = "Jeeva", totalAmount = 1000, bankName = "City" });
230234
tran.Json.SetAsync("accdetails:Shachar", "$", new { name = "Shachar", totalAmount = 1000, bankName = "City" });
231235

232236
// Get the Json response
@@ -240,8 +244,8 @@ public async Task TransactionExample()
240244
tran.Json.NumIncrbyAsync("accdetails:Shachar", "$.totalAmount", 200);
241245

242246
// Get total amount for both Jeeva = 800 & Shachar = 1200
243-
var totalAmtOfJeeva = tran.Json.GetAsync("accdetails:Jeeva", path:"$.totalAmount");
244-
var totalAmtOfShachar = tran.Json.GetAsync("accdetails:Shachar", path:"$.totalAmount");
247+
var totalAmtOfJeeva = tran.Json.GetAsync("accdetails:Jeeva", path: "$.totalAmount");
248+
var totalAmtOfShachar = tran.Json.GetAsync("accdetails:Shachar", path: "$.totalAmount");
245249

246250
// Execute the transaction
247251
var condition = tran.ExecuteAsync();
@@ -253,4 +257,26 @@ public async Task TransactionExample()
253257
Assert.Equal("[800]", totalAmtOfJeeva.Result.ToString());
254258
Assert.Equal("[1200]", totalAmtOfShachar.Result.ToString());
255259
}
260+
261+
[Fact]
262+
public void TestJsonConvert()
263+
{
264+
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
265+
IDatabase db = redis.GetDatabase();
266+
db.Execute("FLUSHALL");
267+
ISearchCommands ft = db.FT();
268+
IJsonCommands json = db.JSON();
269+
270+
ft.Create("test", new FTCreateParams().On(IndexDataType.JSON).Prefix("doc:"),
271+
new Schema().AddTagField(new FieldName("$.name", "name")));
272+
for (int i = 0; i < 10; i++)
273+
{
274+
json.Set("doc:" + i, "$", "{\"name\":\"foo\"}");
275+
}
276+
var res = ft.Search("test", new Query("@name:{foo}"));
277+
278+
var docs = res.ToJson();
279+
280+
Assert.Equal(10, docs.Count());
281+
}
256282
}

0 commit comments

Comments
 (0)