Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 93 additions & 14 deletions content/develop/clients/nodejs/queryjson.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,27 @@ categories:
- oss
- kubernetes
- clients
description: Learn how to use the Redis Query Engine with JSON
linkTitle: Index and query JSON
title: Example - Index and query JSON documents
description: Learn how to use the Redis Query Engine with JSON and hash documents.
linkTitle: Index and query documents
title: Index and query documents
weight: 2
---

This example shows how to create a
[search index]({{< relref "/develop/interact/search-and-query/indexing" >}})
for [JSON]({{< relref "/develop/data-types/json" >}}) data and
run queries against the index.
for [JSON]({{< relref "/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]({{< relref "/develop/data-types/hashes" >}})
documents.

Make sure that you have Redis Stack and `node-redis` installed.
## Initialize

Start by importing dependencies:
Make sure that you have [Redis Community Edition]({{< relref "/operate/oss_and_stack/" >}})
or another Redis server available. Also install the
[`node-redis`]({{< relref "/develop/clients/nodejs" >}}) client library if you
haven't already done so.

Add the following dependencies:

```js
import {
Expand All @@ -33,14 +40,10 @@ import {
} from 'redis';
```

Connect to the database:

```js
const client = await createClient();
await client.connect();
```
## Create data

Create some test data to add to the database:
Create some test data to add to your database. The example data shown
below is compatible with both JSON and hash objects.

```js
const user1 = {
Expand All @@ -65,6 +68,18 @@ const user3 = {
};
```

## Add the index

Connect to your Redis database. The code below shows the most
basic connection but see
[Connect to the server]({{< relref "/develop/clients/nodejs/connect" >}})
to learn more about the available connection options.

```js
const client = await createClient();
await client.connect();
```

Create an index. In this example, only JSON documents with the key prefix `user:` are indexed. For more information, see [Query syntax]({{< relref "/develop/interact/search-and-query/query/" >}}).

```js
Expand All @@ -87,6 +102,8 @@ await client.ft.create('idx:users', {
});
```

## Add the data

Add the three sets of user data to the database as
[JSON]({{< relref "/develop/data-types/json" >}}) objects.
If you use keys with the `user:` prefix then Redis will index the
Expand All @@ -103,6 +120,8 @@ const [user1Reply, user2Reply, user3Reply] = await Promise.all([
]);
```

## Query the data

You can now use the index to search the JSON objects. The
[query]({{< relref "/develop/interact/search-and-query/query" >}})
below searches for objects that have the text "Paul" in any field
Expand Down Expand Up @@ -161,6 +180,66 @@ Finally, close the connection to Redis.
await client.quit();
```

## 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.

```js
await client.ft.create('hash-idx:users', {
'name': {
type: SchemaFieldTypes.TEXT
},
'city': {
type: SchemaFieldTypes.TEXT
},
'age': {
type: SchemaFieldTypes.NUMERIC
}
}, {
ON: 'HASH',
PREFIX: 'huser:'
});
```

You use [`hSet()`]({{< relref "/commands/hset" >}}) to add the hash
documents instead of [`json.set()`]({{< relref "/commands/json.set" >}}),
but the same flat `userX` objects work equally well with either
hash or JSON:

```js
const [huser1Reply, huser2Reply, huser3Reply] = await Promise.all([
client.hSet('huser:1', user1),
client.hSet('huser:2', user2),
client.hSet('huser:3', user3)
]);
```

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
also the same:

```js
let findPaulHashResult = await client.ft.search(
'hash-idx:users', 'Paul @age:[30 40]'
);

console.log(findPaulHashResult.total); // >>> 1

findPaulHashResult.documents.forEach(doc => {
console.log(`ID: ${doc.id}, name: ${doc.value.name}, age: ${doc.value.age}`);
});
// >>> ID: huser:3, name: Paul Zamir, age: 35
```

## More information

See the [Redis Query Engine]({{< relref "/develop/interact/search-and-query" >}}) docs
for a full description of all query features with examples.
129 changes: 110 additions & 19 deletions content/develop/clients/php/queryjson.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,27 @@ categories:
- oss
- kubernetes
- clients
description: Learn how to use the Redis query engine with JSON
linkTitle: Index and query JSON
title: Example - Index and query JSON documents
description: Learn how to use the Redis query engine with JSON and hash documents.
linkTitle: Index and query documents
title: Index and query documents
weight: 20
---

This example shows how to index and query Redis JSON data using `predis`.
This example shows how to create a
[search index]({{< relref "/develop/interact/search-and-query/indexing" >}})
for [JSON]({{< relref "/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]({{< relref "/develop/data-types/hashes" >}})
documents.

Make sure that you have Redis Community Edition and `predis` installed, as described
in the [Install](#install) section above.
## Initialize

Start by importing dependencies:
Make sure that you have [Redis Community Edition]({{< relref "/operate/oss_and_stack/" >}})
or another Redis server available. Also install the
[`Predis`]({{< relref "/develop/clients/php" >}}) client library if you
haven't already done so.

Add the following dependencies:

```php
<?php
Expand All @@ -38,19 +47,9 @@ use Predis\Command\Argument\Search\SchemaFields\TagField;
use Predis\Command\Argument\Search\SchemaFields\VectorField;
```

Connect to the Redis server:

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

Create some test data to add to the database:
Create some test data to add to your database:

```php
$user1 = json_encode([
Expand All @@ -75,6 +74,23 @@ $user3 = json_encode([
], 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]({{< relref "/develop/clients/php/connect" >}})
to learn more about the available connection options.

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

Create an
[index]({{< relref "/develop/interact/search-and-query/indexing" >}}).
In this example, only JSON documents with the key prefix `user:` are indexed.
Expand All @@ -99,6 +115,8 @@ catch (Exception $e) {
}
```

## Add the data

Add the three sets of user data to the database as
[JSON]({{< relref "/develop/data-types/json" >}}) objects.
If you use keys with the `user:` prefix then Redis will index the
Expand All @@ -110,6 +128,8 @@ $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]({{< relref "/develop/interact/search-and-query/query" >}})
below searches for objects that have the text "Paul" in any field
Expand Down Expand Up @@ -149,5 +169,76 @@ 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.

```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()`]({{< relref "/commands/hset" >}}) to add the hash
documents instead of [`jsonset()`]({{< relref "/commands/json.set" >}}).
Supply the fields as an array directly, without using
[`json_encode()`](https://www.php.net/manual/en/function.json-encode.php).

```php
$r->hmset('huser:1', [
'name' => 'Paul John',
'email' => '[email protected]',
'age' => 42,
'city' => 'London',
]);

$r->hmset('huser:2', [
'name' => 'Eden Zamir',
'email' => '[email protected]',
'age' => 29,
'city' => 'Tel Aviv',
]);

$r->hmset('huser:3', [
'name' => 'Paul Zamir',
'email' => '[email protected]',
'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:

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

## More information

See the [Redis query engine]({{< relref "/develop/interact/search-and-query" >}}) docs
for a full description of all query features with examples.