# Index and query documents

```json metadata
{
  "schema_version": 2,
  "title": "Index and query documents",
  "description": "Learn how to use Redis Search with JSON and hash documents.",
  "categories": ["docs","develop","stack","oss","rs","rc","oss","kubernetes","clients"],
  "topics": ["Redis Search","JSON","hash"],
  "relatedPages": ["/develop/clients/php/vecsearch","/develop/ai/search-and-query"],
  "scope": "example",
  "tableOfContents": {"sections":[{"id":"initialize","title":"Initialize"},{"id":"create-data","title":"Create data"},{"id":"add-the-index","title":"Add the index"},{"id":"add-the-data","title":"Add the data"},{"id":"query-the-data","title":"Query the data"},{"children":[{"id":"bulk-import-with-himport","title":"Bulk import with HIMPORT"}],"id":"differences-with-hash-documents","title":"Differences with hash documents"},{"id":"more-information","title":"More information"}]}

,
  "codeExamples": [{"codetabsId":"php_home_json-stepimport","description":"Foundational: Import required dependencies for Redis Search and JSON operations","difficulty":"beginner","id":"import","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepimport"}]},{"codetabsId":"php_home_json-stepcreate_data","description":"Foundational: Create sample JSON data structures for indexing and querying","difficulty":"beginner","id":"create_data","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepcreate_data"}]},{"codetabsId":"php_home_json-stepconnect","description":"Foundational: Connect to a Redis server and establish a client connection","difficulty":"beginner","id":"connect","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepconnect"}]},{"codetabsId":"php_home_json-stepmake_index","description":"Foundational: Create a search index for JSON documents with field schema and prefix filtering","difficulty":"intermediate","id":"make_index","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepmake_index"}]},{"codetabsId":"php_home_json-stepadd_data","description":"Foundational: Store JSON documents with indexed key prefixes for automatic indexing","difficulty":"beginner","id":"add_data","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepadd_data"}]},{"codetabsId":"php_home_json-stepquery1","description":"Query data: Execute full-text and range queries on indexed JSON documents using FT.SEARCH","difficulty":"intermediate","id":"query1","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepquery1"}]},{"codetabsId":"php_home_json-stepquery2","description":"Restrict query results: Use query options to return specific fields from search results","difficulty":"intermediate","id":"query2","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepquery2"}]},{"codetabsId":"php_home_json-stepquery3","description":"Aggregation: Use aggregation queries to group and count results from indexed documents","difficulty":"advanced","id":"query3","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepquery3"}]},{"codetabsId":"php_home_json-stepmake_hash_index","description":"Foundational: Create a search index for hash documents with HASH type specification","difficulty":"intermediate","id":"make_hash_index","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepmake_hash_index"}]},{"codetabsId":"php_home_json-stepadd_hash_data","description":"Foundational: Store hash documents using HSET for indexed retrieval","difficulty":"beginner","id":"add_hash_data","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepadd_hash_data"}]},{"codetabsId":"php_home_json-stepquery1_hash","description":"Query data: Query hash documents using the same search syntax as JSON with different result formatting","difficulty":"intermediate","id":"query1_hash","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepquery1_hash"}]},{"buildsUpon":["add_hash_data"],"codetabsId":"php_home_json-stepadd_hash_himport","description":"Bulk ingestion: Import hash documents as compact hashes using HIMPORT PREPARE and a pipeline of HIMPORT SET calls","difficulty":"intermediate","id":"add_hash_himport","languages":[{"clientId":"predis","clientName":"Predis","id":"PHP","langId":"php","panelId":"panel_PHP_php_home_json-stepadd_hash_himport"}]}]
}
```

## Code Examples Legend

The code examples below show how to perform the same operations in different programming languages and client libraries:

- **Redis CLI**: Command-line interface for Redis
- **C# (Synchronous)**: StackExchange.Redis synchronous client
- **C# (Asynchronous)**: StackExchange.Redis asynchronous client
- **Go**: go-redis client
- **Java (Synchronous - Jedis)**: Jedis synchronous client
- **Java (Asynchronous - Lettuce)**: Lettuce asynchronous client
- **Java (Reactive - Lettuce)**: Lettuce reactive/streaming client
- **JavaScript (Node.js)**: node-redis client
- **PHP**: Predis client
- **Python**: redis-py client
- **Rust (Synchronous)**: redis-rs synchronous client
- **Rust (Asynchronous)**: redis-rs asynchronous client

Each code example demonstrates the same basic operation across different languages. The specific syntax and patterns vary based on the language and client library, but the underlying Redis commands and behavior remain consistent.

---


This example shows how to create a
[search index](https://redis.io/docs/latest/develop/ai/search-and-query/indexing)
for [JSON](https://redis.io/docs/latest/develop/data-types/json) documents and
run queries against the index. It then goes on to show the slight differences
in the equivalent code for [hash](https://redis.io/docs/latest/develop/data-types/hashes)
documents.

> [!NOTE]
> From [v3.0.0](https://github.com/predis/predis/releases/tag/v3.0.0) onwards,
> `Predis` uses query dialect 2 by default.
> Redis Search methods such as [`ftSearch()`](https://redis.io/docs/latest/commands/ft.search)
> will explicitly request this dialect, overriding the default set for the server.
> See
> [Query dialects](https://redis.io/docs/latest/develop/ai/search-and-query/advanced-concepts/dialects)
> for more information.

## Initialize

Make sure that you have [Redis Open Source](https://redis.io/docs/latest/operate/oss_and_stack)
or another Redis server available. Also install the
[`Predis`](https://redis.io/docs/latest/develop/clients/php) client library if you
haven't already done so.

Add the following dependencies:

Foundational: Import required dependencies for Redis Search and JSON operations

**Difficulty:** Beginner

**Available in:** PHP

##### PHP

```php
<?php

require 'vendor/autoload.php';

use Predis\Client as PredisClient;

use Predis\Command\Argument\Search\AggregateArguments;
use Predis\Command\Argument\Search\CreateArguments;
use Predis\Command\Argument\Search\SearchArguments;
use Predis\Command\Argument\Search\SchemaFields\NumericField;
use Predis\Command\Argument\Search\SchemaFields\TextField;
use Predis\Command\Argument\Search\SchemaFields\TagField;
```



## Create data

Create some test data to add to your database:

Foundational: Create sample JSON data structures for indexing and querying

**Difficulty:** Beginner

**Available in:** PHP

##### PHP

```php
        $user1 = json_encode([
            'name' => 'Paul John',
            'email' => 'paul.john@example.com',
            'age' => 42,
            'city' => 'London',
        ], JSON_THROW_ON_ERROR);
        
        $user2 = json_encode([
            'name' => 'Eden Zamir',
            'email' => 'eden.zamir@example.com',
            'age' => 29,
            'city' => 'Tel Aviv',
        ], JSON_THROW_ON_ERROR);
        
        $user3 = json_encode([
            'name' => 'Paul Zamir',
            'email' => 'paul.zamir@example.com',
            'age' => 35,
            'city' => 'Tel Aviv',
        ], JSON_THROW_ON_ERROR);
```



## Add the index

Connect to your Redis database. The code below shows the most
basic connection but see
[Connect to the server](https://redis.io/docs/latest/develop/clients/php/connect)
to learn more about the available connection options.

Foundational: Connect to a Redis server and establish a client connection

**Difficulty:** Beginner

**Available in:** PHP

##### PHP

```php
        $r = new PredisClient([
            'scheme'   => 'tcp',
            'host'     => '127.0.0.1',
            'port'     => 6379,
            'password' => '',
            'database' => 0,
        ]);
```



Create an
[index](https://redis.io/docs/latest/develop/ai/search-and-query/indexing).
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).

Foundational: Create a search index for JSON documents with field schema and prefix filtering

**Difficulty:** Intermediate

**Available in:** PHP

##### PHP

```php
        $schema = [
            new TextField('$.name', 'name'),
            new TagField('$.city', 'city'),
            new NumericField('$.age', "age"),
        ];
        
        try {
        $r->ftCreate("idx:users", $schema,
            (new CreateArguments())
                ->on('JSON')
                ->prefix(["user:"]));
        }
        catch (Exception $e) {
            echo $e->getMessage(), PHP_EOL;
        }
```



## Add the data

Add the three sets of user data to the database as
[JSON](https://redis.io/docs/latest/develop/data-types/json) objects.
If you use keys with the `user:` prefix then Redis will index the
objects automatically as you add them:

Foundational: Store JSON documents with indexed key prefixes for automatic indexing

**Difficulty:** Beginner

**Available in:** PHP

##### PHP

```php
        $r->jsonset('user:1', '$', $user1);
        $r->jsonset('user:2', '$', $user2);
        $r->jsonset('user:3', '$', $user3);
```



## Query the data

You can now use the index to search the JSON objects. The
[query](https://redis.io/docs/latest/develop/ai/search-and-query/query)
below searches for objects that have the text "Paul" in any field
and have an `age` value in the range 30 to 40:

Query data: Execute full-text and range queries on indexed JSON documents using FT.SEARCH

**Difficulty:** Intermediate

**Available in:** PHP

##### PHP

```php
        $res = $r->ftSearch("idx:users", "Paul @age:[30 40]");
        echo json_encode($res), PHP_EOL;
        // >>> [1,"user:3",["$","{\"name\":\"Paul Zamir\",\"email\":\"paul.zamir@example.com\",\"age\":35,\"city\":\"Tel Aviv\"}"]]
```



Specify query options to return only the `city` field:

Restrict query results: Use query options to return specific fields from search results

**Difficulty:** Intermediate

**Available in:** PHP

##### PHP

```php
        $arguments = new SearchArguments();
        $arguments->addReturn(3, '$.city', true, 'thecity');
        $arguments->dialect(2);
        $arguments->limit(0, 5);

        $res = $r->ftSearch("idx:users", "Paul", $arguments);

        echo json_encode($res), PHP_EOL;
        // >>> [2,"user:1",["thecity","London"],"user:3",["thecity","Tel Aviv"]]
```



Use an
[aggregation query](https://redis.io/docs/latest/develop/ai/search-and-query/query/aggregation)
to count all users in each city.

Aggregation: Use aggregation queries to group and count results from indexed documents

**Difficulty:** Advanced

**Available in:** PHP

##### PHP

```php
        $ftAggregateArguments = (new AggregateArguments())
            ->groupBy('@city')
            ->reduce('COUNT', true, 'count');

        $res = $r->ftAggregate('idx:users', '*', $ftAggregateArguments);
        echo json_encode($res), PHP_EOL;
        // >>> [2,["city","London","count","1"],["city","Tel Aviv","count","2"]]
```



## 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 use `HASH` for the `On()` option
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.

Foundational: Create a search index for hash documents with HASH type specification

**Difficulty:** Intermediate

**Available in:** PHP

##### PHP

```php
        $hashSchema = [
            new TextField('name'),
            new TagField('city'),
            new NumericField('age'),
        ];
        
        try {
        $r->ftCreate("hash-idx:users", $hashSchema,
            (new CreateArguments())
                ->on('HASH')
                ->prefix(["huser:"]));
        }
        catch (Exception $e) {
            echo $e->getMessage(), PHP_EOL;
        }
```



You use [`hmset()`](https://redis.io/docs/latest/commands/hset) to add the hash
documents instead of [`jsonset()`](https://redis.io/docs/latest/commands/json.set).
Supply the fields as an array directly, without using
[`json_encode()`](https://www.php.net/manual/en/function.json-encode.php).

Foundational: Store hash documents using HSET for indexed retrieval

**Difficulty:** Beginner

**Available in:** PHP

##### PHP

```php
        $r->hmset('huser:1', [
            'name' => 'Paul John',
            'email' => 'paul.john@example.com',
            'age' => 42,
            'city' => 'London',
        ]);
        
        $r->hmset('huser:2', [
            'name' => 'Eden Zamir',
            'email' => 'eden.zamir@example.com',
            'age' => 29,
            'city' => 'Tel Aviv',
        ]);
        
        $r->hmset('huser:3', [
            'name' => 'Paul Zamir',
            'email' => 'paul.zamir@example.com',
            'age' => 35,
            'city' => 'Tel Aviv',
        ]);
```



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
result array rather than in a JSON string with `$` as its key:

Query data: Query hash documents using the same search syntax as JSON with different result formatting

**Difficulty:** Intermediate

**Available in:** PHP

##### PHP

```php
        $res = $r->ftSearch("hash-idx:users", "Paul @age:[30 40]");
        echo json_encode($res), PHP_EOL;
        // >>> [1,"huser:3",["name","Paul Zamir","email","paul.zamir@example.com","age","35","city","Tel Aviv"]]
```



### Bulk import with HIMPORT

From Redis Open Source 8.10, you can also add the hash documents with the
[`HIMPORT`](https://redis.io/docs/latest/commands/himport) command family. This creates the same
hashes as `hmset()`, but lets Redis store them as
[compact hashes](https://redis.io/docs/latest/develop/data-types/hashes#compact-hashes), which use
less memory when many keys share the same field names. Redis Search indexes
these hashes in the same way.

Declare the field names once by calling `himport()` with
[`PREPARE`](https://redis.io/docs/latest/commands/himport-prepare), then create each
document by calling it with [`SET`](https://redis.io/docs/latest/commands/himport-set), passing only
its values, in the same order as the field names. Use a
[pipeline](https://redis.io/docs/latest/develop/clients/php/transpipe) to send all the
imports in one round trip:

Bulk ingestion: Import hash documents as compact hashes using HIMPORT PREPARE and a pipeline of HIMPORT SET calls

**Difficulty:** Intermediate

**Builds upon:** add_hash_data

**Available in:** PHP

##### PHP

```php
        $himportRes = $r->pipeline(function ($pipe) {
            $pipe->himport('PREPARE', 'huser', ['name', 'email', 'age', 'city']);

            $pipe->himport('SET', 'huser:1', 'huser', ['Paul John', 'paul.john@example.com', 42, 'London']);
            $pipe->himport('SET', 'huser:2', 'huser', ['Eden Zamir', 'eden.zamir@example.com', 29, 'Tel Aviv']);
            $pipe->himport('SET', 'huser:3', 'huser', ['Paul Zamir', 'paul.zamir@example.com', 35, 'Tel Aviv']);
        });
```



`HIMPORT SET` replaces any existing key, so running this code after the
`hmset()` calls leaves you with the same three documents. The query returns
the same result, although the fields can appear in a different order.

> [!NOTE]
> `HIMPORT` requires `Predis` v3.6.0 or later, and `Predis` marks its
> support as experimental, so the API might change. Redis Cloud and
> Redis Software don't support `HIMPORT`.

## More information

See the [Redis Search](https://redis.io/docs/latest/develop/ai/search-and-query) docs
for a full description of all query features with examples.

