#community-help

Converting InstantSearch.js Code to TypeSense Compatibility

TLDR AK asked how to transition a piece of code to compatibility with TypeSense. Jason provided a comprehensive guide on how to change the script and add the necessary elements.

Powered by Struct AI
2
14mo
Solved
Join the chat
Aug 29, 2022 (14 months ago)
AK
Photo of md5-f2442b8542de1fe5a9703111f2002950
AK
02:11 PM
Hi everyone does anyone know how to convert the following code to be compatible with TypeSense? :

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/instantsearch-theme-algolia.min.css">



<script>

var search;

function init_search() {
search = instantsearch({
appId: 'latency',
apiKey: '6be0576ff61c053d5f9a3225e2a90f76',
indexName: 'instant_search',
routing: true
});

search.addWidget(
instantsearch.widgets.searchBox({
container: '#search-box',
placeholder: 'Search for products'
})
);

var makeHits = instantsearch.connectors.connectHits(function renderHits({hits}) {
var hitlist = [];
hits.forEach(function(hit) {
hitlist.push(JSON.stringify(hit));
});
bubble_fn_search_result(hitlist);
});

search.addWidget(makeHits());

search.start();
}

$(document).ready(function(){
$.getScript("https://cdn.jsdelivr.net/npm/[email protected]", function(){
init_search();
});

});


</script>
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
03:54 PM
AK Instead of this:

search = instantsearch({
      appId: 'latency',
      apiKey: '6be0576ff61c053d5f9a3225e2a90f76',
      indexName: 'instant_search',
      routing: true
    });

You want to use:

const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
  server: {
    apiKey: "abcd", // Be sure to use the search-only-api-key
    nodes: [
      {
        host: "",
        port: "443",
        protocol: "https"
      }
    ]
  },
  // The following parameters are directly passed to Typesense's search API endpoint.
  //  So you can pass any parameters supported by the search endpoint below.
  //  queryBy is required.
  additionalSearchParameters: {
    queryBy: "title,authors"
  }
});
const searchClient = typesenseInstantsearchAdapter.searchClient;

const search = instantsearch({
  searchClient,
  indexName: "books" // Use your typesense collection name here
});

And then you want to add a new script tag like this just below the stylesheet:

<link rel="stylesheet" type="text/css" href="">

<!-- Add this: -->
<script src=""></script>