Docs
API Documentation
Node API

Installation

It is available as @searchkit/api on npm.

npm install @searchkit/api@latest

Then import it in your project:

import Client from "@searchkit/api";

Usage

Node client handles incoming instantsearch requests, transforms them into Elasticsearch queries. With the response, it transforms it into a format that instantsearch can understand.

The client is built in a way to simplify the integration with multiple node server frameworks.

Read more on how to configure Searchkit on Searchkit API docs.

 
import Client from "@searchkit/api";
 
// SearchkitConfig is the configuration object that is used to configure the client
const client = Client({
  connection: {
    host: "https://commerce-demo.es.us-east4.gcp.elastic-cloud.com:9243",
    apiKey: "a2Rha1VJTUJMcGU4ajA3Tm9fZ0Y6MjAzX2pLbURTXy1hNm9SUGZGRlhJdw==", // optional apiKey
    headers: { // optional headers sent to Elasticsearch. Useful for basic auth
      "Authorization", 'Basic ' + Buffer.from(username + ":" + password).toString('base64'),
      "my-custom-header": "my-custom-value"
    },
  },
  search_settings: {
    highlight_attributes: ["title", "actors"],
    search_attributes: ["title", "actors"],
    result_attributes: ["title", "actors", "poster", "year"],
    facet_attributes: [
      "type",
      { attribute: "actors", field: "actors.keyword" },
      "rated",
      { attribute: "imdbrating", type: "numeric" },
      { attribute: "metascore", type: "numeric" },
    ],
  },
});

HandleRequest function

The handleRequest method is used to handle incoming REST requests from the browser. It takes in multiple instantsearch SearchRequest objects and returns multiple instantsearch SearchResponse objects.

Usage

// function to handle the incoming request
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // invokes handleRequest passing in the request body
  // containing the search requests
  const results = await client.handleRequest(req.body);
  // returning back the results to the browser
  res.send(results);
}

Parameters

The handleRequest function takes in the following parameters:

  • body - The request body containing the search requests.
  • options - The options object containing the following properties:
    • getQuery - The function used to override the default Elasticsearch query.
    • getBaseFilters - The function used to provide the base Elasticsearch filters. These filters are applied to all search requests.
    • hooks - The hooks object containing the following properties:
      • beforeSearch - The function that is invoked before the search request is executed.
      • afterSearch - The function that is invoked after the search response is received.

getQuery optional function

The getQuery function is used to override the default Elasticsearch query. The function must return an Elasticsearch query. You can read more about the Elasticsearch query DSL here (opens in a new tab).

Below is an example of a getQuery function that overrides the default query to use the combined_fields query type (read more about combined_fields here (opens in a new tab)).

To see the full Elasticsearch query that is executed to Elasticsearch, you can run the client in debug mode (see below).

  const results = await client.handleRequest(req.body, {
    getQuery: (query, search_attributes) => {
      return [
        {
          combined_fields: {
            query,
            fields: search_attributes,
          },
        },
      ];
    }
  });
Function Parameters
  • query: The query string from the search request.
  • search_attributes: The search attributes from the search configuration.

getBaseFilters optional function

The getBaseFilters function is used to add filters to the Elasticsearch query. The function must return an Elasticsearch query. You can read more about the Elasticsearch query DSL here (opens in a new tab).

This function is useful if the request needs to be filtered based on the user's session. For example, if you want to filter the search results based on the user's role or status.

Below is an example of a getBaseFilters function that adds a filter to the Elasticsearch query to only return results where the status field is published.

To see the full Elasticsearch query that is executed to Elasticsearch, you can run the client in debug mode (see below).

  const results = await client.handleRequest(req.body, {
    getBaseFilters: () => {
      return [
        {
          bool: {
            must: {
              term: {
                status: {
                  value: "published",
                },
              },
            },
          },
        },
      ];
    }
  });

Hooks

Hooks are functions that are invoked at different stages of the search request. Hooks are useful if you want to perform some action before or after the search request is executed.

beforeSearch hook function

The beforeSearch hook is invoked before the search request is executed. This hook is useful if you want to perform some action before the search request is executed.

Examples include:

  • Learn to rank
  • Semantic search
  • A/B testing

Below is an example of a beforeSearch hook that adds a rescore query to the Elasticsearch query.

To see the full Elasticsearch query that is executed to Elasticsearch, you can run the client in debug mode (see below).

  const results = await client.handleRequest(req.body, {
    hooks: {
      beforeSearch: (searchRequests) => {
        const uiRequest = searchRequests[0]
 
        return [
          {
            ...uiRequest,
            rescore: {
              window_size: 100,
              query: {
                rescore_query: {
                  match: {
                    plot: {
                      query: uiRequest.query,
                      operator: "and",
                    },
                  },
                },
                query_weight: 1,
                rescore_query_weight: 10,
              }
            }
          },
          searchRequests.slice(1, searchRequests.length)
        ]
        
      },
    }
  });
Function Parameters
  • searchRequests - An array of SearchRequest objects. Each SearchRequest object contains the following properties:
    • indexName - The Elasticsearch index name.
    • body - The Elasticsearch request body query.
    • request - The state requested from the UI. Contains attributes like query, filters, sort, size and more.

afterSearch hook function

The afterSearch hook is invoked after the search response is received. This hook is useful if you want to perform some action after the search response is received.

Examples include:

  • Logging
  • Analytics

Below is an example of an afterSearch hook that logs the search response to the console.

  const results = await client.handleRequest(req.body, {
    hooks: {
      afterSearch: (searchRequests, searchResponses) => {
        console.log(searchResponses);
        return searchResponses;
      },
    },
  });
Function Parameters
  • searchRequests - An array of SearchRequest objects. Each SearchRequest object contains the following properties:
    • indexName - The Elasticsearch index name.
    • body - The Elasticsearch request body query.
    • request - The state requested from the UI. Contains attributes like query, filters, sort, size and more.
  • searchResponse - The search responses array which is used to render the search results UI.

Debug mode

The client can be run in debug mode to help with debugging the Elasticsearch query. To run the client in debug mode, set the debug flag to true in the Client function.

This is helpful when you're overriding the query via getQuery or providing base filters via getBaseFilters and want to see the Elasticsearch query that is executed to Elasticsearch.

const client = Client({
  // search_settings configuration
  connection: {
    // ...
  },
  search_settings: {
    search_attributes: ["title", "plot"],
    // ...
  }
}, { debug: true });

When the client is run in debug mode, the Elasticsearch query is logged to the console.