Gathering detailed insights and metrics for typesense-instantsearch-adapter
Gathering detailed insights and metrics for typesense-instantsearch-adapter
Gathering detailed insights and metrics for typesense-instantsearch-adapter
Gathering detailed insights and metrics for typesense-instantsearch-adapter
npm install typesense-instantsearch-adapter
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
413 Stars
467 Commits
63 Forks
12 Watching
8 Branches
11 Contributors
Updated on 27 Nov 2024
JavaScript (89.74%)
HTML (6.97%)
TypeScript (2.21%)
CSS (1.08%)
Cumulative downloads
Total Downloads
Last day
-11.5%
6,235
Compared to previous day
Last week
-5%
35,533
Compared to previous week
Last month
6.5%
154,778
Compared to previous month
Last year
85.1%
1,445,051
Compared to previous year
1
1
27
An adapter to use the awesome Instantsearch.js library with a Typesense Search Server, to build rich search interfaces.
Here is an example of UI you can build with this adapater: songs-search.typesense.org
Note: If your search interface is built on a custom autocomplete component, or is based on @algolia/autocomplete-js, then you don't need this adapter to use it with Typesense, as typesense-js library already supports client-side fetching data from any async data sources. Read more here.
The good folks over at Algolia have built and open-sourced Instantsearch.js which is a collection of out-of-the-box components that you can use to build interactive search experiences swiftly.
With the adapter in this repository, you'll be able to use Instantsearch (and its React, Vue and Angular cousins) with data indexed in a Typesense search server.
If you haven't used Instantsearch before, we recommend going through their Getting Started guide here. Once you go through the guide, follow the instructions below to plug the Typesense adapter into Instantsearch.
Here's a guide on building a quick search interface with Typesense and InstantSearch.js: https://typesense.org/docs/0.20.0/guide/search-ui-components.html
Here's a demo starter app that shows you how to use the adapter: https://github.com/typesense/typesense-instantsearch-demo
1$ npm install --save typesense-instantsearch-adapter @babel/runtime
or
1$ yarn add typesense-instantsearch-adapter @babel/runtime
or, you can also directly include the adapter via a script tag in your HTML:
1<script src="https://cdn.jsdelivr.net/npm/typesense-instantsearch-adapter@2/dist/typesense-instantsearch-adapter.min.js"></script> 2 3<!-- You might want to pin the version of the adapter used if you don't want to always receive the latest minor version -->
Since this is an adapter, it will not install the Instantsearch library automatically for you. You need to install one of the following in your application directly:
You'll find information on how to get started with each of the above libraries in their respective repos.
We'd also recommend checking out create-instantsearch-app to create your Search UI from a starter template.
1import instantsearch from "instantsearch.js"; 2import { searchBox, hits } from "instantsearch.js/es/widgets"; 3import TypesenseInstantSearchAdapter from "typesense-instantsearch-adapter"; 4 5const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({ 6 server: { 7 apiKey: "abcd", // Be sure to use an API key that only allows search operations 8 nodes: [ 9 { 10 host: "localhost", 11 path: "", // Optional. Example: If you have your typesense mounted in localhost:8108/typesense, path should be equal to '/typesense' 12 port: "8108", 13 protocol: "http", 14 }, 15 ], 16 cacheSearchResultsForSeconds: 2 * 60, // Cache search results from server. Defaults to 2 minutes. Set to 0 to disable caching. 17 }, 18 // The following parameters are directly passed to Typesense's search API endpoint. 19 // So you can pass any parameters supported by the search endpoint below. 20 // query_by is required. 21 additionalSearchParameters: { 22 query_by: "name,description,categories", 23 }, 24}); 25const searchClient = typesenseInstantsearchAdapter.searchClient; 26 27const search = instantsearch({ 28 searchClient, 29 indexName: "products", 30}); 31search.addWidgets([ 32 searchBox({ 33 container: "#searchbox", 34 }), 35 hits({ 36 container: "#hits", 37 templates: { 38 item: ` 39 <div class="hit-name"> 40 {{#helpers.highlight}}{ "attribute": "name" }{{/helpers.highlight}} 41 </div> 42 `, 43 }, 44 }), 45]); 46 47search.start();
You can add any of the Instantsearch widgets here that are supported by the adapter.
You'll also find a working example in test/support/testground. To run it, run npm run testground
from the project root folder.
1import React from "react";
2import ReactDOM from "react-dom";
3import { SearchBox } from "react-instantsearch-dom";
4import TypesenseInstantSearchAdapter from "typesense-instantsearch-adapter";
5
6const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
7 server: {
8 apiKey: "abcd", // Be sure to use an API key that only allows search operations
9 nodes: [
10 {
11 host: "localhost",
12 port: "8108",
13 path: "", // Optional. Example: If you have your typesense mounted in localhost:8108/typesense, path should be equal to '/typesense'
14 protocol: "http",
15 },
16 ],
17 cacheSearchResultsForSeconds: 2 * 60, // Cache search results from server. Defaults to 2 minutes. Set to 0 to disable caching.
18 },
19 // The following parameters are directly passed to Typesense's search API endpoint.
20 // So you can pass any parameters supported by the search endpoint below.
21 // query_by is required.
22 additionalSearchParameters: {
23 query_by: "name,description,categories",
24 },
25});
26const searchClient = typesenseInstantsearchAdapter.searchClient;
27
28const App = () => (
29 <InstantSearch indexName="products" searchClient={searchClient}>
30 <SearchBox />
31 <Hits />
32 </InstantSearch>
33);
You can then add any of the Instantsearch-React widgets here that are supported by the adapter.
The instructions above also apply to React Native.
App.vue:
1<template>
2 <ais-instant-search :search-client="searchClient" index-name="products">
3 <ais-search-box />
4 <ais-hits>
5 <div slot="item" slot-scope="{ item }">
6 <h2>{{ item.name }}</h2>
7 </div>
8 </ais-hits>
9 </ais-instant-search>
10</template>
11
12<script>
13import TypesenseInstantSearchAdapter from "typesense-instantsearch-adapter";
14
15const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
16 server: {
17 apiKey: "abcd", // Be sure to use an API key that only allows search operations
18 nodes: [
19 {
20 host: "localhost",
21 path: "", // Optional. Example: If you have your typesense mounted in localhost:8108/typesense, path should be equal to '/typesense'
22 port: "8108",
23 protocol: "http",
24 },
25 ],
26 cacheSearchResultsForSeconds: 2 * 60, // Cache search results from server. Defaults to 2 minutes. Set to 0 to disable caching.
27 },
28 // The following parameters are directly passed to Typesense's search API endpoint.
29 // So you can pass any parameters supported by the search endpoint below.
30 // query_by is required.
31 additionalSearchParameters: {
32 query_by: "name,description,categories",
33 },
34});
35const searchClient = typesenseInstantsearchAdapter.searchClient;
36
37export default {
38 data() {
39 return {
40 searchClient,
41 };
42 },
43};
44</script>
You can then add any of the Instantsearch widgets here that are supported by the adapter.
1// app.component.ts 2import { Component } from "@angular/core"; 3import TypesenseInstantSearchAdapter from "typesense-instantsearch-adapter"; 4 5const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({ 6 server: { 7 apiKey: "abcd", // Be sure to use an API key that only allows search operations 8 nodes: [ 9 { 10 host: "localhost", 11 path: "", // Optional. Example: If you have your typesense mounted in localhost:8108/typesense, path should be equal to '/typesense' 12 port: "8108", 13 protocol: "http", 14 }, 15 ], 16 cacheSearchResultsForSeconds: 2 * 60, // Cache search results from server. Defaults to 2 minutes. Set to 0 to disable caching. 17 }, 18 // The following parameters are directly passed to Typesense's search API endpoint. 19 // So you can pass any parameters supported by the search endpoint below. 20 // query_by is required. 21 additionalSearchParameters: { 22 query_by: "name,description,categories", 23 }, 24}); 25const searchClient = typesenseInstantsearchAdapter.searchClient; 26 27@Component({ 28 selector: "app-root", 29 templateUrl: "./app.component.html", 30 styleUrls: ["./app.component.css"], 31}) 32export class AppComponent { 33 config = { 34 indexName: "products", 35 searchClient, 36 }; 37}
You can then add any of the Instantsearch widgets here that are supported by the adapter.
hierarchicalMenu
For this widget, you want to create independent fields in the collection's schema with this specific naming convention:
field.lvl0
field.lvl1
field.lvl2
for a nested hierarchy of field.lvl0 > field.lvl1 > field.lvl2
Each of these fields can also hold an array of values. This is useful for handling multiple hierarchies.
sortBy
When instantiating this widget, you want to set the value of the index name to this particular format:
1search.addWidgets([ 2 sortBy({ 3 container: "#sort-by", 4 items: [ 5 { label: "Default", value: "products" }, 6 { label: "Price (asc)", value: "products/sort/price:asc" }, 7 { label: "Price (desc)", value: "products/sort/price:desc" }, 8 ], 9 }), 10]);
The generalized pattern for the value attribute is: <index_name>[/sort/<sort_by>]
. The adapter will use the value in <sort_by>
as the value for the sort_by
search parameter.
configure
If you need to specify a filter_by
search parameter for Typesense, you want to use the configure
InstantSearch widget, along with facetFilters
, numericFilters
or filters
.
The format for facetFilters
and numericFilters
is the same as Algolia's as described here.
But filters
needs to be in Typesense's filter_by
format as described in this table here.
Setting filter_by
inside the additionalQueryParameters
config only works when the widgets are loaded initially, because InstantSearch internally overrides the filter_by
field subsequently.
Read more here.
index
For Federated / Multi-Index Search, you'd need to use the index
widget. To then be able to specify different search parameters for each index/collection, you can specify them using the collectionSpecificSearchParameters
configuration:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
2 server: {
3 apiKey: "abcd", // Be sure to use an API key that only allows search operations
4 nodes: [{ host: "localhost", path: "/", port: "8108", protocol: "http" }],
5 },
6 // Search parameters that are common to all collections/indices go here:
7 additionalSearchParameters: {
8 numTypos: 3,
9 },
10 // Search parameters that need to be *overridden* on a per-collection-basis go here:
11 collectionSpecificSearchParameters: {
12 products: {
13 query_by: "name,description,categories",
14 },
15 brands: {
16 query_by: "name",
17 },
18 },
19});
20const searchClient = typesenseInstantsearchAdapter.searchClient;
Essentially, any parameters set in collectionSpecificSearchParameters
will be merged with the values in additionalSearchParameters
when querying Typesense, effectively overriding values in additionalSearchParameters
on a per-collection-basis.
geoSearch
Algolia uses _geoloc
by default for the name of the field that stores the lat long values for a record.
In Typesense, you can name the geo location field anything. If you use a name other than _geoloc
, you need to specify it when initializing the adapter like below, so InstantSearch can access it:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({ 2 server: { 3 apiKey: "xyz", 4 nodes: [ 5 { 6 host: "localhost", 7 port: "8108", 8 path: "/", 9 protocol: "http", 10 }, 11 ], 12 }, 13 geoLocationField: "lat_lng_field", // <<====== 14 additionalSearchParameters, 15});
dynamicWidgets
Available as of Typesense Server
v0.25.0.rc12
This dynamicWidgets
widget works out of the box with no additional changes,
but if you want to control the order in which these facets are displayed in the UI
Instantsearch expects a parameter called renderingContent
to be set.
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
2 server: {
3 apiKey: "xyz",
4 nodes: [
5 {
6 host: "localhost",
7 port: "8108",
8 path: "/",
9 protocol: "http",
10 },
11 ],
12 },
13 renderingContent: {
14 // <<===== Add this, only if you want to control the order of the widgets displayed by dynamicWidgets
15 facetOrdering: {
16 facets: {
17 order: ["size", "brand"], // <<===== Change this as needed
18 },
19 },
20 },
21 additionalSearchParameters,
22});
Read more about all available options for renderingContent
in Algolia's documentation here.
Available as of typesense-instantsearch-adapter
2.7.0-2
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:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
2 server: {
3 apiKey: "xyz",
4 nodes: [
5 {
6 host: "localhost",
7 port: "8108",
8 path: "/",
9 protocol: "http",
10 },
11 ],
12 },
13 facetableFieldsWithSpecialCharacters: ["brand"], // <======= Add string fields that have colons in their values here, to aid in parsing
14 additionalSearchParameters,
15});
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:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
2 server: {
3 apiKey: "xyz",
4 nodes: [
5 {
6 host: "localhost",
7 port: "8108",
8 path: "/",
9 protocol: "http",
10 },
11 ],
12 },
13 facetableFieldsWithSpecialCharacters: ["price>discount"], // // <======= Add numeric fields that have >, < or = in their names, to aid in parsing
14 additionalSearchParameters,
15});
facet_by
optionsAvailable as of typesense-instantsearch-adapter
2.8.0-1
and Typesense Serverv0.26.0.rc25
The facet_by
parameter is managed by InstantSearch internally when you use the various filter widgets.
But if you need to pass custom options to the facet_by
parameter (eg: server-side sort options), then you can use the facetByOptions
parameter as shown below:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
2 server: {
3 apiKey: "xyz",
4 nodes: [
5 {
6 host: "localhost",
7 port: "8108",
8 path: "/",
9 protocol: "http",
10 },
11 ],
12 },
13 facetByOptions: {
14 brand: "(sort_by: _alpha:asc)",
15 category: "(sort_by: _alpha:desc)",
16 }, // <======= Add any facet_by parameter as a key value pair. Don't forget the surrounding parantheses in the value.
17 collectionSpecificFacetByOptions: {
18 collection1: {
19 brand: "(sort_by: _alpha:desc)",
20 },
21 }, // <======= Use this parameter if multiple collections share the same field names, and you want to use different options for each field. This will override facetByOptions for that particular collection.
22 additionalSearchParameters,
23});
Note that for sorting in refinementLists, in addition to sorting on the Typesense Server-side, you'd also need to pass the sortBy
parameter to the refinementList widget to also sort the results appropriately on the client-side.
filter_by
optionsAvailable as of typesense-instantsearch-adapter
2.8.0-5
The filter_by
parameter is managed by InstantSearch internally when you use the various filter widgets.
By default, the adapter uses exact filtering (filter_by: field:=value
) when sending the queries to Typesense.
If you need to configure the adapter to use :
(non-exact word-level filtering - filter_by: field:value
), you want to instantiate the adapter using the filterByOptions
configuration:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
2 server: {
3 apiKey: "xyz",
4 nodes: [
5 {
6 host: "localhost",
7 port: "8108",
8 path: "/",
9 protocol: "http",
10 },
11 ],
12 },
13 filterByOptions: {
14 brand: { exactMatch: false }, // <========== Add this to do non-exact word-level filtering
15 category: { exactMatch: false },
16 },
17 collectionSpecificFilterByOptions: {
18 collection1: {
19 brand: { exactMatch: false },
20 },
21 }, // <======= Use this parameter if multiple collections share the same field names, and you want to use different options for each field. This will override filterByOptions for that particular collection.
22 additionalSearchParameters,
23});
Available as of typesense-instantsearch-adapter
2.9.0-0
Here's a way to disable overrides / curation rules, when users select a particular sort order:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
2 server: {
3 apiKey: "xyz",
4 nodes: [
5 {
6 host: "localhost",
7 port: "8108",
8 path: "/",
9 protocol: "http",
10 },
11 ],
12 },
13 sortByOptions: {
14 "field1:desc,field2:desc": { enable_overrides: false }, // <========== Add this to disable sorting when this particular Typesense `sort_by` string is generated by the sortBy widget
15 },
16 collectionSpecificSortByOptions: {
17 collection2: {
18 "field1:desc,field2:desc": { enable_overrides: false },
19 },
20 }, // <======= Use this parameter if multiple collections share the same field names, and you want to use different options for each field. This will override sortByOptions for that particular collection.
21 additionalSearchParameters,
22});
If you have a sortBy widgets configured with an indexName value of products/sort/price:asc
for eg, then the key inside sortByOptions
should be price:asc
.
Available as of typesense-instantsearch-adapter
2.7.1-4
By default, when group_by
is used as a search parameters, the adapter flattens the results across all groups into a single list of sequential hits.
If you'd like to preserve the groups, you want to set flattenGroupedHits: false
when instantiating the adapter.
This will place the first hit in a group as the primary hit, and then add all hits in the group inside a _grouped_hits
key inside each hit.
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({ 2 server: { 3 apiKey: "xyz", 4 nodes: [ 5 { 6 host: "localhost", 7 port: "8108", 8 path: "/", 9 protocol: "http", 10 }, 11 ], 12 }, 13 flattenGroupedHits: false, // <======= 14 additionalSearchParameters, 15});
Available as of typesense-instantsearch-adapter
2.7.0-3
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.
Here's a demo that you can run locally to see this in action: https://github.com/typesense/showcase-hn-comments-semantic-search.
Here's how to do this in Instantsearch.js:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({ 2 server: { 3 apiKey: "xyz", 4 nodes: [ 5 { 6 host: "localhost", 7 port: "8108", 8 path: "/", 9 protocol: "http", 10 }, 11 ], 12 }, 13 additionalSearchParameters, 14}); 15// from https://github.com/typesense/showcase-hn-comments-semantic-search/blob/8a33006cae58b425c53f56a64e1273e808cd9375/src/js/index.js#L101 16const searchClient = typesenseInstantsearchAdapter.searchClient; 17search = instantsearch({ 18 searchClient, 19 indexName: INDEX_NAME, 20 routing: true, 21 async searchFunction(helper) { 22 // This fetches 200 (nearest neighbor) results for semantic / hybrid search 23 24 let query = helper.getQuery().query; 25 const page = helper.getPage(); // Retrieve the current page 26 27 if (query !== "" && ["semantic", "hybrid"].includes($("#search-type-select").val())) { 28 console.log(helper.getQuery().query); 29 helper 30 .setQueryParameter( 31 "typesenseVectorQuery", // <=== Special parameter that only works in typesense-instantsearch-adapter@2.7.0-3 and above 32 `embedding:([], k:200)`, 33 ) 34 .setPage(page) 35 .search(); 36 console.log(helper.getQuery().query); 37 } else { 38 helper.setQueryParameter("typesenseVectorQuery", null).setPage(page).search(); 39 } 40 }, 41});
There are two modes of caching:
Server-side caching:
To enable server-side caching, add a parameter called useServerSideSearchCache: true
in the server
configuration block of the typesense-instantsearch-adapter like this:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({ 2 server: { 3 apiKey: "...", 4 nearestNode: {...}, 5 nodes: [...], 6 useServerSideSearchCache: true // <<< Add this to send use_cache as a query parameter instead of post body parameter 7 }, 8 additionalSearchParameters: {...} 9});
This will cause the adapter to add ?use_cache=true
as a URL query parameter to all search requests initiated by the adapter, which will then cause Typesense Server to enable server-side caching for these requests.
Client-side caching:
The adapter also has client-side caching enabled by default, to prevent unnecessary network calls to the server. The TTL for this client-side cache can be configured like this:
1const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({ 2 server: { 3 apiKey: "...", 4 nearestNode: {...}, 5 nodes: [...], 6 cacheSearchResultsForSeconds: 2 * 60 // <<< Add this to configure the TTL for client-side cache in the browser 7 }, 8 additionalSearchParameters: {...} 9});
Typesense Server | typesense-instantsearch-adapter | instantsearch.js | react-instantsearch | vue-instantsearch | angular-instantsearch |
---|---|---|---|---|---|
>= v0.25.0 | >= v2.7.1 | >= 4.51 | >= 6.39 | >= 4.8 | >= 4.4 |
>= v0.25.0.rc14 | >= v2.7.0-1 | >= 4.51 | >= 6.39 | >= 4.8 | >= 4.4 |
>= v0.25.0.rc12 | >= v2.6.0 | >= 4.51 | >= 6.39 | >= 4.8 | >= 4.4 |
>= v0.24 | >= v2.5.0 | >= 4.2.0 | >= 6.0.0 | >= 2.2.1 | >= 3.0.0 |
>= v0.21 | >= v2.0.0 | >= 4.2.0 | >= 6.0.0 | >= 2.2.1 | >= 3.0.0 |
>= v0.19 | >= v1.0.0 | >= 4.2.0 | >= 6.0.0 | >= 2.2.1 | >= 3.0.0 |
>= v0.15 | >= v0.3.0 | >= 4.2.0 | >= 6.0.0 | >= 2.2.1 | >= 3.0.0 |
>= v0.14 | >= v0.2.0 | >= 4.2.0 | >= 6.0.0 | >= 2.2.1 | >= 3.0.0 |
>= v0.13 | >= v0.1.0 | >= 4.2.0 | >= 6.0.0 | >= 2.2.1 | >= 3.0.0 |
>= v0.12 | >= v0.0.4 | >= 4.2.0 | >= 6.0.0 | >= 2.2.1 | >= 3.0.0 |
If a particular version of the above libraries don't work with the adapter, please open a Github issue with details.
This adapter works with all widgets in this list
1$ npm install 2$ npm run typesenseServer 3$ FORCE_REINDEX=true npm run indexTestData 4 5$ npm link typesense-instantsearch-adapter 6$ npm run testground 7 8$ npm test
To release a new version, we use the np package:
1$ npm install --global np 2$ np 3 4# Follow instructions that np shows you 5
If you have any questions or run into any problems, please create a Github issue and we'll try our best to help.
© 2020-present Typesense, Inc.
No vulnerabilities found.
Reason
30 commit(s) and 8 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 2/10 approved changesets -- score normalized to 2
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
36 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More