Skip to content

Commit 7d58f05

Browse files
author
Simon Prickett
committed
Some refactoring.
1 parent 99b261b commit 7d58f05

File tree

1 file changed

+32
-19
lines changed

1 file changed

+32
-19
lines changed

examples/search-json.js

Lines changed: 32 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,50 +2,63 @@
22

33
import { createClient, SchemaFieldTypes, AggregateGroupByReducers, AggregateSteps } from 'redis';
44

5-
async function searchPlusJson() {
5+
async function searchJSON() {
66
const client = createClient();
77

88
await client.connect();
99

10-
// Create an index
11-
await client.ft.create('users', {
12-
'$.name': {
13-
type: SchemaFieldTypes.TEXT,
14-
SORTABLE: 'UNF'
15-
},
16-
'$.age': SchemaFieldTypes.NUMERIC,
17-
'$.coins': SchemaFieldTypes.NUMERIC
18-
}, {
19-
ON: 'JSON'
20-
});
10+
// Create an index.
11+
try {
12+
await client.ft.create('idx:users', {
13+
'$.name': {
14+
type: SchemaFieldTypes.TEXT,
15+
SORTABLE: 'UNF'
16+
},
17+
'$.age': SchemaFieldTypes.NUMERIC,
18+
'$.coins': SchemaFieldTypes.NUMERIC
19+
}, {
20+
ON: 'JSON',
21+
PREFIX: 'noderedis:users'
22+
});
23+
} catch (e) {
24+
if (e.message === 'Index already exists') {
25+
console.log('Index exists already, skipped creation.');
26+
} else {
27+
// Something went wrong, perhaps RediSearch isn't installed...
28+
console.error(e);
29+
process.exit(1);
30+
}
31+
}
2132

22-
// Add some users
33+
// Add some users.
2334
await Promise.all([
24-
client.json.set('users:1', '$', {
35+
client.json.set('noderedis:users:1', '$', {
2536
name: 'Alice',
2637
age: 32,
2738
coins: 100
2839
}),
29-
client.json.set('users:2', '$', {
40+
client.json.set('noderedis:users:2', '$', {
3041
name: 'Bob',
3142
age: 23,
3243
coins: 15
3344
})
3445
]);
3546

3647
// Search all users under 30
48+
// https://oss.redis.com/redisearch/Commands/#ftsearch
3749
// TODO: why "$.age:[-inf, 30]" does not work?
3850
console.log(
39-
await client.ft.search('users', '*')
51+
await client.ft.search('idx:users', '*')
4052
);
4153
// {
4254
// total: 1,
4355
// documents: [...]
4456
// }
4557

46-
// Some aggregrations...
58+
// Some aggregrations, what's the average age and total number of coins...
59+
// https://oss.redis.com/redisearch/Commands/#ftaggregate
4760
console.log(
48-
await client.ft.aggregate('users', '*', {
61+
await client.ft.aggregate('idx:users', '*', {
4962
STEPS: [{
5063
type: AggregateSteps.GROUPBY,
5164
REDUCE: [{
@@ -71,4 +84,4 @@ async function searchPlusJson() {
7184
await client.quit();
7285
}
7386

74-
searchPlusJson();
87+
searchJSON();

0 commit comments

Comments
 (0)