{
  "schema_version": 2,
  "id": "develop/clients/php/queryjson",
  "title": "Index and query documents",
  "url": "https://redis.io/docs/latest/develop/clients/php/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": "a6a7d06c47ec87523525b73972546dab14e5de26150ed3d88547eb868fef90d1",
  "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[`Predis`](https://redis.io/docs/latest/develop/clients/php) client library if you\nhaven't already done so.\n\nAdd the following dependencies:\n\nFoundational: Import required dependencies for Redis Search and JSON operations\n\n**Difficulty:** Beginner\n\n**Available in:** PHP\n\n##### PHP\n\n[code example]"
    },
    {
      "id": "create-data",
      "title": "Create data",
      "role": "content",
      "text": "Create some test data to add to your database:\n\nFoundational: Create sample JSON data structures for indexing and querying\n\n**Difficulty:** Beginner\n\n**Available in:** PHP\n\n##### PHP\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/php/connect)\nto learn more about the available connection options.\n\nFoundational: Connect to a Redis server and establish a client connection\n\n**Difficulty:** Beginner\n\n**Available in:** PHP\n\n##### PHP\n\n[code example]\n\n\n\nCreate an\n[index](https://redis.io/docs/latest/develop/ai/search-and-query/indexing).\nIn this example, only JSON documents with the key prefix `user:` are indexed.\nFor 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 schema and prefix filtering\n\n**Difficulty:** Intermediate\n\n**Available in:** PHP\n\n##### PHP\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 indexed key prefixes for automatic indexing\n\n**Difficulty:** Beginner\n\n**Available in:** PHP\n\n##### PHP\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 full-text and range queries on indexed JSON documents using FT.SEARCH\n\n**Difficulty:** Intermediate\n\n**Available in:** PHP\n\n##### PHP\n\n[code example]\n\n\n\nSpecify query options to return only the `city` field:\n\nRestrict query results: Use query options to return specific fields from search results\n\n**Difficulty:** Intermediate\n\n**Available in:** PHP\n\n##### PHP\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: Use aggregation queries to group and count results from indexed documents\n\n**Difficulty:** Advanced\n\n**Available in:** PHP\n\n##### PHP\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 `On()` option\nwhen 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 HASH type specification\n\n**Difficulty:** Intermediate\n\n**Available in:** PHP\n\n##### PHP\n\n[code example]\n\n\n\nYou use [`hmset()`](https://redis.io/docs/latest/commands/hset) to add the hash\ndocuments instead of [`jsonset()`](https://redis.io/docs/latest/commands/json.set).\nSupply the fields as an array directly, without using\n[`json_encode()`](https://www.php.net/manual/en/function.json-encode.php).\n\nFoundational: Store hash documents using HSET for indexed retrieval\n\n**Difficulty:** Beginner\n\n**Available in:** PHP\n\n##### PHP\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 array rather than in a JSON string with `$` as its key:\n\nQuery data: Query hash documents using the same search syntax as JSON with different result formatting\n\n**Difficulty:** Intermediate\n\n**Available in:** PHP\n\n##### PHP\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 `hmset()`, 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 by calling `himport()` with\n[`PREPARE`](https://redis.io/docs/latest/commands/himport-prepare), then create each\ndocument by calling it with [`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/php/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:** PHP\n\n##### PHP\n\n[code example]\n\n\n\n`HIMPORT SET` replaces any existing key, so running this code after the\n`hmset()` 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 `Predis` v3.6.0 or later, and `Predis` 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": "php",
      "code": "<?php\n\nrequire 'vendor/autoload.php';\n\nuse Predis\\Client as PredisClient;\n\nuse Predis\\Command\\Argument\\Search\\AggregateArguments;\nuse Predis\\Command\\Argument\\Search\\CreateArguments;\nuse Predis\\Command\\Argument\\Search\\SearchArguments;\nuse Predis\\Command\\Argument\\Search\\SchemaFields\\NumericField;\nuse Predis\\Command\\Argument\\Search\\SchemaFields\\TextField;\nuse Predis\\Command\\Argument\\Search\\SchemaFields\\TagField;",
      "section_id": "initialize"
    },
    {
      "id": "create-data-ex0",
      "language": "php",
      "code": "$user1 = json_encode([\n            'name' => 'Paul John',\n            'email' => 'paul.john@example.com',\n            'age' => 42,\n            'city' => 'London',\n        ], JSON_THROW_ON_ERROR);\n        \n        $user2 = json_encode([\n            'name' => 'Eden Zamir',\n            'email' => 'eden.zamir@example.com',\n            'age' => 29,\n            'city' => 'Tel Aviv',\n        ], JSON_THROW_ON_ERROR);\n        \n        $user3 = json_encode([\n            'name' => 'Paul Zamir',\n            'email' => 'paul.zamir@example.com',\n            'age' => 35,\n            'city' => 'Tel Aviv',\n        ], JSON_THROW_ON_ERROR);",
      "section_id": "create-data"
    },
    {
      "id": "add-the-index-ex0",
      "language": "php",
      "code": "$r = new PredisClient([\n            'scheme'   => 'tcp',\n            'host'     => '127.0.0.1',\n            'port'     => 6379,\n            'password' => '',\n            'database' => 0,\n        ]);",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-index-ex1",
      "language": "php",
      "code": "$schema = [\n            new TextField('$.name', 'name'),\n            new TagField('$.city', 'city'),\n            new NumericField('$.age', \"age\"),\n        ];\n        \n        try {\n        $r->ftCreate(\"idx:users\", $schema,\n            (new CreateArguments())\n                ->on('JSON')\n                ->prefix([\"user:\"]));\n        }\n        catch (Exception $e) {\n            echo $e->getMessage(), PHP_EOL;\n        }",
      "section_id": "add-the-index"
    },
    {
      "id": "add-the-data-ex0",
      "language": "php",
      "code": "$r->jsonset('user:1', '$', $user1);\n        $r->jsonset('user:2', '$', $user2);\n        $r->jsonset('user:3', '$', $user3);",
      "section_id": "add-the-data"
    },
    {
      "id": "query-the-data-ex0",
      "language": "php",
      "code": "$res = $r->ftSearch(\"idx:users\", \"Paul @age:[30 40]\");\n        echo json_encode($res), PHP_EOL;\n        // >>> [1,\"user:3\",[\"$\",\"{\\\"name\\\":\\\"Paul Zamir\\\",\\\"email\\\":\\\"paul.zamir@example.com\\\",\\\"age\\\":35,\\\"city\\\":\\\"Tel Aviv\\\"}\"]]",
      "section_id": "query-the-data"
    },
    {
      "id": "query-the-data-ex1",
      "language": "php",
      "code": "$arguments = new SearchArguments();\n        $arguments->addReturn(3, '$.city', true, 'thecity');\n        $arguments->dialect(2);\n        $arguments->limit(0, 5);\n\n        $res = $r->ftSearch(\"idx:users\", \"Paul\", $arguments);\n\n        echo json_encode($res), PHP_EOL;\n        // >>> [2,\"user:1\",[\"thecity\",\"London\"],\"user:3\",[\"thecity\",\"Tel Aviv\"]]",
      "section_id": "query-the-data"
    },
    {
      "id": "query-the-data-ex2",
      "language": "php",
      "code": "$ftAggregateArguments = (new AggregateArguments())\n            ->groupBy('@city')\n            ->reduce('COUNT', true, 'count');\n\n        $res = $r->ftAggregate('idx:users', '*', $ftAggregateArguments);\n        echo json_encode($res), PHP_EOL;\n        // >>> [2,[\"city\",\"London\",\"count\",\"1\"],[\"city\",\"Tel Aviv\",\"count\",\"2\"]]",
      "section_id": "query-the-data"
    },
    {
      "id": "differences-with-hash-documents-ex0",
      "language": "php",
      "code": "$hashSchema = [\n            new TextField('name'),\n            new TagField('city'),\n            new NumericField('age'),\n        ];\n        \n        try {\n        $r->ftCreate(\"hash-idx:users\", $hashSchema,\n            (new CreateArguments())\n                ->on('HASH')\n                ->prefix([\"huser:\"]));\n        }\n        catch (Exception $e) {\n            echo $e->getMessage(), PHP_EOL;\n        }",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex1",
      "language": "php",
      "code": "$r->hmset('huser:1', [\n            'name' => 'Paul John',\n            'email' => 'paul.john@example.com',\n            'age' => 42,\n            'city' => 'London',\n        ]);\n        \n        $r->hmset('huser:2', [\n            'name' => 'Eden Zamir',\n            'email' => 'eden.zamir@example.com',\n            'age' => 29,\n            'city' => 'Tel Aviv',\n        ]);\n        \n        $r->hmset('huser:3', [\n            'name' => 'Paul Zamir',\n            'email' => 'paul.zamir@example.com',\n            'age' => 35,\n            'city' => 'Tel Aviv',\n        ]);",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "differences-with-hash-documents-ex2",
      "language": "php",
      "code": "$res = $r->ftSearch(\"hash-idx:users\", \"Paul @age:[30 40]\");\n        echo json_encode($res), PHP_EOL;\n        // >>> [1,\"huser:3\",[\"name\",\"Paul Zamir\",\"email\",\"paul.zamir@example.com\",\"age\",\"35\",\"city\",\"Tel Aviv\"]]",
      "section_id": "differences-with-hash-documents"
    },
    {
      "id": "bulk-import-with-himport-ex0",
      "language": "php",
      "code": "$himportRes = $r->pipeline(function ($pipe) {\n            $pipe->himport('PREPARE', 'huser', ['name', 'email', 'age', 'city']);\n\n            $pipe->himport('SET', 'huser:1', 'huser', ['Paul John', 'paul.john@example.com', 42, 'London']);\n            $pipe->himport('SET', 'huser:2', 'huser', ['Eden Zamir', 'eden.zamir@example.com', 29, 'Tel Aviv']);\n            $pipe->himport('SET', 'huser:3', 'huser', ['Paul Zamir', 'paul.zamir@example.com', 35, 'Tel Aviv']);\n        });",
      "section_id": "bulk-import-with-himport"
    }
  ]
}
