Skip to content

Commit baa9f81

Browse files
Merge pull request #1465 from redis/DOC-5108-js-hash-query-examples
DOC-5108 and DOC-5112 hash query examples for JS and PHP
2 parents 3eecd96 + 7d9affc commit baa9f81

File tree

2 files changed

+203
-33
lines changed

2 files changed

+203
-33
lines changed

content/develop/clients/nodejs/queryjson.md

Lines changed: 93 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,27 @@ categories:
99
- oss
1010
- kubernetes
1111
- clients
12-
description: Learn how to use the Redis Query Engine with JSON
13-
linkTitle: Index and query JSON
14-
title: Example - Index and query JSON documents
12+
description: Learn how to use the Redis Query Engine with JSON and hash documents.
13+
linkTitle: Index and query documents
14+
title: Index and query documents
1515
weight: 2
1616
---
1717

1818
This example shows how to create a
1919
[search index]({{< relref "/develop/interact/search-and-query/indexing" >}})
20-
for [JSON]({{< relref "/develop/data-types/json" >}}) data and
21-
run queries against the index.
20+
for [JSON]({{< relref "/develop/data-types/json" >}}) documents and
21+
run queries against the index. It then goes on to show the slight differences
22+
in the equivalent code for [hash]({{< relref "/develop/data-types/hashes" >}})
23+
documents.
2224

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

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

2734
```js
2835
import {
@@ -33,14 +40,10 @@ import {
3340
} from 'redis';
3441
```
3542

36-
Connect to the database:
37-
38-
```js
39-
const client = await createClient();
40-
await client.connect();
41-
```
43+
## Create data
4244

43-
Create some test data to add to the database:
45+
Create some test data to add to your database. The example data shown
46+
below is compatible with both JSON and hash objects.
4447

4548
```js
4649
const user1 = {
@@ -65,6 +68,18 @@ const user3 = {
6568
};
6669
```
6770

71+
## Add the index
72+
73+
Connect to your Redis database. The code below shows the most
74+
basic connection but see
75+
[Connect to the server]({{< relref "/develop/clients/nodejs/connect" >}})
76+
to learn more about the available connection options.
77+
78+
```js
79+
const client = await createClient();
80+
await client.connect();
81+
```
82+
6883
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/" >}}).
6984

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

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

123+
## Query the data
124+
106125
You can now use the index to search the JSON objects. The
107126
[query]({{< relref "/develop/interact/search-and-query/query" >}})
108127
below searches for objects that have the text "Paul" in any field
@@ -161,6 +180,66 @@ Finally, close the connection to Redis.
161180
await client.quit();
162181
```
163182

183+
## Differences with hash documents
184+
185+
Indexing for hash documents is very similar to JSON indexing but you
186+
need to specify some slightly different options.
187+
188+
When you create the schema for a hash index, you don't need to
189+
add aliases for the fields, since you use the basic names to access
190+
the fields anyway. Also, you must use `HASH` for the `ON` option
191+
when you create the index. The code below shows these changes with
192+
a new index called `hash-idx:users`, which is otherwise the same as
193+
the `idx:users` index used for JSON documents in the previous examples.
194+
195+
```js
196+
await client.ft.create('hash-idx:users', {
197+
'name': {
198+
type: SchemaFieldTypes.TEXT
199+
},
200+
'city': {
201+
type: SchemaFieldTypes.TEXT
202+
},
203+
'age': {
204+
type: SchemaFieldTypes.NUMERIC
205+
}
206+
}, {
207+
ON: 'HASH',
208+
PREFIX: 'huser:'
209+
});
210+
```
211+
212+
You use [`hSet()`]({{< relref "/commands/hset" >}}) to add the hash
213+
documents instead of [`json.set()`]({{< relref "/commands/json.set" >}}),
214+
but the same flat `userX` objects work equally well with either
215+
hash or JSON:
216+
217+
```js
218+
const [huser1Reply, huser2Reply, huser3Reply] = await Promise.all([
219+
client.hSet('huser:1', user1),
220+
client.hSet('huser:2', user2),
221+
client.hSet('huser:3', user3)
222+
]);
223+
```
224+
225+
The query commands work the same here for hash as they do for JSON (but
226+
the name of the hash index is different). The format of the result is
227+
also the same:
228+
229+
```js
230+
let findPaulHashResult = await client.ft.search(
231+
'hash-idx:users', 'Paul @age:[30 40]'
232+
);
233+
234+
console.log(findPaulHashResult.total); // >>> 1
235+
236+
findPaulHashResult.documents.forEach(doc => {
237+
console.log(`ID: ${doc.id}, name: ${doc.value.name}, age: ${doc.value.age}`);
238+
});
239+
// >>> ID: huser:3, name: Paul Zamir, age: 35
240+
```
241+
242+
## More information
164243

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

content/develop/clients/php/queryjson.md

Lines changed: 110 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,27 @@ categories:
99
- oss
1010
- kubernetes
1111
- clients
12-
description: Learn how to use the Redis query engine with JSON
13-
linkTitle: Index and query JSON
14-
title: Example - Index and query JSON documents
12+
description: Learn how to use the Redis query engine with JSON and hash documents.
13+
linkTitle: Index and query documents
14+
title: Index and query documents
1515
weight: 20
1616
---
1717

18-
This example shows how to index and query Redis JSON data using `predis`.
18+
This example shows how to create a
19+
[search index]({{< relref "/develop/interact/search-and-query/indexing" >}})
20+
for [JSON]({{< relref "/develop/data-types/json" >}}) documents and
21+
run queries against the index. It then goes on to show the slight differences
22+
in the equivalent code for [hash]({{< relref "/develop/data-types/hashes" >}})
23+
documents.
1924

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

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

2534
```php
2635
<?php
@@ -38,19 +47,9 @@ use Predis\Command\Argument\Search\SchemaFields\TagField;
3847
use Predis\Command\Argument\Search\SchemaFields\VectorField;
3948
```
4049

41-
Connect to the Redis server:
42-
43-
```php
44-
$r = new PredisClient([
45-
'scheme' => 'tcp',
46-
'host' => '127.0.0.1',
47-
'port' => 6379,
48-
'password' => '',
49-
'database' => 0,
50-
]);
51-
```
50+
## Create data
5251

53-
Create some test data to add to the database:
52+
Create some test data to add to your database:
5453

5554
```php
5655
$user1 = json_encode([
@@ -75,6 +74,23 @@ $user3 = json_encode([
7574
], JSON_THROW_ON_ERROR);
7675
```
7776

77+
## Add the index
78+
79+
Connect to your Redis database. The code below shows the most
80+
basic connection but see
81+
[Connect to the server]({{< relref "/develop/clients/php/connect" >}})
82+
to learn more about the available connection options.
83+
84+
```php
85+
$r = new PredisClient([
86+
'scheme' => 'tcp',
87+
'host' => '127.0.0.1',
88+
'port' => 6379,
89+
'password' => '',
90+
'database' => 0,
91+
]);
92+
```
93+
7894
Create an
7995
[index]({{< relref "/develop/interact/search-and-query/indexing" >}}).
8096
In this example, only JSON documents with the key prefix `user:` are indexed.
@@ -99,6 +115,8 @@ catch (Exception $e) {
99115
}
100116
```
101117

118+
## Add the data
119+
102120
Add the three sets of user data to the database as
103121
[JSON]({{< relref "/develop/data-types/json" >}}) objects.
104122
If you use keys with the `user:` prefix then Redis will index the
@@ -110,6 +128,8 @@ $r->jsonset('user:2', '$', $user2);
110128
$r->jsonset('user:3', '$', $user3);
111129
```
112130

131+
## Query the data
132+
113133
You can now use the index to search the JSON objects. The
114134
[query]({{< relref "/develop/interact/search-and-query/query" >}})
115135
below searches for objects that have the text "Paul" in any field
@@ -149,5 +169,76 @@ echo json_encode($res), PHP_EOL;
149169
// >>> [2,["city","London","count","1"],["city","Tel Aviv","count","2"]]
150170
```
151171

172+
## Differences with hash documents
173+
174+
Indexing for hash documents is very similar to JSON indexing but you
175+
need to specify some slightly different options.
176+
177+
When you create the schema for a hash index, you don't need to
178+
add aliases for the fields, since you use the basic names to access
179+
the fields anyway. Also, you must use `HASH` for the `On()` option
180+
when you create the index. The code below shows these changes with
181+
a new index called `hash-idx:users`, which is otherwise the same as
182+
the `idx:users` index used for JSON documents in the previous examples.
183+
184+
```php
185+
$hashSchema = [
186+
new TextField('name'),
187+
new TagField('city'),
188+
new NumericField('age'),
189+
];
190+
191+
try {
192+
$r->ftCreate("hash-idx:users", $hashSchema,
193+
(new CreateArguments())
194+
->on('HASH')
195+
->prefix(["huser:"]));
196+
}
197+
catch (Exception $e) {
198+
echo $e->getMessage(), PHP_EOL;
199+
}
200+
```
201+
202+
You use [`hmset()`]({{< relref "/commands/hset" >}}) to add the hash
203+
documents instead of [`jsonset()`]({{< relref "/commands/json.set" >}}).
204+
Supply the fields as an array directly, without using
205+
[`json_encode()`](https://www.php.net/manual/en/function.json-encode.php).
206+
207+
```php
208+
$r->hmset('huser:1', [
209+
'name' => 'Paul John',
210+
'email' => 'paul.john@example.com',
211+
'age' => 42,
212+
'city' => 'London',
213+
]);
214+
215+
$r->hmset('huser:2', [
216+
'name' => 'Eden Zamir',
217+
'email' => 'eden.zamir@example.com',
218+
'age' => 29,
219+
'city' => 'Tel Aviv',
220+
]);
221+
222+
$r->hmset('huser:3', [
223+
'name' => 'Paul Zamir',
224+
'email' => 'paul.zamir@example.com',
225+
'age' => 35,
226+
'city' => 'Tel Aviv',
227+
]);
228+
```
229+
230+
The query commands work the same here for hash as they do for JSON (but
231+
the name of the hash index is different). The format of the result is
232+
almost the same except that the fields are returned directly in the
233+
result array rather than in a JSON string with `$` as its key:
234+
235+
```php
236+
$res = $r->ftSearch("hash-idx:users", "Paul @age:[30 40]");
237+
echo json_encode($res), PHP_EOL;
238+
// >>> [1,"huser:3",["age","35","city","Tel Aviv","email","paul.zamir@example.com","name","Paul Zamir"]]
239+
```
240+
241+
## More information
242+
152243
See the [Redis query engine]({{< relref "/develop/interact/search-and-query" >}}) docs
153244
for a full description of all query features with examples.

0 commit comments

Comments
 (0)