{
  "schema_version": 2,
  "id": "develop/clients/redis-py/queryjson",
  "title": "Index and query documents",
  "url": "https://redis.io/docs/latest/develop/clients/redis-py/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": "2ec0dcb3fba5b42068a5073a18bf411b850475e7d5fef7986ccaa2c3d2aa5f01",
  "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[`redis-py`](https://redis.io/docs/latest/develop/clients/redis-py) client library if you\nhaven't already done so.\n\nAdd the following dependencies. All of them are applicable to both JSON and hash,\nexcept for the `Path` class, which is specific to JSON (see\n[Path](https://redis.io/docs/latest/develop/data-types/json/path) for a description of the\nJSON path syntax).\n\nFoundational: Import required libraries for Redis Search, JSON operations, and search functionality\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: Define sample user data structures for indexing and querying\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/redis-py/connect)\nto learn more about the available connection options.\n\nFoundational: Establish a connection to a Redis server for query operations\n\n[code example]\n\n\n\nThe example uses an index called `idx:users` for JSON documents and adds\nsome JSON documents with the `user:` key prefix. To avoid errors, first\ndelete any existing index or documents whose names that might\nconflict with the example:\n\nFoundational: Clean up existing indexes and documents to prepare for fresh example data\n\n[code example]\n\n\n\nCreate an index for the JSON data. The code below specifies that only JSON documents with\nthe key prefix `user:` are indexed. For more information, see\n[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[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[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[code example]\n\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[code example]\n\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[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 use `HASH` for the `IndexType`\nwhen you create the index.\n\nFirst delete any existing index or documents\nwhose names might conflict with the hash example:\n\nFoundational: Clean up existing hash indexes and documents to prepare for fresh example data\n\n[code example]\n\n\n\n\nCreate a 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 HASH index type and field definitions\n\n[code example]\n\n\n\n\nYou use [`hset()`](https://redis.io/docs/latest/commands/hset) to add the hash\ndocuments instead of [`json().set()`](https://redis.io/docs/latest/commands/json.set),\nbut the same flat `userX` dictionaries work equally well with either\nhash or JSON:\n\nFoundational: Store hash documents in Redis with automatic indexing based on key prefix\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\nresult `Document` object instead of in an enclosing `json` dictionary:\n\nQuery with filters: Search hash documents using text matching and numeric range filters (same as JSON queries)\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[`himport_prepare()`](https://redis.io/docs/latest/commands/himport-prepare), then create each\ndocument with [`himport_set()`](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/redis-py/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:** Python\n\n##### Python\n\n[code example]\n\n\n\n`himport_set()` 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, although the fields can appear in a different order.\n\n> [!NOTE]\n> `HIMPORT` requires `redis-py` v8.1.0 or later, and `redis-py` 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": "python",
      "code": "import redis\nfrom redis.commands.json.path import Path\nimport redis.commands.search.aggregation as aggregations\nimport redis.commands.search.reducers as reducers\nfrom redis.commands.search.field import TextField, NumericField, TagField\nfrom redis.commands.search.index_definition import IndexDefinition, IndexType\nfrom redis.commands.search.query import Query\nimport redis.exceptions",
      "section_id": "initialize"
    },
    {
      "id": "create-data-ex0",
      "language": "python",
      "code": "user1 = {\n    \"name\": \"Paul John\",\n    \"email\": \"paul.john@example.com\",\n    \"age\": 42,\n    \"city\": \"London\"\n}\n\nuser2 = {\n    \"name\": \"Eden Zamir\",\n    \"email\": \"eden.zamir@example.com\",\n    \"age\": 29,\n    \"city\": \"Tel Aviv\"\n}\n\nuser3 = {\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": "python",
      "code": "r = redis.Redis(decode_responses=True)",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-index-ex1",
      "language": "python",
      "code": "try:\n    r.ft(\"idx:users\").dropindex(True)\nexcept redis.exceptions.ResponseError:\n    pass\n\nr.delete(\"user:1\", \"user:2\", \"user:3\")",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-index-ex2",
      "language": "python",
      "code": "schema = (\n    TextField(\"$.name\", as_name=\"name\"),\n    TagField(\"$.city\", as_name=\"city\"),\n    NumericField(\"$.age\", as_name=\"age\")\n)\n\nindexCreated = r.ft(\"idx:users\").create_index(\n    schema,\n    definition=IndexDefinition(\n        prefix=[\"user:\"], index_type=IndexType.JSON\n    )\n)",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-data-ex0",
      "language": "python",
      "code": "user1Set = r.json().set(\"user:1\", Path.root_path(), user1)\nuser2Set = r.json().set(\"user:2\", Path.root_path(), user2)\nuser3Set = r.json().set(\"user:3\", Path.root_path(), user3)",
      "section_id": "add-the-data"
    },
    {
      "id": "query-the-data-ex0",
      "language": "python",
      "code": "findPaulResult = r.ft(\"idx:users\").search(\n    Query(\"Paul @age:[30 40]\")\n)\n\nprint(findPaulResult)\n# >>> Result{1 total, docs: [Document {'id': 'user:3', ...",
      "section_id": "query-the-data"
    },
    {
      "id": "query-the-data-ex1",
      "language": "python",
      "code": "citiesResult = r.ft(\"idx:users\").search(\n    Query(\"Paul\").return_field(\"$.city\", as_field=\"city\")\n).docs\n\nprint(citiesResult)\n# >>> [Document {'id': 'user:1', 'payload': None, ...",
      "section_id": "query-the-data"
    },
    {
      "id": "query-the-data-ex2",
      "language": "python",
      "code": "req = aggregations.AggregateRequest(\"*\").group_by(\n    '@city', reducers.count().alias('count')\n)\n\naggResult = r.ft(\"idx:users\").aggregate(req).rows\nprint(aggResult)\n# >>> [['city', 'London', 'count', '1'], ['city', 'Tel Aviv', 'count', '2']]",
      "section_id": "query-the-data"
    },
    {
      "id": "differences-with-hash-documents-ex0",
      "language": "python",
      "code": "try:\n    r.ft(\"hash-idx:users\").dropindex(True)\nexcept redis.exceptions.ResponseError:\n    pass\n\nr.delete(\"huser:1\", \"huser:2\", \"huser:3\")",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex1",
      "language": "python",
      "code": "hashSchema = (\n    TextField(\"name\"),\n    TagField(\"city\"),\n    NumericField(\"age\")\n)\n\nhashIndexCreated = r.ft(\"hash-idx:users\").create_index(\n    hashSchema,\n    definition=IndexDefinition(\n        prefix=[\"huser:\"], index_type=IndexType.HASH\n    )\n)",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex2",
      "language": "python",
      "code": "huser1Set = r.hset(\"huser:1\", mapping=user1)\nhuser2Set = r.hset(\"huser:2\", mapping=user2)\nhuser3Set = r.hset(\"huser:3\", mapping=user3)",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex3",
      "language": "python",
      "code": "findPaulHashResult = r.ft(\"hash-idx:users\").search(\n    Query(\"Paul @age:[30 40]\")\n)\n\nprint(findPaulHashResult)\n# >>> Result{1 total, docs: [Document {'id': 'huser:3',\n# >>>   'payload': None, 'name': 'Paul Zamir', ...",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "bulk-import-with-himport-ex0",
      "language": "python",
      "code": "fields = [\"name\", \"email\", \"age\", \"city\"]\nr.himport_prepare(\"huser\", fields)\n\nwith r.pipeline(transaction=False) as pipe:\n    for key, user in [(\"huser:1\", user1), (\"huser:2\", user2), (\"huser:3\", user3)]:\n        pipe.himport_set(key, \"huser\", [user[f] for f in fields])\n    himportRes = pipe.execute()",
      "section_id": "bulk-import-with-himport"
    }
  ]
}
