typesense-instantsearch-adapter 2.7.0-1 → 2.7.0-3

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/README.md CHANGED
@@ -400,10 +400,111 @@ const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
400
400
 
401
401
  Read more about all available options for `renderingContent` in [Algolia's documentation here](https://www.algolia.com/doc/api-reference/api-parameters/renderingContent/?client=javascript#examples).
402
402
 
403
+ ### Special characters in field names / values
404
+
405
+ > Available as of typesense-instantsearch-adapter `2.7.0-2`
406
+
407
+ - If any string fields in your documents have a colon `:` in their values (for eg, let's say there's a field called `{ brand: "a:b" }`, then you would need to add a parameter like below when instantiating the adapter:
408
+
409
+ ```js
410
+ const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
411
+ server: {
412
+ apiKey: "xyz",
413
+ nodes: [
414
+ {
415
+ host: "localhost",
416
+ port: "8108",
417
+ path: "/",
418
+ protocol: "http",
419
+ },
420
+ ],
421
+ },
422
+ facetableFieldsWithSpecialCharacters: ["brand"], // <======= Add string fields that have colons in their values here, to aid in parsing
423
+ additionalSearchParameters,
424
+ });
425
+ ```
426
+
427
+ - If any numeric field _names_ in your documents have special characters like `>`, `<`, `=` (for eg, let's say there's a field called `{ price>discount: 3.0 }`) then you would need to add a parameter like below when instantiating the adapter:
428
+
429
+ ```js
430
+ const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
431
+ server: {
432
+ apiKey: "xyz",
433
+ nodes: [
434
+ {
435
+ host: "localhost",
436
+ port: "8108",
437
+ path: "/",
438
+ protocol: "http",
439
+ },
440
+ ],
441
+ },
442
+ facetableFieldsWithSpecialCharacters: ["price>discount"], // // <======= Add numeric fields that have >, < or = in their names, to aid in parsing
443
+ additionalSearchParameters,
444
+ });
445
+ ```
446
+
447
+ ### Vector Search
448
+
449
+ > Available as of typesense-instantsearch-adapter `2.7.0-3`
450
+
451
+ The general idea is to first hook into the query life-cycle of Instantsearch, intercept the typed query and send it to an embedding API, fetch the embeddings and then send the vectors to Typesense to do a nearest neighbor vector search.
452
+
453
+ Here's a demo that you can run locally to see this in action: [https://github.com/typesense/typesense-instantsearch-semantic-search-demo](https://github.com/typesense/typesense-instantsearch-semantic-search-demo).
454
+
455
+ Here's how to do this in Instantsearch.js:
456
+
457
+ ```javascript
458
+ const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
459
+ server: {
460
+ apiKey: "xyz",
461
+ nodes: [
462
+ {
463
+ host: "localhost",
464
+ port: "8108",
465
+ path: "/",
466
+ protocol: "http",
467
+ },
468
+ ],
469
+ },
470
+ additionalSearchParameters,
471
+ });
472
+ const searchClient = typesenseInstantsearchAdapter.searchClient;
473
+ const search = instantsearch({
474
+ searchClient,
475
+ indexName: 'products',
476
+ routing: true,
477
+ async searchFunction(helper) {
478
+ let query = helper.getQuery().query;
479
+
480
+ if (query !== '') {
481
+ // Get embedding for the query
482
+ let response = await fetch(
483
+ 'http://localhost:8000/embedding?' + new URLSearchParams({ q: query }) // <=== Embedding API
484
+ );
485
+
486
+ let parsedResponse = await response.json();
487
+
488
+ console.log(parsedResponse);
489
+
490
+ // Send the embedding to Typesense to do a nearest neighbor search
491
+ helper
492
+ .setQueryParameter(
493
+ 'typesenseVectorQuery', // <=== Special parameter that only works in typesense-instantsearch-adapter@2.7.0-3 and above
494
+ `vectors:([${parsedResponse['embedding'].join(',')}])`
495
+ )
496
+ .search();
497
+ } else {
498
+ helper.setQueryParameter('typesenseVectorQuery', null).search();
499
+ }
500
+ },
501
+ });
502
+ ```
503
+
403
504
  ## Compatibility
404
505
 
405
506
  | Typesense Server | typesense-instantsearch-adapter | instantsearch.js | react-instantsearch | vue-instantsearch | angular-instantsearch |
406
- |------------------|---------------------------------| ---------------- | ------------------- | ----------------- | --------------------- |
507
+ | ---------------- | ------------------------------- | ---------------- | ------------------- | ----------------- | --------------------- |
407
508
  | \>= v0.25.0.rc14 | \>= v2.7.0-1 | \>= 4.51 | \>= 6.39 | \>= 4.8 | \>= 4.4 |
408
509
  | \>= v0.25.0.rc12 | \>= v2.6.0 | \>= 4.51 | \>= 6.39 | \>= 4.8 | \>= 4.4 |
409
510
  | \>= v0.24 | \>= v2.5.0 | \>= 4.2.0 | \>= 6.0.0 | \>= 2.2.1 | \>= 3.0.0 |
@@ -2214,6 +2214,7 @@ var Configuration = /*#__PURE__*/function () {
2214
2214
  _ref4,
2215
2215
  _this$additionalSearc4,
2216
2216
  _options$geoLocationF,
2217
+ _options$facetableFie,
2217
2218
  _options$collectionSp,
2218
2219
  _this = this;
2219
2220
 
@@ -2236,6 +2237,7 @@ var Configuration = /*#__PURE__*/function () {
2236
2237
  this.additionalSearchParameters.sort_by = (_ref3 = (_this$additionalSearc3 = this.additionalSearchParameters.sortBy) !== null && _this$additionalSearc3 !== void 0 ? _this$additionalSearc3 : this.additionalSearchParameters.sort_by) !== null && _ref3 !== void 0 ? _ref3 : "";
2237
2238
  this.additionalSearchParameters.highlight_full_fields = (_ref4 = (_this$additionalSearc4 = this.additionalSearchParameters.highlightFullFields) !== null && _this$additionalSearc4 !== void 0 ? _this$additionalSearc4 : this.additionalSearchParameters.highlight_full_fields) !== null && _ref4 !== void 0 ? _ref4 : this.additionalSearchParameters.query_by;
2238
2239
  this.geoLocationField = (_options$geoLocationF = options.geoLocationField) !== null && _options$geoLocationF !== void 0 ? _options$geoLocationF : "_geoloc";
2240
+ this.facetableFieldsWithSpecialCharacters = (_options$facetableFie = options.facetableFieldsWithSpecialCharacters) !== null && _options$facetableFie !== void 0 ? _options$facetableFie : [];
2239
2241
  this.collectionSpecificSearchParameters = (_options$collectionSp = options.collectionSpecificSearchParameters) !== null && _options$collectionSp !== void 0 ? _options$collectionSp : {};
2240
2242
  Object.keys(this.collectionSpecificSearchParameters).forEach(function (collection) {
2241
2243
  var _params$queryBy, _params$preset, _params$sortBy, _ref5, _ref6, _params$highlightFull;
@@ -2419,9 +2421,10 @@ var SearchRequestAdapter = /*#__PURE__*/function () {
2419
2421
  // }
2420
2422
  var intermediateFacetFilters = {};
2421
2423
  item.forEach(function (facetFilter) {
2422
- var facetFilterMatches = facetFilter.match(_this.constructor.FILTER_STRING_MATCHING_REGEX);
2423
- var fieldName = "".concat(facetFilterMatches[1]).concat(facetFilterMatches[2]);
2424
- var fieldValue = "".concat(facetFilterMatches[3]);
2424
+ var _this$_parseFacetFilt = _this._parseFacetFilter(facetFilter),
2425
+ fieldName = _this$_parseFacetFilt.fieldName,
2426
+ fieldValue = _this$_parseFacetFilt.fieldValue;
2427
+
2425
2428
  intermediateFacetFilters[fieldName] = intermediateFacetFilters[fieldName] || [];
2426
2429
  intermediateFacetFilters[fieldName].push(fieldValue);
2427
2430
  });
@@ -2477,11 +2480,9 @@ var SearchRequestAdapter = /*#__PURE__*/function () {
2477
2480
  // fieldName:fieldValue
2478
2481
  // Into
2479
2482
  // fieldName:=fieldValue
2480
- var facetFilterMatches = item.match(_this.constructor.FILTER_STRING_MATCHING_REGEX);
2481
-
2482
- var _fieldName = "".concat(facetFilterMatches[1]).concat(facetFilterMatches[2]);
2483
-
2484
- var fieldValue = "".concat(facetFilterMatches[3]);
2483
+ var _this$_parseFacetFilt2 = _this._parseFacetFilter(item),
2484
+ _fieldName = _this$_parseFacetFilt2.fieldName,
2485
+ fieldValue = _this$_parseFacetFilt2.fieldValue;
2485
2486
 
2486
2487
  var _typesenseFilterString;
2487
2488
 
@@ -2498,6 +2499,51 @@ var SearchRequestAdapter = /*#__PURE__*/function () {
2498
2499
 
2499
2500
  return adaptedResult;
2500
2501
  }
2502
+ }, {
2503
+ key: "_parseFacetFilter",
2504
+ value: function _parseFacetFilter(facetFilter) {
2505
+ var _this$configuration$f;
2506
+
2507
+ var filterStringMatchingRegex, facetFilterMatches, fieldName, fieldValue; // This is helpful when the filter looks like `facetName:with:colons:facetValue:with:colons` and the default regex above parses the filter as `facetName:with:colons:facetValue:with` and `colon`.
2508
+ // So if a facetValue can contain a colon, we ask users to pass in all possible facetable fields in `facetableFieldsWithSpecialCharacters` when instantiating the adapter, so we can explicitly match against that.
2509
+
2510
+ if (((_this$configuration$f = this.configuration.facetableFieldsWithSpecialCharacters) === null || _this$configuration$f === void 0 ? void 0 : _this$configuration$f.length) > 0) {
2511
+ // escape any Regex special characters, source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
2512
+ var sanitizedFacetableFieldsWithSpecialCharacters = this.configuration.facetableFieldsWithSpecialCharacters.flat().map(function (f) {
2513
+ return f.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2514
+ });
2515
+ filterStringMatchingRegex = new RegExp("^(".concat(sanitizedFacetableFieldsWithSpecialCharacters.join("|"), "):(.*)$"));
2516
+ facetFilterMatches = facetFilter.match(filterStringMatchingRegex);
2517
+
2518
+ if (facetFilterMatches != null) {
2519
+ fieldName = "".concat(facetFilterMatches[1]);
2520
+ fieldValue = "".concat(facetFilterMatches[2]);
2521
+ return {
2522
+ fieldName: fieldName,
2523
+ fieldValue: fieldValue
2524
+ };
2525
+ }
2526
+ } // If we haven't found any matches yet
2527
+ // Use the default filter parsing regex, which assumes that only facet names have colons, and not facet values
2528
+
2529
+
2530
+ filterStringMatchingRegex = this.constructor.DEFAULT_FACET_FILTER_STRING_MATCHING_REGEX;
2531
+ facetFilterMatches = facetFilter.match(filterStringMatchingRegex); // console.log(filterStringMatchingRegex);
2532
+ // console.log(facetFilter);
2533
+ // console.log(facetFilterMatches);
2534
+
2535
+ if (facetFilterMatches == null) {
2536
+ console.error("[Typesense-Instantsearch-Adapter] Parsing failed for a facet filter `".concat(facetFilter, "` with the Regex `").concat(filterStringMatchingRegex, "`. If you have field names with special characters, be sure to add them to a parameter called `facetableFieldsWithSpecialCharacters` when instantiating the adapter."));
2537
+ } else {
2538
+ fieldName = "".concat(facetFilterMatches[1]).concat(facetFilterMatches[2]);
2539
+ fieldValue = "".concat(facetFilterMatches[3]);
2540
+ }
2541
+
2542
+ return {
2543
+ fieldName: fieldName,
2544
+ fieldValue: fieldValue
2545
+ };
2546
+ }
2501
2547
  }, {
2502
2548
  key: "_escapeFacetValue",
2503
2549
  value: function _escapeFacetValue(value) {
@@ -2517,6 +2563,8 @@ var SearchRequestAdapter = /*#__PURE__*/function () {
2517
2563
  }, {
2518
2564
  key: "_adaptNumericFilters",
2519
2565
  value: function _adaptNumericFilters(numericFilters) {
2566
+ var _this2 = this;
2567
+
2520
2568
  // Need to transform this:
2521
2569
  // ["field1<=634", "field1>=289", "field2<=5", "field3>=3"]
2522
2570
  // to:
@@ -2542,14 +2590,13 @@ var SearchRequestAdapter = /*#__PURE__*/function () {
2542
2590
 
2543
2591
  var filtersHash = {};
2544
2592
  numericFilters.forEach(function (filter) {
2545
- var _filter$match = filter.match(new RegExp("(.*?)(<=|>=|>|<|:|=)(.*)")),
2546
- _filter$match2 = (0,_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__["default"])(_filter$match, 4),
2547
- field = _filter$match2[1],
2548
- operator = _filter$match2[2],
2549
- value = _filter$match2[3];
2550
-
2551
- filtersHash[field] = filtersHash[field] || {};
2552
- filtersHash[field][operator] = value;
2593
+ var _this2$_parseNumericF = _this2._parseNumericFilter(filter),
2594
+ fieldName = _this2$_parseNumericF.fieldName,
2595
+ operator = _this2$_parseNumericF.operator,
2596
+ fieldValue = _this2$_parseNumericF.fieldValue;
2597
+
2598
+ filtersHash[fieldName] = filtersHash[fieldName] || {};
2599
+ filtersHash[fieldName][operator] = fieldValue;
2553
2600
  }); // Transform that to:
2554
2601
  // "field1:=[634..289] && field2:<=5 && field3:>=3"
2555
2602
 
@@ -2570,6 +2617,64 @@ var SearchRequestAdapter = /*#__PURE__*/function () {
2570
2617
  adaptedResult = adaptedFilters.join(" && ");
2571
2618
  return adaptedResult;
2572
2619
  }
2620
+ }, {
2621
+ key: "_parseNumericFilter",
2622
+ value: function _parseNumericFilter(numericFilter) {
2623
+ var _this$configuration$f2;
2624
+
2625
+ var filterStringMatchingRegex, numericFilterMatches;
2626
+ var fieldName, operator, fieldValue; // The following is helpful when the facetName has special characters like > and the default regex fails to parse it properly.
2627
+ // So we ask users to pass in facetable fields in `facetableFieldsWithSpecialCharactersWithSpecialCharacters` when instantiating the adapter, so we can explicitly match against that.
2628
+
2629
+ if (((_this$configuration$f2 = this.configuration.facetableFieldsWithSpecialCharacters) === null || _this$configuration$f2 === void 0 ? void 0 : _this$configuration$f2.length) > 0) {
2630
+ // escape any Regex special characters, source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
2631
+ var sanitizedFacetableFieldsWithSpecialCharacters = this.configuration.facetableFieldsWithSpecialCharacters.map(function (f) {
2632
+ return f.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2633
+ });
2634
+ filterStringMatchingRegex = new RegExp("^(".concat(sanitizedFacetableFieldsWithSpecialCharacters.join("|"), ")(<=|>=|>|<|=)(.*)$"));
2635
+ numericFilterMatches = numericFilter.match(filterStringMatchingRegex);
2636
+
2637
+ if (numericFilterMatches != null) {
2638
+ // If no matches are found or if the above didn't trigger, fall back to the default regex
2639
+ var _numericFilterMatches = numericFilterMatches;
2640
+
2641
+ var _numericFilterMatches2 = (0,_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__["default"])(_numericFilterMatches, 4);
2642
+
2643
+ fieldName = _numericFilterMatches2[1];
2644
+ operator = _numericFilterMatches2[2];
2645
+ fieldValue = _numericFilterMatches2[3];
2646
+ return {
2647
+ fieldName: fieldName,
2648
+ operator: operator,
2649
+ fieldValue: fieldValue
2650
+ };
2651
+ }
2652
+ } // If we haven't found any matches yet, fall back to the default regex
2653
+
2654
+
2655
+ filterStringMatchingRegex = this.constructor.DEFAULT_NUMERIC_FILTER_STRING_MATCHING_REGEX;
2656
+ numericFilterMatches = numericFilter.match(filterStringMatchingRegex); // console.log(filterStringMatchingRegex);
2657
+ // console.log(numericFilter);
2658
+ // console.log(numericFilterMatches);
2659
+
2660
+ if (numericFilterMatches == null) {
2661
+ console.error("[Typesense-Instantsearch-Adapter] Parsing failed for a numeric filter `".concat(numericFilter, "` with the Regex `").concat(filterStringMatchingRegex, "`. If you have field names with special characters, be sure to add them to a parameter called `facetableFieldsWithSpecialCharacters` when instantiating the adapter."));
2662
+ } else {
2663
+ var _numericFilterMatches3 = numericFilterMatches;
2664
+
2665
+ var _numericFilterMatches4 = (0,_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__["default"])(_numericFilterMatches3, 4);
2666
+
2667
+ fieldName = _numericFilterMatches4[1];
2668
+ operator = _numericFilterMatches4[2];
2669
+ fieldValue = _numericFilterMatches4[3];
2670
+ }
2671
+
2672
+ return {
2673
+ fieldName: fieldName,
2674
+ operator: operator,
2675
+ fieldValue: fieldValue
2676
+ };
2677
+ }
2573
2678
  }, {
2574
2679
  key: "_adaptGeoFilter",
2575
2680
  value: function _adaptGeoFilter(_ref) {
@@ -2703,6 +2808,12 @@ var SearchRequestAdapter = /*#__PURE__*/function () {
2703
2808
  if (params.facetQuery) {
2704
2809
  typesenseSearchParams.facet_query = "".concat(params.facetName, ":").concat(params.facetQuery);
2705
2810
  typesenseSearchParams.per_page = 0;
2811
+ } // If a custom vector query is specified, set q=*
2812
+
2813
+
2814
+ if (params.typesenseVectorQuery) {
2815
+ typesenseSearchParams.vector_query = params.typesenseVectorQuery;
2816
+ typesenseSearchParams.q = "*";
2706
2817
  } // console.log(params);
2707
2818
  // console.log(typesenseSearchParams);
2708
2819
  // Filter out empty or null values, so we don't accidentally override values set in presets
@@ -2726,15 +2837,16 @@ var SearchRequestAdapter = /*#__PURE__*/function () {
2726
2837
  key: "request",
2727
2838
  value: function () {
2728
2839
  var _request = (0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_4___default().mark(function _callee() {
2729
- var _this2 = this;
2840
+ var _this3 = this;
2730
2841
 
2731
2842
  var searches;
2732
2843
  return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_4___default().wrap(function _callee$(_context) {
2733
2844
  while (1) {
2734
2845
  switch (_context.prev = _context.next) {
2735
2846
  case 0:
2847
+ // console.log(this.instantsearchRequests);
2736
2848
  searches = this.instantsearchRequests.map(function (instantsearchRequest) {
2737
- return _this2._buildSearchParameters(instantsearchRequest);
2849
+ return _this3._buildSearchParameters(instantsearchRequest);
2738
2850
  });
2739
2851
  return _context.abrupt("return", this.typesenseClient.multiSearch.perform({
2740
2852
  searches: searches
@@ -2760,10 +2872,15 @@ var SearchRequestAdapter = /*#__PURE__*/function () {
2760
2872
  return new RegExp("^(.+?)(?=(/sort/(.*))|$)");
2761
2873
  }
2762
2874
  }, {
2763
- key: "FILTER_STRING_MATCHING_REGEX",
2875
+ key: "DEFAULT_FACET_FILTER_STRING_MATCHING_REGEX",
2764
2876
  get: function get() {
2765
2877
  return new RegExp("(.*)((?!:).):(?!:)(.*)");
2766
2878
  }
2879
+ }, {
2880
+ key: "DEFAULT_NUMERIC_FILTER_STRING_MATCHING_REGEX",
2881
+ get: function get() {
2882
+ return new RegExp("(.*?)(<=|>=|>|<|=)(.*)");
2883
+ }
2767
2884
  }]);
2768
2885
 
2769
2886
  return SearchRequestAdapter;