Index and query documents

Learn how to use the Redis query engine with JSON and hash documents.

This example shows how to create a search index for JSON documents and run queries against the index. It then goes on to show the slight differences in the equivalent code for hash documents.

Note:
From v1.0.0 onwards, NRedisStack uses query dialect 2 by default. Redis query engine methods such as FT().Search() will explicitly request this dialect, overriding the default set for the server. See Query dialects for more information.

Initialize

Make sure that you have Redis Open Source or another Redis server available. Also install the NRedisStack client library if you haven't already done so.

Add the following dependencies:


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

Create data

Create some test data to add to the database:


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

Add the index

Connect to your Redis database. The code below shows the most basic connection but see Connect to the server to learn more about the available connection options.


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

Create an index. In this example, only JSON documents with the key prefix user: are indexed. For more information, see Query syntax.


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

Add the data

Add the three sets of user data to the database as JSON objects. If you use keys with the user: prefix then Redis will index the objects automatically as you add them:


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

Query the data

You can now use the index to search the JSON objects. The query below searches for objects that have the text "Paul" in any field and have an age value in the range 30 to 40:


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

Specify query options to return only the city field:


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

Use an aggregation query to count all users in each city.


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

Differences with hash documents

Indexing for hash documents is very similar to JSON indexing but you need to specify some slightly different options.

When you create the schema for a hash index, you don't need to add aliases for the fields, since you use the basic names to access the fields anyway. Also, you must set the On option to IndexDataType.HASH in the FTCreateParams object when you create the index. The code below shows these changes with a new index called hash-idx:users, which is otherwise the same as the idx:users index used for JSON documents in the previous examples.


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

You use HashSet() to add the hash documents instead of JSON.Set(). Also, you must add the fields as key-value pairs instead of combining them into a single object.


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

The query commands work the same here for hash as they do for JSON (but the name of the hash index is different). The format of the result is almost the same except that the fields are returned directly in the Document object of the result (for JSON, the fields are all enclosed in a string under the key json):


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 = "[email protected]",
            age = 42,
            city = "London"
        };

        var user2 = new
        {
            name = "Eden Zamir",
            email = "[email protected]",
            age = 29,
            city = "Tel Aviv"
        };

        var user3 = new
        {
            name = "Paul Zamir",
            email = "[email protected]",
            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
        );


        bool user1Set = db.JSON().Set("user:1", "$", user1);
        bool user2Set = db.JSON().Set("user:2", "$", user2);
        bool user3Set = db.JSON().Set("user:3", "$", user3);


        SearchResult findPaulResult = db.FT().Search(
            "idx:users",
            new("Paul @age:[30 40]")
        );
        Console.WriteLine(string.Join(
            ", ",
            findPaulResult.Documents.Select(x => x["json"])
        ));
        // >>> {"name":"Paul Zamir","email":"[email protected]", ...


        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


        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

        var hashSchema = new Schema()
            .AddTextField("name")
            .AddTagField("city")
            .AddNumericField("age");

        bool hashIndexCreated = db.FT().Create(
            "hash-idx:users",
            new FTCreateParams()
                .On(IndexDataType.HASH)
                .Prefix("huser:"),
            hashSchema
        );

        db.HashSet("huser:1", [
            new("name", "Paul John"),
            new("email", "[email protected]"),
            new("age", 42),
            new("city", "London")
        ]);

        db.HashSet("huser:2", [
            new("name", "Eden Zamir"),
            new("email", "[email protected]"),
            new("age", 29),
            new("city", "Tel Aviv")
        ]);

        db.HashSet("huser:3", [
            new("name", "Paul Zamir"),
            new("email", "[email protected]"),
            new("age", 35),
            new("city", "Tel Aviv")
        ]);

        SearchResult findPaulHashResult = db.FT().Search(
            "hash-idx:users",
            new("Paul @age:[30 40]")
        );

        foreach (Document doc in findPaulHashResult.Documents)
        {
            Console.WriteLine(
                $"Name: {doc["name"]}, email: {doc["email"]}, " +
                $"age: {doc["age"]}, city:{doc["city"]}"
            );
        }
        // >>> Name: Paul Zamir, email: [email protected], age: 35, ...
    }
}

More information

See the Redis query engine docs for a full description of all query features with examples.

RATE THIS PAGE
Back to top ↑