-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathsearch.ts
247 lines (215 loc) · 7.05 KB
/
search.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/* eslint-disable no-param-reassign */
import { Resolver, isObject, ObjectTypeComposer } from 'graphql-compose';
import type { ResolverResolveParams, ProjectionType } from 'graphql-compose';
import ElasticApiParser from '../ElasticApiParser';
import { getSearchBodyITC, prepareBodyInResolve } from '../elasticDSL/SearchBody';
import { getSearchOutputTC } from '../types/SearchOutput';
import type { CommonOpts } from '../utils';
export default function createSearchResolver<TSource, TContext>(
opts: CommonOpts<TContext>
): Resolver<TSource, TContext> {
const { fieldMap, sourceTC, schemaComposer } = opts;
if (!fieldMap || !fieldMap._all) {
throw new Error(
'opts.fieldMap for Resolver search() should be fieldMap of FieldsMapByElasticType type.'
);
}
if (!(sourceTC instanceof ObjectTypeComposer)) {
throw new Error(
'opts.sourceTC for Resolver search() should be instance of ObjectTypeComposer.'
);
}
const parser = new ElasticApiParser({
elasticClient: opts.elasticClient,
prefix: opts.prefix,
});
const searchITC = getSearchBodyITC(opts).removeField([
'size',
'from',
'_source',
'explain',
'version',
]);
const searchFC = parser.generateFieldConfig('search', {
index: opts.elasticIndex,
type: opts.elasticType,
});
const argsConfigMap = {
...searchFC.args,
body: {
type: searchITC,
},
} as Record<string, any>;
delete argsConfigMap.index; // index can not be changed, it hardcoded in searchFC
delete argsConfigMap.type; // type can not be changed, it hardcoded in searchFC
delete argsConfigMap.explain; // added automatically if requested _shard, _node, _explanation
delete argsConfigMap.version; // added automatically if requested _version
delete argsConfigMap._source; // added automatically due projection
delete argsConfigMap._sourceExclude; // added automatically due projection
delete argsConfigMap._sourceInclude; // added automatically due projection
delete argsConfigMap.trackScores; // added automatically due projection (is _score requested with sort)
delete argsConfigMap.size;
delete argsConfigMap.from;
argsConfigMap.limit = 'Int';
argsConfigMap.skip = 'Int';
argsConfigMap.query = searchITC.getField('query');
argsConfigMap.aggs = searchITC.getField('aggs');
argsConfigMap.sort = searchITC.getField('sort');
argsConfigMap.collapse = searchITC.getField('collapse');
argsConfigMap.highlight = searchITC.getField('highlight');
argsConfigMap.post_filter = searchITC.getField('post_filter');
const topLevelArgs = [
'q',
'query',
'collapse',
'sort',
'limit',
'skip',
'aggs',
'highlight',
'opts',
'post_filter',
];
argsConfigMap.opts = schemaComposer
.createInputTC({
name: `${sourceTC.getTypeName()}Opts`,
fields: { ...argsConfigMap },
})
.removeField(topLevelArgs);
Object.keys(argsConfigMap).forEach((argKey) => {
if (topLevelArgs.indexOf(argKey) === -1) {
// $FlowFixMe
delete argsConfigMap[argKey];
}
});
const type = getSearchOutputTC(opts);
let hitsType;
try {
hitsType = type.get('hits.hits');
} catch (e) {
hitsType = 'JSON';
}
type
.addFields({
count: 'Int',
max_score: 'Float',
hits: hitsType ? ([hitsType] as any) : 'JSON',
})
.reorderFields(['hits', 'count', 'aggregations', 'max_score', 'took', 'timed_out', '_shards']);
return schemaComposer
.createResolver({
type,
name: 'search',
kind: 'query',
args: argsConfigMap,
resolve: async (rp: ResolverResolveParams<any, any>) => {
let args = rp.args || ({} as Record<string, any>);
const projection = rp.projection || {};
if (!args.body) args.body = {};
if ({}.hasOwnProperty.call(args, 'limit')) {
args.size = args.limit;
delete args.limit;
}
if ({}.hasOwnProperty.call(args, 'skip')) {
args.from = args.skip;
delete args.skip;
}
const { hits = {} } = projection;
if (hits && typeof hits === 'object') {
// Turn on explain if in projection requested this fields:
if (hits._shard || hits._node || hits._explanation) {
args.body.explain = true;
}
if (hits._version) {
args.body.version = true;
}
if (!hits._source) {
args.body._source = false;
} else {
args.body._source = toDottedList(hits._source);
}
if (hits._score) {
args.body.track_scores = true;
}
}
if (args.query) {
args.body.query = args.query;
delete args.query;
}
if (args.post_filter) {
args.body.post_filter = args.post_filter;
delete args.post_filter;
}
if (args.collapse) {
args.body.collapse = args.collapse;
delete args.collapse;
}
if (args.aggs) {
args.body.aggs = args.aggs;
delete args.aggs;
}
if (args.highlight) {
args.body.highlight = args.highlight;
delete args.highlight;
}
if (args.sort) {
args.body.sort = args.sort;
delete args.sort;
}
if (args.opts) {
args = {
...args.opts,
...args,
body: { ...args.opts.body, ...args.body },
};
delete args.opts;
}
if (args.body) {
args.body = prepareBodyInResolve(args.body, fieldMap);
}
const res: any = await searchFC.resolve(rp.source, args, rp.context, rp.info);
if (typeof res.aggregations === 'undefined') {
res.aggregations = res.body.aggregations;
}
if (typeof res.took === 'undefined') {
res.took = res.body.took;
}
if (typeof res.timed_out === 'undefined') {
res.timed_out = res.body.timed_out;
}
if (typeof res.hits === 'undefined') {
res.count =
typeof res.body.hits.total?.value === 'number'
? res.body.hits.total.value
: res.body.hits.total;
res.max_score = res.body.hits.max_score;
res.hits = res.body.hits.hits;
} else {
res.count =
typeof res.hits.total?.value === 'number' ? res.hits.total.value : res.hits.total;
res.max_score = res.hits.max_score;
res.hits = res.hits.hits;
}
return res;
},
})
.reorderArgs(['q', 'query', 'collapse', 'sort', 'limit', 'skip', 'aggs']);
}
export function toDottedList(projection: ProjectionType, prev?: string[]): string[] | boolean {
let result = [] as string[];
Object.keys(projection).forEach((k) => {
if (isObject(projection[k])) {
const tmp = toDottedList(projection[k], prev ? [...prev, k] : [k]);
if (Array.isArray(tmp)) {
result = result.concat(tmp);
return;
}
}
if (prev) {
result.push([...prev, k].join('.'));
} else {
result.push(k);
}
});
return result.length > 0 ? result : true;
}