{
  "id": "queryjson",
  "title": "Index and query documents",
  "url": "https://redis.io/docs/latest/develop/clients/dotnet/nredisstack/queryjson/",
  "summary": "Learn how to use Redis Search with JSON and hash documents.",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-04-29T10:21:19-05:00",
  "page_type": "content",
  "content_hash": "bbff0d312d8653ea6a810d761fc03e708cedf1d3c2264839c1a1ffa9a19e69de",
  "sections": [
    {
      "id": "initialize",
      "title": "Initialize",
      "role": "content",
      "text": "Make sure that you have [Redis Open Source](https://redis.io/docs/latest/operate/oss_and_stack)\nor another Redis server available. Also install the\n[`NRedisStack`](https://redis.io/docs/latest/develop/clients/dotnet) client library if you\nhaven't already done so. \n\nAdd the following dependencies:\n\nFoundational: Import required libraries for Redis Search, JSON operations, and search functionality\n\n**Difficulty:** Beginner\n\n**Available in:** C#\n\n##### C#\n\n[code example]"
    },
    {
      "id": "create-data",
      "title": "Create data",
      "role": "content",
      "text": "Create some test data to add to the database:\n\nFoundational: Define sample user data structures for indexing and querying\n\n**Difficulty:** Beginner\n\n**Available in:** C#\n\n##### C#\n\n[code example]"
    },
    {
      "id": "add-the-index",
      "title": "Add the index",
      "role": "content",
      "text": "Connect to your Redis database. The code below shows the most\nbasic connection but see\n[Connect to the server](https://redis.io/docs/latest/develop/clients/dotnet/connect)\nto learn more about the available connection options.\n\nFoundational: Establish a connection to a Redis server for query operations\n\n**Difficulty:** Beginner\n\n**Available in:** C#\n\n##### C#\n\n[code example]\n\n\n\nDelete any existing index called `idx:users` and any keys that start with `user:`.\n\nFoundational: Clean up existing indexes and documents to prepare for fresh example data\n\n**Difficulty:** Beginner\n\n**Available in:** C#\n\n##### C#\n\n[code example]\n\n\n\nCreate an index. In this example, only JSON documents with the key prefix `user:` are indexed. For more information, see [Query syntax](https://redis.io/docs/latest/develop/ai/search-and-query/query/).\n\nFoundational: Create a search index for JSON documents with field definitions and key prefix filtering\n\n**Difficulty:** Intermediate\n\n**Available in:** C#\n\n##### C#\n\n[code example]"
    },
    {
      "id": "add-the-data",
      "title": "Add the data",
      "role": "content",
      "text": "Add the three sets of user data to the database as\n[JSON](https://redis.io/docs/latest/develop/data-types/json) objects.\nIf you use keys with the `user:` prefix then Redis will index the\nobjects automatically as you add them:\n\nFoundational: Store JSON documents in Redis with automatic indexing based on key prefix\n\n**Difficulty:** Beginner\n\n**Available in:** C#\n\n##### C#\n\n[code example]"
    },
    {
      "id": "query-the-data",
      "title": "Query the data",
      "role": "content",
      "text": "You can now use the index to search the JSON objects. The\n[query](https://redis.io/docs/latest/develop/ai/search-and-query/query)\nbelow searches for objects that have the text \"Paul\" in any field\nand have an `age` value in the range 30 to 40:\n\nQuery with filters: Search JSON documents using text matching and numeric range filters to find specific records\n\n**Difficulty:** Intermediate\n\n**Available in:** C#\n\n##### C#\n\n[code example]\n\n\n\nSpecify query options to return only the `city` field:\n\nQuery with field projection: Retrieve only specific fields from search results to reduce data transfer\n\n**Difficulty:** Intermediate\n\n**Available in:** C#\n\n##### C#\n\n[code example]\n\n\n\nUse an\n[aggregation query](https://redis.io/docs/latest/develop/ai/search-and-query/query/aggregation)\nto count all users in each city.\n\nAggregation queries: Use GROUP BY and COUNT operations to summarize and analyze indexed data\n\n**Difficulty:** Advanced\n\n**Available in:** C#\n\n##### C#\n\n[code example]"
    },
    {
      "id": "differences-with-hash-documents",
      "title": "Differences with hash documents",
      "role": "content",
      "text": "Indexing for hash documents is very similar to JSON indexing but you\nneed to specify some slightly different options.\n\nWhen you create the schema for a hash index, you don't need to\nadd aliases for the fields, since you use the basic names to access\nthe fields anyway. Also, you must set the `On` option to `IndexDataType.HASH`\nin the `FTCreateParams` object when you create the index. The code below shows\nthese changes with a new index called `hash-idx:users`, which is otherwise the\nsame as the `idx:users` index used for JSON documents in the previous examples.\n\nFirst, delete any existing index called `hash-idx:users` and any keys that start with `huser:`.\n\nFoundational: Clean up existing hash indexes and documents to prepare for fresh example data\n\n**Difficulty:** Beginner\n\n**Available in:** C#\n\n##### C#\n\n[code example]\n\n\n\nNow create the new index:\n\nFoundational: Create a search index for hash documents with HASH index type and field definitions\n\n**Difficulty:** Intermediate\n\n**Available in:** C#\n\n##### C#\n\n[code example]\n\n\n\nYou use [`HashSet()`](https://redis.io/docs/latest/commands/hset) to add the hash\ndocuments instead of [`JSON.Set()`](https://redis.io/docs/latest/commands/json.set).\nAlso, you must add the fields as key-value pairs instead of combining them\ninto a single object.\n\nFoundational: Store hash documents in Redis with automatic indexing based on key prefix\n\n**Difficulty:** Beginner\n\n**Available in:** C#\n\n##### C#\n\n[code example]\n\n\n\nThe query commands work the same here for hash as they do for JSON (but\nthe name of the hash index is different). The format of the result is\nalmost the same except that the fields are returned directly in the\n`Document` object of the result (for JSON, the fields are all enclosed\nin a string under the key `json`):\n\nQuery with filters: Search hash documents using text matching and numeric range filters (same as JSON queries)\n\n**Difficulty:** Intermediate\n\n**Available in:** C#\n\n##### C#\n\n[code example]"
    },
    {
      "id": "more-information",
      "title": "More information",
      "role": "content",
      "text": "See the [Redis Search](https://redis.io/docs/latest/develop/ai/search-and-query) docs\nfor a full description of all query features with examples."
    }
  ],
  "examples": [
    {
      "id": "initialize-ex0",
      "language": "csharp",
      "code": "using NRedisStack.RedisStackCommands;\nusing NRedisStack.Search;\nusing NRedisStack.Search.Aggregation;\nusing NRedisStack.Search.Literals.Enums;\nusing StackExchange.Redis;",
      "section_id": "initialize"
    },
    {
      "id": "create-data-ex0",
      "language": "csharp",
      "code": "var user1 = new\n        {\n            name = \"Paul John\",\n            email = \"paul.john@example.com\",\n            age = 42,\n            city = \"London\"\n        };\n\n        var user2 = new\n        {\n            name = \"Eden Zamir\",\n            email = \"eden.zamir@example.com\",\n            age = 29,\n            city = \"Tel Aviv\"\n        };\n\n        var user3 = new\n        {\n            name = \"Paul Zamir\",\n            email = \"paul.zamir@example.com\",\n            age = 35,\n            city = \"Tel Aviv\"\n        };",
      "section_id": "create-data"
    },
    {
      "id": "add-the-index-ex0",
      "language": "csharp",
      "code": "var muxer = ConnectionMultiplexer.Connect(\"localhost:6379\");\n        var db = muxer.GetDatabase();",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-index-ex1",
      "language": "csharp",
      "code": "db.KeyDelete([\"user:1\", \"user:2\", \"user:3\"]);\n        try { db.FT().DropIndex(\"idx:users\"); } catch { }",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-index-ex2",
      "language": "csharp",
      "code": "var schema = new Schema()\n            .AddTextField(new FieldName(\"$.name\", \"name\"))\n            .AddTagField(new FieldName(\"$.city\", \"city\"))\n            .AddNumericField(new FieldName(\"$.age\", \"age\"));\n\n        bool indexCreated = db.FT().Create(\n            \"idx:users\",\n            new FTCreateParams()\n                .On(IndexDataType.JSON)\n                .Prefix(\"user:\"),\n            schema\n        );",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-data-ex0",
      "language": "csharp",
      "code": "bool user1Set = db.JSON().Set(\"user:1\", \"$\", user1);\n        bool user2Set = db.JSON().Set(\"user:2\", \"$\", user2);\n        bool user3Set = db.JSON().Set(\"user:3\", \"$\", user3);",
      "section_id": "add-the-data"
    },
    {
      "id": "query-the-data-ex0",
      "language": "csharp",
      "code": "SearchResult findPaulResult = db.FT().Search(\n            \"idx:users\",\n            new(\"Paul @age:[30 40]\")\n        );\n        Console.WriteLine(string.Join(\n            \", \",\n            findPaulResult.Documents.Select(x => x[\"json\"])\n        ));\n        // >>> {\"name\":\"Paul Zamir\",\"email\":\"paul.zamir@example.com\", ...",
      "section_id": "query-the-data"
    },
    {
      "id": "query-the-data-ex1",
      "language": "csharp",
      "code": "var citiesResult = db.FT().Search(\n            \"idx:users\",\n            new Query(\"Paul\")\n                .ReturnFields(new FieldName(\"$.city\", \"city\"))\n        );\n        Console.WriteLine(string.Join(\n            \", \",\n            citiesResult.Documents.Select(x => x[\"city\"]).OrderBy(x => x)\n        ));\n        // >>> London, Tel Aviv",
      "section_id": "query-the-data"
    },
    {
      "id": "query-the-data-ex2",
      "language": "csharp",
      "code": "AggregationRequest aggRequest = new AggregationRequest(\"*\")\n            .GroupBy(\"@city\", Reducers.Count().As(\"count\"));\n\n        AggregationResult aggResult = db.FT().Aggregate(\"idx:users\", aggRequest);\n        IReadOnlyList<Dictionary<string, RedisValue>> resultsList =\n                                                        aggResult.GetResults();\n\n        for (var i = 0; i < resultsList.Count; i++)\n        {\n            Dictionary<string, RedisValue> item = resultsList.ElementAt(i);\n            Console.WriteLine($\"{item[\"city\"]} - {item[\"count\"]}\");\n        }\n        // >>> London - 1\n        // >>> Tel Aviv - 2",
      "section_id": "query-the-data"
    },
    {
      "id": "differences-with-hash-documents-ex0",
      "language": "csharp",
      "code": "db.KeyDelete([\"huser:1\", \"huser:2\", \"huser:3\"]);\n        try { db.FT().DropIndex(\"hash-idx:users\"); } catch { }",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex1",
      "language": "csharp",
      "code": "var hashSchema = new Schema()\n            .AddTextField(\"name\")\n            .AddTagField(\"city\")\n            .AddNumericField(\"age\");\n\n        bool hashIndexCreated = db.FT().Create(\n            \"hash-idx:users\",\n            new FTCreateParams()\n                .On(IndexDataType.HASH)\n                .Prefix(\"huser:\"),\n            hashSchema\n        );",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex2",
      "language": "csharp",
      "code": "db.HashSet(\"huser:1\", [\n            new(\"name\", \"Paul John\"),\n            new(\"email\", \"paul.john@example.com\"),\n            new(\"age\", 42),\n            new(\"city\", \"London\")\n        ]);\n\n        db.HashSet(\"huser:2\", [\n            new(\"name\", \"Eden Zamir\"),\n            new(\"email\", \"eden.zamir@example.com\"),\n            new(\"age\", 29),\n            new(\"city\", \"Tel Aviv\")\n        ]);\n\n        db.HashSet(\"huser:3\", [\n            new(\"name\", \"Paul Zamir\"),\n            new(\"email\", \"paul.zamir@example.com\"),\n            new(\"age\", 35),\n            new(\"city\", \"Tel Aviv\")\n        ]);",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex3",
      "language": "csharp",
      "code": "SearchResult findPaulHashResult = db.FT().Search(\n            \"hash-idx:users\",\n            new(\"Paul @age:[30 40]\")\n        );\n\n        foreach (Document doc in findPaulHashResult.Documents)\n        {\n            Console.WriteLine(\n                $\"Name: {doc[\"name\"]}, email: {doc[\"email\"]}, \" +\n                $\"age: {doc[\"age\"]}, city:{doc[\"city\"]}\"\n            );\n        }\n        // >>> Name: Paul Zamir, email: paul.zamir@example.com, age: 35, ...",
      "section_id": "differences-with-hash-documents"
    }
  ]
}
