-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.ts
215 lines (189 loc) 路 5.35 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Import here Polyfills if needed. Recommended core-js (npm i -D core-js)
// import "core-js/fn/array.find"
// ...
import { Redis } from 'ioredis';
import * as R from 'ramda';
import { Field } from './field';
import { Query } from './query';
import { Result } from './result';
import { BatchIndexer } from './batch-indexer';
export interface SchemaDictionary {
[key: string]: any;
}
export interface NumericDictionary {
[key: string]: number;
}
export type SearchDictionary = NumericDictionary;
export type SnippetsDictionary = NumericDictionary;
export type DocumentScore =
| 0.0
| 0.1
| 0.2
| 0.3
| 0.4
| 0.5
| 0.6
| 0.7
| 0.8
| 0.9
| 1.0;
enum Commands {
Create = 'FT.CREATE',
Search = 'FT.SEARCH',
Add = 'FT.ADD',
Drop = 'FT.DROP',
Explain = 'FT.EXPLAIN',
Del = 'FT.DEL'
}
enum ClientArgs {
Schema = 'SCHEMA',
Nooffsets = 'NOOFFSETS',
Nofields = 'NOFIELDS',
Stopwords = 'STOPWORDS',
NoSave = 'NOSAVE',
Payload = 'PAYLOAD',
Replace = 'REPLACE',
Partial = 'PARTIAL',
Fields = 'FIELDS'
}
/**
* A client for the RediSearch module.
* It abstracts the API of the module and lets you just use the engine
*/
export class Client<C extends Redis = Redis> {
readonly redis: C;
private indexName: string;
constructor(indexName: string, conn: C) {
this.indexName = indexName;
this.redis = conn;
}
/**
* Create the search index. Creating an existing index juts updates its properties
* @param fields a list of TextField or NumericField objects
*/
public createIndex(fields: Field[]): Promise<'OK'> {
return this.redis.send_command(
Commands.Create,
this.indexName,
ClientArgs.Schema,
...fields.map(f => f.redisArgs)
);
}
/**
* Drop the index if it exists
*/
public dropIndex(): Promise<'OK'> {
return this.redis.send_command(Commands.Drop, this.indexName);
}
/**
* Add a single document to the index.
* @param docId the id of the saved document.
* @param fields object of the document fields to be saved and/or indexed.
* NOTE: Geo points should be encoded as strings of "lon,lat"
* @param score the document ranking, between 0.0 and 1.0
* @param payload optional inner-index payload we can save for fast access in scoring functions
* @param noSave if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids.
* @param replace if true, and the document already is in the index, we perform an update and reindex the document
* @param partial if true, the fields specified will be added to the existing document.
* This has the added benefit that any fields specified with `no_index`
* will not be reindexed again. Implies `replace`
*/
public addDocument<T extends SchemaDictionary>(
docId: string,
fields: T,
score: DocumentScore = 1.0,
payload?: Object,
noSave = false,
replace = false,
partial = false
): Promise<'OK'> {
return this._addDocument(
null,
docId,
fields,
score,
payload,
noSave,
replace,
partial
);
}
/**
* Search the index for a given query, and return a result of documents
* @param queryOrString the search query.
* Either a text for simple queries
* with default parameters,
* or a Query object for complex queries.
* See RediSearch's documentation on query format
* @param snippetSizes A dictionary of {field: snippet_size}
* used to trim and format the result. e.g. {'body': 500}
*/
public search<T = SchemaDictionary, S = NumericDictionary>(
queryOrString: Query | string,
snippetSizes?: S
): Promise<Result<T, S>> {
const query = this.toQuery(queryOrString);
// Set time
const hrstart = process.hrtime();
// Execute the search;
return this.redis
.send_command(Commands.Search, this.indexName, ...query.args)
.then((res: any[]) => {
const hrend = process.hrtime(hrstart);
const elapsedMillis = hrend[1] / 1000000;
return new Result(
res,
!query._noContent,
query.queryString,
query._withPayloads,
elapsedMillis,
snippetSizes
);
});
}
/**
* Create a new batch indexer from the client with a given chunk size
*/
public batchIndexer(chunkSize = 1000): BatchIndexer {
return new BatchIndexer(this, chunkSize);
}
// private
_addDocument<T extends SchemaDictionary>(
conn: Redis | null,
docId: string,
fields: T,
score: DocumentScore = 1.0,
payload?: Object,
noSave = false,
replace = false,
partial = false
): Promise<'OK'> {
if (partial) {
replace = true;
}
const args = [this.indexName, docId, score];
if (noSave) {
args.push(ClientArgs.NoSave);
}
// if (R.not(R.isNil(payload))) {
// args.push(ClientArgs.Payload, payload);
// }
if (replace) {
args.push(ClientArgs.Replace);
if (partial) {
args.push(ClientArgs.Partial);
}
}
args.push(ClientArgs.Fields, ...R.unnest(R.toPairs(fields)));
return this.redis.send_command(Commands.Add, ...args);
}
private toQuery(query: string | Query): Query {
if (R.is(String, query)) {
query = new Query(query as string);
}
if (R.not(R.is(Query, query))) {
throw new Error(`Bad query type: '${typeof query}'`);
}
return query;
}
}