1
+ // This example demonstrates how to use RediSearch to index and query data
2
+ // stored in Redis hashes.
3
+
4
+ import { createClient , SchemaFieldTypes } from 'redis' ;
5
+
6
+ async function searchHashes ( ) {
7
+ const client = createClient ( ) ;
8
+
9
+ await client . connect ( ) ;
10
+
11
+ // Create an index...
12
+ try {
13
+ // Documentation: https://oss.redis.com/redisearch/Commands/#ftcreate
14
+ await client . ft . create ( 'idx:animals' , {
15
+ name : {
16
+ type : SchemaFieldTypes . TEXT ,
17
+ sortable : true
18
+ } ,
19
+ species : SchemaFieldTypes . TAG ,
20
+ age : SchemaFieldTypes . NUMERIC
21
+ } , {
22
+ ON : 'HASH' ,
23
+ PREFIX : 'noderedis:animals'
24
+ } ) ;
25
+ } catch ( e ) {
26
+ if ( e . message === 'Index already exists' ) {
27
+ console . log ( 'Index exists already, skipped creation.' ) ;
28
+ } else {
29
+ // Something went wrong, perhaps RediSearch isn't installed...
30
+ console . error ( e ) ;
31
+ process . exit ( 1 ) ;
32
+ }
33
+ }
34
+
35
+ // Add some sample data...
36
+ await Promise . all ( [
37
+ client . hSet ( 'noderedis:animals:1' , { name : 'Fluffy' , species : 'cat' , age : 3 } ) ,
38
+ client . hSet ( 'noderedis:animals:2' , { name : 'Ginger' , species : 'cat' , age : 4 } ) ,
39
+ client . hSet ( 'noderedis:animals:3' , { name : 'Rover' , species : 'dog' , age : 9 } ) ,
40
+ client . hSet ( 'noderedis:animals:4' , { name : 'Fido' , species : 'dog' , age : 7 } )
41
+ ] ) ;
42
+
43
+ // Perform a search query, find all the dogs...
44
+ // Documentation: https://oss.redis.com/redisearch/Commands/#ftsearch
45
+ // Query synatax: https://oss.redis.com/redisearch/Query_Syntax/
46
+ const results = await client . ft . search ( 'idx:animals' , '@species:{dog}' ) ;
47
+
48
+ // results:
49
+ // {
50
+ // total: 2,
51
+ // documents: [
52
+ // {
53
+ // id: 'noderedis:animals:4',
54
+ // value: {
55
+ // name: 'Fido',
56
+ // species: 'dog',
57
+ // age: '7'
58
+ // }
59
+ // },
60
+ // {
61
+ // id: 'noderedis:animals:3',
62
+ // value: {
63
+ // name: 'Rover',
64
+ // species: 'dog',
65
+ // age: '9'
66
+ // }
67
+ // }
68
+ // ]
69
+ // }
70
+
71
+ console . log ( `Results found: ${ results . total } .` ) ;
72
+
73
+ for ( const doc of results . documents ) {
74
+ // noderedis:animals:4: Fido
75
+ // noderedis:animals:3: Rover
76
+ console . log ( `${ doc . id } : ${ doc . value . name } ` ) ;
77
+ }
78
+
79
+ await client . quit ( ) ;
80
+ }
81
+
82
+ searchHashes ( ) ;
0 commit comments