Building a custom connector
Elastic Cloud Serverless projects are autoscaled environments, fully managed by Elastic and available on Elastic Cloud. Availability This functionality is generally available and ready for production usage. Serverless interfaces and procedures might differ from classic Elastic Stack deployments. The Elastic Stack includes Elastic's core products such as Elasticsearch, Kibana, Logstash, and Beats. Availability This functionality is generally available and ready for production usage. Unless stated otherwise on the page, this functionality is available when your Elastic Stack is deployed on Elastic Cloud Hosted, Elastic Cloud Enterprise, Elastic Cloud on Kubernetes, and self-managed environments. This documentation corresponds to the latest patch available for each minor version. If you're not using the latest patch, check the release notes for changes.
Serverless
Generally available
Stack
Generally available
This guide helps you build a custom connector so you can use Search UI with your own API.
A connector is a class that implements the following methods:
onSearchonAutocompleteonResultClickonAutocompleteResultClick
Below is an example of a custom connector. Example is given in typescript as the types may be helpful to you.
See Request State, Response State and Search Query Config for more information.
import type { APIConnector } from "@elastic/search-ui";
class MyAPIConnector implements APIConnector {
async onSearch(
state: RequestState,
queryConfig: QueryConfig
): Promise<ResponseState> {
const { searchTerm, current, filters, sort } = state;
// perform a request to your API with the request state
const response = await fetch("https://api.my-host/search", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
searchTerm,
current,
filters,
sort
})
});
// response will need to be in the shape of ResponseState.
// Alternatively you could transform the response here
return response.json();
}
async onAutocomplete(
state: RequestState,
queryConfig: AutocompleteQueryConfig
): Promise<AutocompleteResponseState> {
const response = await fetch(
"https://api.my-host/autocomplete?query" + state.searchTerm,
{
headers: {
"Content-Type": "application/json"
}
}
);
// response will need to be in the shape of AutocompleteResponseState.
// Alternatively you could transform the response here
return response.json();
}
onResultClick(params): void {
console.log(
"perform a call to the API to highlight a result has been clicked"
);
}
onAutocompleteResultClick(params): void {
console.log(
"perform a call to the API to highlight an autocomplete result has been clicked"
);
}
}
Once you have built your connector, you can simply use it within Search UI.
const connector = new MyAPIConnector();
const config = {
apiConnector: connector,
searchQuery: { ... },
autocompleteQuery: { ... }
};
const App = () => (
<SearchProvider config={config}>
<div className="App">
<SearchBox />
</div>
</SearchProvider>
);