typesense-instantsearch-adapter 2.4.1-4 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -1
- package/src/.DS_Store +0 -0
- package/src/Configuration.js +77 -0
- package/src/FacetSearchResponseAdapter.js +38 -0
- package/src/SearchRequestAdapter.js +323 -0
- package/src/SearchResponseAdapter.js +164 -0
- package/src/TypesenseInstantsearchAdapter.js +87 -0
- package/src/support/utils.js +15 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typesense-instantsearch-adapter",
|
|
3
|
-
"version": "2.4.1
|
|
3
|
+
"version": "2.4.1",
|
|
4
4
|
"description": "Adapter to use InstantSearch UI widgets with Typesense Search",
|
|
5
5
|
"homepage": "https://github.com/typesense/typesense-instantsearch-adapter",
|
|
6
6
|
"main": "lib/TypesenseInstantsearchAdapter.js",
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
"files": [
|
|
9
9
|
"dist/",
|
|
10
10
|
"lib/",
|
|
11
|
+
"src/",
|
|
11
12
|
"scripts/",
|
|
12
13
|
"index.d.ts"
|
|
13
14
|
],
|
package/src/.DS_Store
ADDED
|
Binary file
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
export class Configuration {
|
|
4
|
+
constructor(options = {}) {
|
|
5
|
+
this.server = options.server || {
|
|
6
|
+
nodes: [
|
|
7
|
+
{
|
|
8
|
+
host: "localhost",
|
|
9
|
+
port: "8108",
|
|
10
|
+
path: "",
|
|
11
|
+
protocol: "http",
|
|
12
|
+
},
|
|
13
|
+
],
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
this.server.cacheSearchResultsForSeconds = this.server.cacheSearchResultsForSeconds ?? 2 * 60;
|
|
17
|
+
|
|
18
|
+
this.additionalSearchParameters = options.additionalSearchParameters ?? {};
|
|
19
|
+
|
|
20
|
+
this.additionalSearchParameters.query_by =
|
|
21
|
+
this.additionalSearchParameters.queryBy ?? this.additionalSearchParameters.query_by ?? "";
|
|
22
|
+
|
|
23
|
+
this.additionalSearchParameters.sort_by =
|
|
24
|
+
this.additionalSearchParameters.sortBy ?? this.additionalSearchParameters.sort_by ?? "";
|
|
25
|
+
|
|
26
|
+
this.additionalSearchParameters.highlight_full_fields =
|
|
27
|
+
this.additionalSearchParameters.highlightFullFields ??
|
|
28
|
+
this.additionalSearchParameters.highlight_full_fields ??
|
|
29
|
+
this.additionalSearchParameters.query_by;
|
|
30
|
+
|
|
31
|
+
this.geoLocationField = options.geoLocationField ?? "_geoloc";
|
|
32
|
+
|
|
33
|
+
this.collectionSpecificSearchParameters = options.collectionSpecificSearchParameters ?? {};
|
|
34
|
+
|
|
35
|
+
Object.keys(this.collectionSpecificSearchParameters).forEach((collection) => {
|
|
36
|
+
const params = this.collectionSpecificSearchParameters[collection];
|
|
37
|
+
params.query_by = params.queryBy ?? params.query_by;
|
|
38
|
+
params.sort_by = params.sortBy ?? params.sort_by;
|
|
39
|
+
params.highlight_full_fields =
|
|
40
|
+
params.highlightFullFields ??
|
|
41
|
+
params.highlight_full_fields ??
|
|
42
|
+
this.additionalSearchParameters.highlight_full_fields ??
|
|
43
|
+
params.query_by;
|
|
44
|
+
|
|
45
|
+
// Remove undefined values
|
|
46
|
+
Object.keys(params).forEach((key) => (params[key] === undefined ? delete params[key] : {}));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
validate() {
|
|
51
|
+
// Warn if camelCased parameters are used, suggest using snake_cased parameters instead
|
|
52
|
+
if (
|
|
53
|
+
this.additionalSearchParameters.queryBy ||
|
|
54
|
+
Object.values(this.collectionSpecificSearchParameters).some((c) => c.queryBy)
|
|
55
|
+
) {
|
|
56
|
+
console.warn(
|
|
57
|
+
"[typesense-instantsearch-adapter] Please use snake_cased versions of parameters in additionalSearchParameters instead of camelCased parameters. For example: Use query_by instead of queryBy. camelCased parameters will be deprecated in a future version." +
|
|
58
|
+
" We're making this change so that parameter names are identical to the ones sent to Typesense (which are all snake_cased), and to also keep the types for these parameters in sync with the types defined in typesense-js."
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/*
|
|
63
|
+
* Either additionalSearchParameters.query_by needs to be set, or
|
|
64
|
+
* All collectionSpecificSearchParameters need to have query_by
|
|
65
|
+
*
|
|
66
|
+
* */
|
|
67
|
+
if (
|
|
68
|
+
this.additionalSearchParameters.query_by.length === 0 &&
|
|
69
|
+
(Object.keys(this.collectionSpecificSearchParameters).length === 0 ||
|
|
70
|
+
Object.values(this.collectionSpecificSearchParameters).some((c) => (c.query_by || "").length === 0))
|
|
71
|
+
) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
"[typesense-instantsearch-adapter] Missing parameter: Either additionalSearchParameters.query_by needs to be set, or all collectionSpecificSearchParameters need to have .query_by set"
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { utils } from "./support/utils";
|
|
4
|
+
|
|
5
|
+
export class FacetSearchResponseAdapter {
|
|
6
|
+
constructor(typesenseResponse, instantsearchRequest) {
|
|
7
|
+
this.typesenseResponse = typesenseResponse;
|
|
8
|
+
this.instantsearchRequest = instantsearchRequest;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
_adaptFacetHits(typesenseFacetCounts) {
|
|
12
|
+
let adaptedResult = {};
|
|
13
|
+
const facet = typesenseFacetCounts.find((facet) => facet.field_name === this.instantsearchRequest.params.facetName);
|
|
14
|
+
|
|
15
|
+
adaptedResult = facet.counts.map((facetCount) => ({
|
|
16
|
+
value: facetCount.value,
|
|
17
|
+
highlighted: this._adaptHighlightTag(
|
|
18
|
+
facetCount.highlighted,
|
|
19
|
+
this.instantsearchRequest.params.highlightPreTag,
|
|
20
|
+
this.instantsearchRequest.params.highlightPostTag
|
|
21
|
+
),
|
|
22
|
+
count: facetCount.count,
|
|
23
|
+
}));
|
|
24
|
+
|
|
25
|
+
return adaptedResult;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
adapt() {
|
|
29
|
+
const adaptedResult = {
|
|
30
|
+
facetHits: this._adaptFacetHits(this.typesenseResponse.facet_counts),
|
|
31
|
+
exhaustiveFacetsCount: true,
|
|
32
|
+
processingTimeMS: this.typesenseResponse.search_time_ms,
|
|
33
|
+
};
|
|
34
|
+
return adaptedResult;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
Object.assign(FacetSearchResponseAdapter.prototype, utils);
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
export class SearchRequestAdapter {
|
|
4
|
+
static get INDEX_NAME_MATCHING_REGEX() {
|
|
5
|
+
return new RegExp("^(.+?)(?=(/sort/(.*))|$)");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
static get FILTER_STRING_MATCHING_REGEX() {
|
|
9
|
+
return new RegExp("(.*)((?!:).):(?!:)(.*)");
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
constructor(instantsearchRequests, typesenseClient, configuration) {
|
|
13
|
+
this.instantsearchRequests = instantsearchRequests;
|
|
14
|
+
this.typesenseClient = typesenseClient;
|
|
15
|
+
this.configuration = configuration;
|
|
16
|
+
this.additionalSearchParameters = configuration.additionalSearchParameters;
|
|
17
|
+
this.collectionSpecificSearchParameters = configuration.collectionSpecificSearchParameters;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
_adaptFacetFilters(facetFilters) {
|
|
21
|
+
let adaptedResult = "";
|
|
22
|
+
|
|
23
|
+
if (!facetFilters) {
|
|
24
|
+
return adaptedResult;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Need to transform:
|
|
29
|
+
* facetFilters = [["field1:value1", "field1:value2"], "field2:value3", "field2:value4"]
|
|
30
|
+
*
|
|
31
|
+
* Into this:
|
|
32
|
+
* field1:=[value1,value2] && field2:=value3 && field2:=value4
|
|
33
|
+
*
|
|
34
|
+
* Steps:
|
|
35
|
+
* - For each item in facetFilters
|
|
36
|
+
* - If item is array
|
|
37
|
+
* - OR values together.
|
|
38
|
+
* - Warn if field names are not the same
|
|
39
|
+
* - If item is string, convert to facet:=value format
|
|
40
|
+
* - Join strings by &&
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
const transformedTypesenseFilters = facetFilters.map((item) => {
|
|
44
|
+
if (Array.isArray(item)) {
|
|
45
|
+
// Need to transform:
|
|
46
|
+
// facetFilters = ["field1:value1", "field1:value2", "facetN:valueN"]
|
|
47
|
+
//
|
|
48
|
+
// Into this:
|
|
49
|
+
// intermediateFacetFilters = {
|
|
50
|
+
// "field1": ["value1", "value2"],
|
|
51
|
+
// "fieldN": ["valueN"]
|
|
52
|
+
// }
|
|
53
|
+
|
|
54
|
+
const intermediateFacetFilters = {};
|
|
55
|
+
item.forEach((facetFilter) => {
|
|
56
|
+
const facetFilterMatches = facetFilter.match(this.constructor.FILTER_STRING_MATCHING_REGEX);
|
|
57
|
+
const fieldName = `${facetFilterMatches[1]}${facetFilterMatches[2]}`;
|
|
58
|
+
const fieldValue = `${facetFilterMatches[3]}`;
|
|
59
|
+
intermediateFacetFilters[fieldName] = intermediateFacetFilters[fieldName] || [];
|
|
60
|
+
intermediateFacetFilters[fieldName].push(fieldValue);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
if (Object.keys(intermediateFacetFilters).length > 1) {
|
|
64
|
+
console.error(
|
|
65
|
+
`[Typesense-Instantsearch-Adapter] Typesense does not support cross-field ORs at the moment. The adapter could not OR values between these fields: ${Object.keys(
|
|
66
|
+
intermediateFacetFilters
|
|
67
|
+
).join(",")}`
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Pick first value from intermediateFacetFilters
|
|
72
|
+
const fieldName = Object.keys(intermediateFacetFilters)[0];
|
|
73
|
+
const fieldValues = intermediateFacetFilters[fieldName];
|
|
74
|
+
|
|
75
|
+
// Need to transform:
|
|
76
|
+
// intermediateFacetFilters = {
|
|
77
|
+
// "field1": ["value1", "value2"],
|
|
78
|
+
// }
|
|
79
|
+
//
|
|
80
|
+
// Into this:
|
|
81
|
+
// field1:=[value1,value2]
|
|
82
|
+
|
|
83
|
+
// Partition values into included and excluded values
|
|
84
|
+
const [excludedFieldValues, includedFieldValues] = fieldValues.reduce(
|
|
85
|
+
(result, fieldValue) => {
|
|
86
|
+
if (fieldValue.startsWith("-") && !this._isNumber(fieldValue)) {
|
|
87
|
+
result[0].push(fieldValue.substring(1));
|
|
88
|
+
} else {
|
|
89
|
+
result[1].push(fieldValue);
|
|
90
|
+
}
|
|
91
|
+
return result;
|
|
92
|
+
},
|
|
93
|
+
[[], []]
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
const typesenseFilterStringComponents = [];
|
|
97
|
+
if (includedFieldValues.length > 0) {
|
|
98
|
+
typesenseFilterStringComponents.push(
|
|
99
|
+
`${fieldName}:=[${includedFieldValues.map((v) => this._escapeFacetValue(v)).join(",")}]`
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
if (excludedFieldValues.length > 0) {
|
|
103
|
+
typesenseFilterStringComponents.push(
|
|
104
|
+
`${fieldName}:!=[${excludedFieldValues.map((v) => this._escapeFacetValue(v)).join(",")}]`
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const typesenseFilterString = typesenseFilterStringComponents.filter((f) => f).join(" && ");
|
|
109
|
+
|
|
110
|
+
return typesenseFilterString;
|
|
111
|
+
} else {
|
|
112
|
+
// Need to transform:
|
|
113
|
+
// fieldName:fieldValue
|
|
114
|
+
// Into
|
|
115
|
+
// fieldName:=fieldValue
|
|
116
|
+
|
|
117
|
+
const facetFilterMatches = item.match(this.constructor.FILTER_STRING_MATCHING_REGEX);
|
|
118
|
+
const fieldName = `${facetFilterMatches[1]}${facetFilterMatches[2]}`;
|
|
119
|
+
const fieldValue = `${facetFilterMatches[3]}`;
|
|
120
|
+
let typesenseFilterString;
|
|
121
|
+
if (fieldValue.startsWith("-") && !this._isNumber(fieldValue)) {
|
|
122
|
+
typesenseFilterString = `${fieldName}:!=[${this._escapeFacetValue(fieldValue.substring(1))}]`;
|
|
123
|
+
} else {
|
|
124
|
+
typesenseFilterString = `${fieldName}:=[${this._escapeFacetValue(fieldValue)}]`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return typesenseFilterString;
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
adaptedResult = transformedTypesenseFilters.join(" && ");
|
|
132
|
+
// console.log(`${JSON.stringify(facetFilters)} => ${adaptedResult}`);
|
|
133
|
+
|
|
134
|
+
return adaptedResult;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
_escapeFacetValue(value) {
|
|
138
|
+
// Don't escape booleans, integers or floats
|
|
139
|
+
if (typeof value === "boolean" || value === "true" || value === "false" || this._isNumber(value)) {
|
|
140
|
+
return value;
|
|
141
|
+
}
|
|
142
|
+
return `\`${value}\``;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
_isNumber(value) {
|
|
146
|
+
return (
|
|
147
|
+
Number.isInteger(value % 1) || // Mod 1 will automatically try converting string values to integer/float
|
|
148
|
+
!!(value % 1)
|
|
149
|
+
); // Is Float
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
_adaptNumericFilters(numericFilters) {
|
|
153
|
+
// Need to transform this:
|
|
154
|
+
// ["field1<=634", "field1>=289", "field2<=5", "field3>=3"]
|
|
155
|
+
// to:
|
|
156
|
+
// "field1:=[634..289] && field2:<=5 && field3:>=3"
|
|
157
|
+
let adaptedResult = "";
|
|
158
|
+
|
|
159
|
+
if (!numericFilters) {
|
|
160
|
+
return adaptedResult;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Transform to intermediate structure:
|
|
164
|
+
// {
|
|
165
|
+
// field1: {
|
|
166
|
+
// "<=": 634,
|
|
167
|
+
// ">=": 289
|
|
168
|
+
// },
|
|
169
|
+
// field2: {
|
|
170
|
+
// "<=": 5
|
|
171
|
+
// },
|
|
172
|
+
// field3: {
|
|
173
|
+
// ">=": 3
|
|
174
|
+
// }
|
|
175
|
+
// };
|
|
176
|
+
const filtersHash = {};
|
|
177
|
+
numericFilters.forEach((filter) => {
|
|
178
|
+
const [, field, operator, value] = filter.match(new RegExp("(.*?)(<=|>=|>|<|:|=)(.*)"));
|
|
179
|
+
filtersHash[field] = filtersHash[field] || {};
|
|
180
|
+
filtersHash[field][operator] = value;
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
// Transform that to:
|
|
184
|
+
// "field1:=[634..289] && field2:<=5 && field3:>=3"
|
|
185
|
+
const adaptedFilters = [];
|
|
186
|
+
Object.keys(filtersHash).forEach((field) => {
|
|
187
|
+
if (filtersHash[field]["<="] != null && filtersHash[field][">="] != null) {
|
|
188
|
+
adaptedFilters.push(`${field}:=[${filtersHash[field][">="]}..${filtersHash[field]["<="]}]`);
|
|
189
|
+
} else if (filtersHash[field]["<="] != null) {
|
|
190
|
+
adaptedFilters.push(`${field}:<=${filtersHash[field]["<="]}`);
|
|
191
|
+
} else if (filtersHash[field][">="] != null) {
|
|
192
|
+
adaptedFilters.push(`${field}:>=${filtersHash[field][">="]}`);
|
|
193
|
+
} else if (filtersHash[field]["="] != null) {
|
|
194
|
+
adaptedFilters.push(`${field}:=${filtersHash[field]["="]}`);
|
|
195
|
+
} else {
|
|
196
|
+
console.warn(
|
|
197
|
+
`[Typesense-Instantsearch-Adapter] Unsupported operator found ${JSON.stringify(filtersHash[field])}`
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
adaptedResult = adaptedFilters.join(" && ");
|
|
203
|
+
return adaptedResult;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
_adaptGeoFilter({ insideBoundingBox, aroundRadius, aroundLatLng, insidePolygon }) {
|
|
207
|
+
// Give this parameter first priority if it exists, since
|
|
208
|
+
if (insideBoundingBox) {
|
|
209
|
+
let x1, y1, x2, y2;
|
|
210
|
+
if (Array.isArray(insideBoundingBox)) {
|
|
211
|
+
[x1, y1, x2, y2] = insideBoundingBox.flat();
|
|
212
|
+
} else {
|
|
213
|
+
[x1, y1, x2, y2] = insideBoundingBox.split(",");
|
|
214
|
+
}
|
|
215
|
+
return `${this.configuration.geoLocationField}:(${x1}, ${y1}, ${x1}, ${y2}, ${x2}, ${y2}, ${x2}, ${y1})`;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (aroundLatLng || aroundRadius) {
|
|
219
|
+
if (!aroundRadius || aroundRadius === "all") {
|
|
220
|
+
throw new Error(
|
|
221
|
+
"[Typesense-Instantsearch-Adapter] In Typesense, geo-filtering around a lat/lng also requires a numerical radius. " +
|
|
222
|
+
"So the `aroundRadius` parameter is required when `aroundLatLng` is used. " +
|
|
223
|
+
"If you intend to just geo-sort around a lat/long, you want to use the sortBy InstantSearch widget (or a virtual sortBy custom widget)."
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
const adaptedAroundRadius = `${parseFloat(aroundRadius) / 1000} km`; // aroundRadius is in meters
|
|
227
|
+
return `${this.configuration.geoLocationField}:(${aroundLatLng}, ${adaptedAroundRadius})`;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (insidePolygon) {
|
|
231
|
+
let coordinates = insidePolygon;
|
|
232
|
+
if (Array.isArray(insidePolygon)) {
|
|
233
|
+
coordinates = insidePolygon.flat().join(",");
|
|
234
|
+
}
|
|
235
|
+
return `${this.configuration.geoLocationField}:(${coordinates})`;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
_adaptFilters(instantsearchParams) {
|
|
240
|
+
const adaptedFilters = [];
|
|
241
|
+
|
|
242
|
+
// `filters` can be used with the `Configure` widget
|
|
243
|
+
// However the format needs to be in the Typesense filter_by format, instead of Algolia filter format.
|
|
244
|
+
if (instantsearchParams.filters) {
|
|
245
|
+
adaptedFilters.push(instantsearchParams.filters);
|
|
246
|
+
}
|
|
247
|
+
adaptedFilters.push(this._adaptFacetFilters(instantsearchParams.facetFilters));
|
|
248
|
+
adaptedFilters.push(this._adaptNumericFilters(instantsearchParams.numericFilters));
|
|
249
|
+
adaptedFilters.push(this._adaptGeoFilter(instantsearchParams));
|
|
250
|
+
|
|
251
|
+
return adaptedFilters.filter((filter) => filter && filter !== "").join(" && ");
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
_adaptIndexName(indexName) {
|
|
255
|
+
return indexName.match(this.constructor.INDEX_NAME_MATCHING_REGEX)[1];
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
_adaptSortBy(indexName) {
|
|
259
|
+
return indexName.match(this.constructor.INDEX_NAME_MATCHING_REGEX)[3];
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
_buildSearchParameters(instantsearchRequest) {
|
|
263
|
+
const params = instantsearchRequest.params;
|
|
264
|
+
const indexName = instantsearchRequest.indexName;
|
|
265
|
+
const adaptedCollectionName = this._adaptIndexName(indexName);
|
|
266
|
+
|
|
267
|
+
// Convert all common parameters to snake case
|
|
268
|
+
const snakeCasedAdditionalSearchParameters = {};
|
|
269
|
+
for (const [key, value] of Object.entries(this.additionalSearchParameters)) {
|
|
270
|
+
snakeCasedAdditionalSearchParameters[this._camelToSnakeCase(key)] = value;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Override, collection specific parameters
|
|
274
|
+
if (this.collectionSpecificSearchParameters[adaptedCollectionName]) {
|
|
275
|
+
for (const [key, value] of Object.entries(this.collectionSpecificSearchParameters[adaptedCollectionName])) {
|
|
276
|
+
snakeCasedAdditionalSearchParameters[this._camelToSnakeCase(key)] = value;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const typesenseSearchParams = Object.assign({}, snakeCasedAdditionalSearchParameters);
|
|
281
|
+
|
|
282
|
+
const adaptedSortBy = this._adaptSortBy(indexName);
|
|
283
|
+
|
|
284
|
+
Object.assign(typesenseSearchParams, {
|
|
285
|
+
collection: adaptedCollectionName,
|
|
286
|
+
q: params.query === "" || params.query === undefined ? "*" : params.query,
|
|
287
|
+
facet_by: [params.facets].flat().join(","),
|
|
288
|
+
filter_by: this._adaptFilters(params) || snakeCasedAdditionalSearchParameters.filter_by,
|
|
289
|
+
sort_by: adaptedSortBy || snakeCasedAdditionalSearchParameters.sort_by,
|
|
290
|
+
max_facet_values: params.maxValuesPerFacet,
|
|
291
|
+
page: (params.page || 0) + 1,
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
if (params.hitsPerPage) {
|
|
295
|
+
typesenseSearchParams.per_page = params.hitsPerPage;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (params.facetQuery) {
|
|
299
|
+
typesenseSearchParams.facet_query = `${params.facetName}:${params.facetQuery}`;
|
|
300
|
+
typesenseSearchParams.per_page = 0;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// console.log(params);
|
|
304
|
+
// console.log(typesenseSearchParams);
|
|
305
|
+
|
|
306
|
+
return typesenseSearchParams;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
_camelToSnakeCase(str) {
|
|
310
|
+
return str
|
|
311
|
+
.split(/(?=[A-Z])/)
|
|
312
|
+
.join("_")
|
|
313
|
+
.toLowerCase();
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async request() {
|
|
317
|
+
const searches = this.instantsearchRequests.map((instantsearchRequest) =>
|
|
318
|
+
this._buildSearchParameters(instantsearchRequest)
|
|
319
|
+
);
|
|
320
|
+
|
|
321
|
+
return this.typesenseClient.multiSearch.perform({ searches: searches });
|
|
322
|
+
}
|
|
323
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { utils } from "./support/utils";
|
|
4
|
+
|
|
5
|
+
export class SearchResponseAdapter {
|
|
6
|
+
constructor(typesenseResponse, instantsearchRequest, configuration) {
|
|
7
|
+
this.typesenseResponse = typesenseResponse;
|
|
8
|
+
this.instantsearchRequest = instantsearchRequest;
|
|
9
|
+
this.configuration = configuration;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
_adaptGroupedHits(typesenseGroupedHits) {
|
|
13
|
+
let adaptedResult = [];
|
|
14
|
+
|
|
15
|
+
adaptedResult = typesenseGroupedHits.map((groupedHit) => this._adaptHits(groupedHit.hits));
|
|
16
|
+
|
|
17
|
+
// adaptedResult is now in the form of [[{}, {}], [{}, {}], ...]
|
|
18
|
+
// where each element in the outer most array corresponds to a group.
|
|
19
|
+
// We now flatten it to [{}, {}, {}]
|
|
20
|
+
adaptedResult = adaptedResult.flat();
|
|
21
|
+
|
|
22
|
+
return adaptedResult;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
_adaptHits(typesenseHits) {
|
|
26
|
+
let adaptedResult = [];
|
|
27
|
+
adaptedResult = typesenseHits.map((typesenseHit) => {
|
|
28
|
+
const adaptedHit = {
|
|
29
|
+
...typesenseHit.document,
|
|
30
|
+
};
|
|
31
|
+
adaptedHit.objectID = typesenseHit.document.id;
|
|
32
|
+
adaptedHit._snippetResult = this._adaptHighlightResult(typesenseHit, "snippet");
|
|
33
|
+
adaptedHit._highlightResult = this._adaptHighlightResult(typesenseHit, "value");
|
|
34
|
+
|
|
35
|
+
// Add metadata fields to result, if a field with that name doesn't already exist
|
|
36
|
+
["text_match", "geo_distance_meters", "curated"].forEach((metadataField) => {
|
|
37
|
+
if (Object.keys(typesenseHit).includes(metadataField) && !Object.keys(adaptedHit).includes(metadataField)) {
|
|
38
|
+
adaptedHit[metadataField] = typesenseHit[metadataField];
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const geoLocationValue = adaptedHit[this.configuration.geoLocationField];
|
|
43
|
+
if (geoLocationValue) {
|
|
44
|
+
adaptedHit._geoloc = {
|
|
45
|
+
lat: geoLocationValue[0],
|
|
46
|
+
lng: geoLocationValue[1],
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return adaptedHit;
|
|
51
|
+
});
|
|
52
|
+
return adaptedResult;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
_adaptHighlightResult(typesenseHit, snippetOrValue) {
|
|
56
|
+
// Algolia lists all searchable attributes in this key, even if there are no matches
|
|
57
|
+
// So do the same and then override highlights
|
|
58
|
+
|
|
59
|
+
const result = Object.assign(
|
|
60
|
+
{},
|
|
61
|
+
...Object.entries(typesenseHit.document).map(([attribute, value]) => ({
|
|
62
|
+
[attribute]: {
|
|
63
|
+
value: value,
|
|
64
|
+
matchLevel: "none",
|
|
65
|
+
matchedWords: [],
|
|
66
|
+
},
|
|
67
|
+
}))
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
typesenseHit.highlights.forEach((highlight) => {
|
|
71
|
+
result[highlight.field] = {
|
|
72
|
+
value: highlight[snippetOrValue] || highlight[`${snippetOrValue}s`],
|
|
73
|
+
matchLevel: "full",
|
|
74
|
+
matchedWords: highlight.matched_tokens,
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
if (highlight.indices) {
|
|
78
|
+
result[highlight.field]["matchedIndices"] = highlight.indices;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// Now convert any values that have an array value
|
|
83
|
+
// Also, replace highlight tag
|
|
84
|
+
Object.entries(result).forEach(([k, v]) => {
|
|
85
|
+
const attribute = k;
|
|
86
|
+
const { value, matchLevel, matchedWords, matchedIndices } = v;
|
|
87
|
+
if (Array.isArray(value)) {
|
|
88
|
+
// Algolia lists all values of the key in highlights, even those that don't have any highlights
|
|
89
|
+
// So add all values of the array field, including highlights
|
|
90
|
+
result[attribute] = [];
|
|
91
|
+
typesenseHit.document[attribute].forEach((unhighlightedValueFromArray, index) => {
|
|
92
|
+
if (matchedIndices && matchedIndices.includes(index)) {
|
|
93
|
+
result[attribute].push({
|
|
94
|
+
value: this._adaptHighlightTag(
|
|
95
|
+
`${value[matchedIndices.indexOf(index)]}`,
|
|
96
|
+
this.instantsearchRequest.params.highlightPreTag,
|
|
97
|
+
this.instantsearchRequest.params.highlightPostTag
|
|
98
|
+
),
|
|
99
|
+
matchLevel: matchLevel,
|
|
100
|
+
matchedWords: matchedWords[index],
|
|
101
|
+
});
|
|
102
|
+
} else {
|
|
103
|
+
result[attribute].push({
|
|
104
|
+
value: `${unhighlightedValueFromArray}`,
|
|
105
|
+
matchLevel: "none",
|
|
106
|
+
matchedWords: [],
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
} else {
|
|
111
|
+
// Convert all values to strings
|
|
112
|
+
result[attribute].value = this._adaptHighlightTag(
|
|
113
|
+
`${value}`,
|
|
114
|
+
this.instantsearchRequest.params.highlightPreTag,
|
|
115
|
+
this.instantsearchRequest.params.highlightPostTag
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
_adaptFacets(typesenseFacetCounts) {
|
|
123
|
+
const adaptedResult = {};
|
|
124
|
+
typesenseFacetCounts.forEach((facet) => {
|
|
125
|
+
Object.assign(adaptedResult, {
|
|
126
|
+
[facet.field_name]: Object.assign({}, ...facet.counts.map((count) => ({ [count.value]: count.count }))),
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
return adaptedResult;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
_adaptFacetStats(typesenseFacetCounts) {
|
|
133
|
+
const adaptedResult = {};
|
|
134
|
+
typesenseFacetCounts.forEach((facet) => {
|
|
135
|
+
if (Object.keys(facet.stats).length > 0) {
|
|
136
|
+
Object.assign(adaptedResult, {
|
|
137
|
+
[facet.field_name]: facet.stats,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
return adaptedResult;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
adapt() {
|
|
145
|
+
const adaptedResult = {
|
|
146
|
+
hits: this.typesenseResponse.grouped_hits
|
|
147
|
+
? this._adaptGroupedHits(this.typesenseResponse.grouped_hits)
|
|
148
|
+
: this._adaptHits(this.typesenseResponse.hits),
|
|
149
|
+
nbHits: this.typesenseResponse.found,
|
|
150
|
+
page: this.typesenseResponse.page - 1,
|
|
151
|
+
nbPages: this._adaptNumberOfPages(),
|
|
152
|
+
hitsPerPage: this.typesenseResponse.request_params.per_page,
|
|
153
|
+
facets: this._adaptFacets(this.typesenseResponse.facet_counts || []),
|
|
154
|
+
facets_stats: this._adaptFacetStats(this.typesenseResponse.facet_counts || {}),
|
|
155
|
+
query: this.typesenseResponse.request_params.q,
|
|
156
|
+
processingTimeMS: this.typesenseResponse.search_time_ms,
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
// console.log(adaptedResult);
|
|
160
|
+
return adaptedResult;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
Object.assign(SearchResponseAdapter.prototype, utils);
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { Configuration } from "./Configuration";
|
|
4
|
+
import { SearchClient as TypesenseSearchClient } from "typesense";
|
|
5
|
+
import { SearchRequestAdapter } from "./SearchRequestAdapter";
|
|
6
|
+
import { SearchResponseAdapter } from "./SearchResponseAdapter";
|
|
7
|
+
import { FacetSearchResponseAdapter } from "./FacetSearchResponseAdapter";
|
|
8
|
+
|
|
9
|
+
export default class TypesenseInstantsearchAdapter {
|
|
10
|
+
constructor(options) {
|
|
11
|
+
this.configuration = new Configuration(options);
|
|
12
|
+
this.configuration.validate();
|
|
13
|
+
this.typesenseClient = new TypesenseSearchClient(this.configuration.server);
|
|
14
|
+
this.searchClient = {
|
|
15
|
+
clearCache: () => this.clearCache(),
|
|
16
|
+
search: (instantsearchRequests) => this.searchTypesenseAndAdapt(instantsearchRequests),
|
|
17
|
+
searchForFacetValues: (instantsearchRequests) =>
|
|
18
|
+
this.searchTypesenseForFacetValuesAndAdapt(instantsearchRequests),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async searchTypesenseAndAdapt(instantsearchRequests) {
|
|
23
|
+
let typesenseResponse;
|
|
24
|
+
try {
|
|
25
|
+
typesenseResponse = await this._adaptAndPerformTypesenseRequest(instantsearchRequests);
|
|
26
|
+
|
|
27
|
+
const adaptedResponses = typesenseResponse.results.map((typesenseResult, index) => {
|
|
28
|
+
this._validateTypesenseResult(typesenseResult);
|
|
29
|
+
const responseAdapter = new SearchResponseAdapter(
|
|
30
|
+
typesenseResult,
|
|
31
|
+
instantsearchRequests[index],
|
|
32
|
+
this.configuration
|
|
33
|
+
);
|
|
34
|
+
return responseAdapter.adapt();
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
results: adaptedResponses,
|
|
39
|
+
};
|
|
40
|
+
} catch (error) {
|
|
41
|
+
console.error(error);
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async searchTypesenseForFacetValuesAndAdapt(instantsearchRequests) {
|
|
47
|
+
let typesenseResponse;
|
|
48
|
+
try {
|
|
49
|
+
typesenseResponse = await this._adaptAndPerformTypesenseRequest(instantsearchRequests);
|
|
50
|
+
|
|
51
|
+
const adaptedResponses = typesenseResponse.results.map((typesenseResult, index) => {
|
|
52
|
+
this._validateTypesenseResult(typesenseResult);
|
|
53
|
+
const responseAdapter = new FacetSearchResponseAdapter(
|
|
54
|
+
typesenseResult,
|
|
55
|
+
instantsearchRequests[index],
|
|
56
|
+
this.configuration
|
|
57
|
+
);
|
|
58
|
+
return responseAdapter.adapt();
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
return adaptedResponses;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
console.error(error);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async _adaptAndPerformTypesenseRequest(instantsearchRequests) {
|
|
69
|
+
const requestAdapter = new SearchRequestAdapter(instantsearchRequests, this.typesenseClient, this.configuration);
|
|
70
|
+
const typesenseResponse = await requestAdapter.request();
|
|
71
|
+
return typesenseResponse;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
clearCache() {
|
|
75
|
+
this.typesenseClient = new TypesenseSearchClient(this.configuration.server);
|
|
76
|
+
return this.searchClient;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
_validateTypesenseResult(typesenseResult) {
|
|
80
|
+
if (typesenseResult.error) {
|
|
81
|
+
throw new Error(`${typesenseResult.code} - ${typesenseResult.error}`);
|
|
82
|
+
}
|
|
83
|
+
if (!typesenseResult.hits && !typesenseResult.grouped_hits) {
|
|
84
|
+
throw new Error(`Did not find any hits. ${typesenseResult.code} - ${typesenseResult.error}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const utils = {
|
|
2
|
+
_adaptHighlightTag(value, highlightPreTag, highlightPostTag) {
|
|
3
|
+
return value
|
|
4
|
+
.replace(new RegExp("<mark>", "g"), highlightPreTag || "<mark>")
|
|
5
|
+
.replace(new RegExp("</mark>", "g"), highlightPostTag || "</mark>");
|
|
6
|
+
},
|
|
7
|
+
_adaptNumberOfPages() {
|
|
8
|
+
const result = this.typesenseResponse.found / this.typesenseResponse.request_params.per_page;
|
|
9
|
+
if (Number.isFinite(result)) {
|
|
10
|
+
return Math.ceil(result);
|
|
11
|
+
} else {
|
|
12
|
+
return 1;
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
};
|