2
2
3
3
import { createClient , SchemaFieldTypes , AggregateGroupByReducers , AggregateSteps } from 'redis' ;
4
4
5
- async function searchPlusJson ( ) {
5
+ async function searchJSON ( ) {
6
6
const client = createClient ( ) ;
7
7
8
8
await client . connect ( ) ;
9
9
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
+ }
21
32
22
- // Add some users
33
+ // Add some users.
23
34
await Promise . all ( [
24
- client . json . set ( 'users:1' , '$' , {
35
+ client . json . set ( 'noderedis: users:1' , '$' , {
25
36
name : 'Alice' ,
26
37
age : 32 ,
27
38
coins : 100
28
39
} ) ,
29
- client . json . set ( 'users:2' , '$' , {
40
+ client . json . set ( 'noderedis: users:2' , '$' , {
30
41
name : 'Bob' ,
31
42
age : 23 ,
32
43
coins : 15
33
44
} )
34
45
] ) ;
35
46
36
47
// Search all users under 30
48
+ // https://oss.redis.com/redisearch/Commands/#ftsearch
37
49
// TODO: why "$.age:[-inf, 30]" does not work?
38
50
console . log (
39
- await client . ft . search ( 'users' , '*' )
51
+ await client . ft . search ( 'idx: users' , '*' )
40
52
) ;
41
53
// {
42
54
// total: 1,
43
55
// documents: [...]
44
56
// }
45
57
46
- // Some aggregrations...
58
+ // Some aggregrations, what's the average age and total number of coins...
59
+ // https://oss.redis.com/redisearch/Commands/#ftaggregate
47
60
console . log (
48
- await client . ft . aggregate ( 'users' , '*' , {
61
+ await client . ft . aggregate ( 'idx: users' , '*' , {
49
62
STEPS : [ {
50
63
type : AggregateSteps . GROUPBY ,
51
64
REDUCE : [ {
@@ -71,4 +84,4 @@ async function searchPlusJson() {
71
84
await client . quit ( ) ;
72
85
}
73
86
74
- searchPlusJson ( ) ;
87
+ searchJSON ( ) ;
0 commit comments