{
  "schema_version": 2,
  "id": "develop/clients/go/queryjson",
  "title": "Index and query documents",
  "url": "https://redis.io/docs/latest/develop/clients/go/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-10-16T16:25:49+01:00",
  "page_type": "content",
  "content_hash": "af3047cc2481accc11d0433018ff39928b621caab99994c26112ac01cc14493d",
  "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[`go-redis`](https://redis.io/docs/latest/develop/clients/go) client library if you\nhaven't already done so.\n\nAdd the following dependencies:\n\nFoundational: Import go-redis package, which includes support for Redis Search operations\n\n**Difficulty:** Beginner\n\n**Available in:** Go\n\n##### Go\n\n[code example]"
    },
    {
      "id": "create-data",
      "title": "Create data",
      "role": "content",
      "text": "Create some test data to add to your database. The example data shown\nbelow is compatible with both JSON and hash objects.\n\nFoundational: Create sample user data structures for indexing and querying\n\n**Difficulty:** Beginner\n\n**Available in:** Go\n\n##### Go\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/go/connect)\nto learn more about the available connection options.\n\nFoundational: Establish a connection to Redis with RESP2 protocol for Redis Search operations\n\n**Difficulty:** Beginner\n\n**Available in:** Go\n\n##### Go\n\n[code example]\n\n\n&nbsp;\n\n> [!NOTE]\n> The connection options in the example specify\n> [RESP2](https://redis.io/docs/latest/develop/reference/protocol-spec) in the `Protocol`\n> field. We recommend that you use RESP2 for Redis Search operations in `go-redis`\n> because some of the response structures for the default RESP3 are currently\n> incomplete and so you must handle the \"raw\" responses in your own code.\n>\n> If you do want to use RESP3, you should set the `UnstableResp3` option when\n> you connect:\n>\n> [code example]\n>\n> You must also access command results using the `RawResult()` and `RawVal()` methods\n> rather than the usual `Result()` and `Val()`:\n>\n> [code example]\n\nUse the code below to create a search index. The `FTCreateOptions` parameter enables\nindexing only for JSON objects where the key has a `user:` prefix.\nThe\n[schema](https://redis.io/docs/latest/develop/ai/search-and-query/indexing)\nfor the index has three fields for the user's name, age, and city.\nThe `FieldName` field of the `FieldSchema` struct specifies a\n[JSON path](https://redis.io/docs/latest/develop/data-types/json/path)\nthat identifies which data field to index. Use the `As` struct field\nto provide an alias for the JSON path expression. You can use\nthe alias in queries as a short and intuitive way to refer to the\nexpression, instead of typing it in full:\n\nFoundational: Create a search index for JSON documents with field definitions and key prefix filtering\n\n**Difficulty:** Beginner\n\n**Available in:** Go\n\n##### Go\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 with automatic indexing using JSONSet with matching key prefix\n\n**Difficulty:** Beginner\n\n**Available in:** Go\n\n##### Go\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 data: Execute a full-text search with numeric range filtering using FTSearchWithArgs\n\n**Difficulty:** Intermediate\n\n**Available in:** Go\n\n##### Go\n\n[code example]\n\n\n\nSpecify query options to return only the `city` field:\n\nRestrict query results: Limit query results to specific fields using FTSearchOptions to reduce data transfer\n\n**Difficulty:** Intermediate\n\n**Available in:** Go\n\n##### Go\n\n[code example]\n\n\n\nYou can also use the same query with the `CountOnly` option\nenabled to get the number of documents found without\nreturning the documents themselves.\n\nPerformance optimization: Get document count without retrieving results using CountOnly option for better performance\n\n**Difficulty:** Intermediate\n\n**Available in:** Go\n\n##### Go\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: Perform aggregation queries to group and count documents by field values using FTAggregateWithArgs\n\n**Difficulty:** Intermediate\n\n**Available in:** Go\n\n##### Go\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 `OnHash` to `true` in the `FTCreateOptions`\nobject when you create the index. The code below shows these changes with\na new index called `hash-idx:users`, which is otherwise the same as\nthe `idx:users` index used for JSON documents in the previous examples.\n\nFoundational: Create a search index for hash documents with OnHash option and simplified field schema\n\n**Difficulty:** Intermediate\n\n**Available in:** Go\n\n##### Go\n\n[code example]\n\n\n\nYou use [`HSet()`](https://redis.io/docs/latest/commands/hset) to add the hash\ndocuments instead of [`JSONSet()`](https://redis.io/docs/latest/commands/json.set),\nbut the same flat `userX` maps work equally well with either\nhash or JSON:\n\nFoundational: Store hash documents with automatic indexing using HSet with matching key prefix\n\n**Difficulty:** Beginner\n\n**Available in:** Go\n\n##### Go\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 map of the result (for JSON, the fields are all enclosed\nin a string under the key \"$\"):\n\nQuery data: Execute search queries on hash documents with slightly different result structure compared to JSON\n\n**Difficulty:** Intermediate\n\n**Available in:** Go\n\n##### Go\n\n[code example]"
    },
    {
      "id": "bulk-import-with-himport",
      "title": "Bulk import with HIMPORT",
      "role": "content",
      "text": "From Redis Open Source 8.10, you can also add the hash documents with the\n[`HIMPORT`](https://redis.io/docs/latest/commands/himport) command family. This creates the same\nhashes as `HSet()`, but lets Redis store them as\n[compact hashes](https://redis.io/docs/latest/develop/data-types/hashes#compact-hashes), which use\nless memory when many keys share the same field names. Redis Search indexes\nthese hashes in the same way.\n\nDeclare the field names once with\n[`HImportPrepare()`](https://redis.io/docs/latest/commands/himport-prepare), then create each\ndocument with [`HImportSet()`](https://redis.io/docs/latest/commands/himport-set), passing only\nits values, in the same order as the field names. Use a\n[pipeline](https://redis.io/docs/latest/develop/clients/go/transpipe) to send all the\nimports in one round trip:\n\nBulk ingestion: Import hash documents as compact hashes using HIMPORT PREPARE and a pipeline of HIMPORT SET calls\n\n**Difficulty:** Intermediate\n\n**Builds upon:** add_hash_data\n\n**Available in:** Go\n\n##### Go\n\n[code example]\n\n\n\n`HImportSet()` replaces any existing key, so running this code after the\n`HSet()` calls leaves you with the same three documents. The query returns\nthe same result.\n\n> [!NOTE]\n> `HIMPORT` requires `go-redis` v9.22.0 or later, and `go-redis` marks its\n> support as experimental, so the API might change. Redis Cloud and\n> Redis Software don't support `HIMPORT`."
    },
    {
      "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": "go",
      "code": "import (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com/redis/go-redis/v9\"\n)",
      "section_id": "initialize"
    },
    {
      "id": "create-data-ex0",
      "language": "go",
      "code": "user1 := map[string]interface{}{\n\t\t\"name\":  \"Paul John\",\n\t\t\"email\": \"paul.john@example.com\",\n\t\t\"age\":   42,\n\t\t\"city\":  \"London\",\n\t}\n\n\tuser2 := map[string]interface{}{\n\t\t\"name\":  \"Eden Zamir\",\n\t\t\"email\": \"eden.zamir@example.com\",\n\t\t\"age\":   29,\n\t\t\"city\":  \"Tel Aviv\",\n\t}\n\n\tuser3 := map[string]interface{}{\n\t\t\"name\":  \"Paul Zamir\",\n\t\t\"email\": \"paul.zamir@example.com\",\n\t\t\"age\":   35,\n\t\t\"city\":  \"Tel Aviv\",\n\t}",
      "section_id": "create-data"
    },
    {
      "id": "add-the-index-ex0",
      "language": "go",
      "code": "ctx := context.Background()\n\n\trdb := redis.NewClient(&redis.Options{\n\t\tAddr:     \"localhost:6379\",\n\t\tPassword: \"\", // no password docs\n\t\tDB:       0,  // use default DB\n\t\tProtocol: 2,\n\t})",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-index-ex1",
      "language": "go",
      "code": "> rdb := redis.NewClient(&redis.Options{\n>     UnstableResp3: true,\n>     // Other options...\n> })\n>",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-index-ex2",
      "language": "go",
      "code": "> res1, err := client.FTSearchWithArgs(\n>     ctx, \"txt\", \"foo bar\", &redis.FTSearchOptions{},\n> ).RawResult()\n> val1 := client.FTSearchWithArgs(\n>     ctx, \"txt\", \"foo bar\", &redis.FTSearchOptions{},\n> ).RawVal()\n>",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-index-ex3",
      "language": "go",
      "code": "_, err := rdb.FTCreate(\n\t\tctx,\n\t\t\"idx:users\",\n\t\t// Options:\n\t\t&redis.FTCreateOptions{\n\t\t\tOnJSON: true,\n\t\t\tPrefix: []interface{}{\"user:\"},\n\t\t},\n\t\t// Index schema fields:\n\t\t&redis.FieldSchema{\n\t\t\tFieldName: \"$.name\",\n\t\t\tAs:        \"name\",\n\t\t\tFieldType: redis.SearchFieldTypeText,\n\t\t},\n\t\t&redis.FieldSchema{\n\t\t\tFieldName: \"$.city\",\n\t\t\tAs:        \"city\",\n\t\t\tFieldType: redis.SearchFieldTypeTag,\n\t\t},\n\t\t&redis.FieldSchema{\n\t\t\tFieldName: \"$.age\",\n\t\t\tAs:        \"age\",\n\t\t\tFieldType: redis.SearchFieldTypeNumeric,\n\t\t},\n\t).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-data-ex0",
      "language": "go",
      "code": "_, err = rdb.JSONSet(ctx, \"user:1\", \"$\", user1).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = rdb.JSONSet(ctx, \"user:2\", \"$\", user2).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = rdb.JSONSet(ctx, \"user:3\", \"$\", user3).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}",
      "section_id": "add-the-data"
    },
    {
      "id": "query-the-data-ex0",
      "language": "go",
      "code": "findPaulResult, err := rdb.FTSearch(\n\t\tctx,\n\t\t\"idx:users\",\n\t\t\"Paul @age:[30 40]\",\n\t).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(findPaulResult)\n\t// >>> {1 [{user:3 <nil> <nil> <nil> map[$:{\"age\":35,\"city\":\"Tel Aviv\"...",
      "section_id": "query-the-data"
    },
    {
      "id": "query-the-data-ex1",
      "language": "go",
      "code": "citiesResult, err := rdb.FTSearchWithArgs(\n\t\tctx,\n\t\t\"idx:users\",\n\t\t\"Paul\",\n\t\t&redis.FTSearchOptions{\n\t\t\tReturn: []redis.FTSearchReturn{\n\t\t\t\t{\n\t\t\t\t\tFieldName: \"$.city\",\n\t\t\t\t\tAs:        \"city\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsort.Slice(citiesResult.Docs, func(i, j int) bool {\n\t\treturn citiesResult.Docs[i].Fields[\"city\"] < citiesResult.Docs[j].Fields[\"city\"]\n\t})\n\n\tfor _, result := range citiesResult.Docs {\n\t\tfmt.Println(result.Fields[\"city\"])\n\t}\n\t// >>> London\n\t// >>> Tel Aviv",
      "section_id": "query-the-data"
    },
    {
      "id": "query-the-data-ex2",
      "language": "go",
      "code": "citiesResult2, err := rdb.FTSearchWithArgs(\n\t\tctx,\n\t\t\"idx:users\",\n\t\t\"Paul\",\n\t\t&redis.FTSearchOptions{\n\t\t\tReturn: []redis.FTSearchReturn{\n\t\t\t\t{\n\t\t\t\t\tFieldName: \"$.city\",\n\t\t\t\t\tAs:        \"city\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tCountOnly: true,\n\t\t},\n\t).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The `Total` field has the correct number of docs found\n\t// by the query but the `Docs` slice is empty.\n\tfmt.Println(len(citiesResult2.Docs)) // >>> 0\n\tfmt.Println(citiesResult2.Total)     // >>> 2",
      "section_id": "query-the-data"
    },
    {
      "id": "query-the-data-ex3",
      "language": "go",
      "code": "aggOptions := redis.FTAggregateOptions{\n\t\tGroupBy: []redis.FTAggregateGroupBy{\n\t\t\t{\n\t\t\t\tFields: []interface{}{\"@city\"},\n\t\t\t\tReduce: []redis.FTAggregateReducer{\n\t\t\t\t\t{\n\t\t\t\t\t\tReducer: redis.SearchCount,\n\t\t\t\t\t\tAs:      \"count\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\taggResult, err := rdb.FTAggregateWithArgs(\n\t\tctx,\n\t\t\"idx:users\",\n\t\t\"*\",\n\t\t&aggOptions,\n\t).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsort.Slice(aggResult.Rows, func(i, j int) bool {\n\t\treturn aggResult.Rows[i].Fields[\"city\"].(string) <\n\t\t\taggResult.Rows[j].Fields[\"city\"].(string)\n\t})\n\n\tfor _, row := range aggResult.Rows {\n\t\tfmt.Printf(\"%v - %v\\n\",\n\t\t\trow.Fields[\"city\"], row.Fields[\"count\"],\n\t\t)\n\t}\n\t// >>> City: London - 1\n\t// >>> City: Tel Aviv - 2",
      "section_id": "query-the-data"
    },
    {
      "id": "differences-with-hash-documents-ex0",
      "language": "go",
      "code": "_, err := rdb.FTCreate(\n\t\tctx,\n\t\t\"hash-idx:users\",\n\t\t// Options:\n\t\t&redis.FTCreateOptions{\n\t\t\tOnHash: true,\n\t\t\tPrefix: []interface{}{\"huser:\"},\n\t\t},\n\t\t// Index schema fields:\n\t\t&redis.FieldSchema{\n\t\t\tFieldName: \"name\",\n\t\t\tFieldType: redis.SearchFieldTypeText,\n\t\t},\n\t\t&redis.FieldSchema{\n\t\t\tFieldName: \"city\",\n\t\t\tFieldType: redis.SearchFieldTypeTag,\n\t\t},\n\t\t&redis.FieldSchema{\n\t\t\tFieldName: \"age\",\n\t\t\tFieldType: redis.SearchFieldTypeNumeric,\n\t\t},\n\t).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex1",
      "language": "go",
      "code": "_, err = rdb.HSet(ctx, \"huser:1\", user1).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = rdb.HSet(ctx, \"huser:2\", user2).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = rdb.HSet(ctx, \"huser:3\", user3).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex2",
      "language": "go",
      "code": "findPaulHashResult, err := rdb.FTSearch(\n\t\tctx,\n\t\t\"hash-idx:users\",\n\t\t\"Paul @age:[30 40]\",\n\t).Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(findPaulHashResult)\n\t// >>> {1 [{huser:3 <nil> <nil> <nil> map[age:35 city:Tel Aviv...",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "bulk-import-with-himport-ex0",
      "language": "go",
      "code": "fields := []string{\"name\", \"email\", \"age\", \"city\"}\n\n\terr = rdb.HImportPrepare(ctx, \"huser\", fields...).Err()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tpipe := rdb.Pipeline()\n\n\tfor i, user := range []map[string]interface{}{user1, user2, user3} {\n\t\tvalues := make([]interface{}, len(fields))\n\t\tfor j, field := range fields {\n\t\t\tvalues[j] = user[field]\n\t\t}\n\n\t\tpipe.HImportSet(ctx, fmt.Sprintf(\"huser:%d\", i+1), \"huser\", values...)\n\t}\n\n\tif _, err := pipe.Exec(ctx); err != nil {\n\t\tpanic(err)\n\t}",
      "section_id": "bulk-import-with-himport"
    }
  ]
}
