- Notifications
You must be signed in to change notification settings - Fork21
Elastic App Search Official JavaScript Client
License
elastic/app-search-javascript
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A first-party JavaScript client for building excellent, relevant search experiences withElastic App Search.
The easiest way to install this client is to simply include the built distribution from thejsDelivr CDN.
<scriptsrc="https://cdn.jsdelivr.net/npm/@elastic/app-search-javascript@8.13.0/dist/elastic_app_search.umd.js"></script>
This will make the client available globally at:
window.ElasticAppSearch;
This package can also be installed withnpm
oryarn
.
npm install --save @elastic/app-search-javascript
The client could then be included into your project like follows:
// CommonJSvarElasticAppSearch=require("@elastic/app-search-javascript");// ESimport*asElasticAppSearchfrom"@elastic/app-search-javascript";
This client is versioned and released alongside App Search.
To guarantee compatibility, use the most recent version of this library within the major version of the corresponding App Search implementation.
For example, for App Search7.3
, use7.3
of this library or above, but not8.0
.
If you are using theSaaS version available on swiftype.com of App Search, you should use the version 7.5.x of the client.
The client is compatible with all modern browsers.
Note that this library depends on theFetch API.
This is not supported by Internet Explorer. If you need backwards compatibilityfor Internet Explorer, you'll need to polyfill the Fetch API with somethinglikehttps://github.com/github/fetch.
Using this client assumes that you have already an instance ofElastic App Search up and running.
The client is configured using thesearchKey
,endpointBase
, andengineName
parameters.
varclient=ElasticAppSearch.createClient({searchKey:"search-mu75psc5egt9ppzuycnc2mc3",endpointBase:"http://127.0.0.1:3002",engineName:"favorite-videos"});
* Please note that you should only ever use aPublic Search Key within Javascript code on the browser. By default, your account should have a Key prefixed withsearch-
that is read-only. More information can be found in thedocumentation.
When using theSaaS version available on swiftype.com of App Search, you can configure the client using yourhostIdentifier
instead of theendpointBase
parameter.ThehostIdentifier
can be found within theCredentials menu.
varclient=ElasticAppSearch.createClient({hostIdentifier:"host-c5s2mj",searchKey:"search-mu75psc5egt9ppzuycnc2mc3",engineName:"favorite-videos"});
Option | Required | Description |
---|---|---|
hostIdentifier | No | YourHost Identifier, should start withhost- . Required unless explicitly settingendpointBase |
searchKey | No | YourPublic Search Key. It should start withsearch- .NOTE: This is nottechnically required, but in 99% of cases it should be provided. There is a small edge case for not providing this, mainly useful for internal App Search usage, where this can be ommited in order to leverage App Search's session based authentication. |
engineName | Yes | |
endpointBase | No | Overrides the base of the App Search API endpoint completely. Useful when proxying the App Search API, developing against a local server, or a Self-Managed or Cloud Deployment. Ex. "http://localhost:3002" |
cacheResponses | No | Whether or not API responses should be cached. Default:true . |
additionalHeaders | No | An Object with keys and values that will be converted to header names and values on all API requests |
This client is a thin interface to the Elastic App Search API. Additional details for requests and responses can befound in thedocumentation.
For the query termlion
, a search call is constructed as follows:
varoptions={search_fields:{title:{}},result_fields:{id:{raw:{}},title:{raw:{}}}};client.search("lion",options).then(resultList=>{resultList.results.forEach(result=>{console.log(`id:${result.getRaw("id")} raw:${result.getRaw("title")}`);});}).catch(error=>{console.log(`error:${error}`);});
Note thatoptions
supports all options listed here:https://swiftype.com/documentation/app-search/guides/search.
In addition to the supported options above, we also support the following fields:
Name | Type | Description |
---|---|---|
disjunctiveFacets | Array[String] | An array of field names. Every field listed here must also be provided as a facet in thefacet field. It denotes that a facet should be considered disjunctive. When returning counts for disjunctive facets, the counts will be returned as if no filter is applied on this field, even if one is applied. |
disjunctiveFacetsAnalyticsTags | Array[String] | Used in conjunction with thedisjunctiveFacets parameter. Queries will be tagged with "Facet-Only" in the Analytics Dashboard unless specified here. |
Response
The search method returns the response wrapped in aResultList
type:
ResultList{rawResults:[],// List of raw `results` from JSON responserawInfo:{// Object wrapping the raw `meta` property from JSON responsemeta:{}},results:[ResultItem],// List of `results` wrapped in `ResultItem` typeinfo:{// Currently the same as `rawInfo`meta:{}}}ResultItem{getRaw(fieldName),// Returns the HTML-unsafe raw value for a field, if it existsgetSnippet(fieldName)// Returns the HTML-safe snippet value for a field, if it exists}
varoptions={size:3,types:{documents:{fields:["name"]}}};client.querySuggestion("cat",options).then(response=>{response.results.documents.forEach(document=>{console.log(document.suggestion);});}).catch(error=>{console.log(`error:${error}`);});
It is possible to run multiple queries at once using themultiSearch
method.
To search for the termlion
andtiger
, a search call is constructed as follows:
varoptions={search_fields:{name:{}},result_fields:{id:{raw:{}},title:{raw:{}}}};client.multiSearch([{query:"node", options},{query:"java", options}]).then(allResults=>{allResults.forEach(resultList=>{resultList.results.forEach(result=>{console.log(`id:${result.getRaw("id")} raw:${result.getRaw("title")}`);});});}).catch(error=>{console.log(`error:${error}`);});
client.click({query:"lion",documentId:"1234567",requestId:"8b55561954484f13d872728f849ffd22",tags:["Animal"]}).catch(error=>{console.log(`error:${error}`);});
Clickthroughs can be tracked by bindingclient.click
calls to click events on individual search result links.
The following example shows how this can be implemented declaratively by annotating links with class and data attributes.
document.addEventListener("click",function(e){constel=e.target;if(!el.classList.contains("track-click"))return;client.click({query:el.getAttribute("data-query"),documentId:el.getAttribute("data-document-id"),requestId:el.getAttribute("data-request-id"),tags:[el.getAttribute("data-tag")]});});
<ahref="/items/1234567"class="track-click"data-request-id="8b55561954484f13d872728f849ffd22"data-document-id="1234567"data-query="lion"data-tag="Animal"> Item 1</a>
The specs in this project usenode-replay to capture responses.
The responses are then checked against Jest snapshots.
To capture new responses and update snapshots, run:
nvm useREPLAY=record npm run test -u
To run tests:
nvm usenpm run test
You will probably want to install a node version manager, like nvm.
We depend upon the version of node defined in.nvmrc.
To install and use the correct node version with nvm:
nvm install
Install dependencies:
nvm usenpm install
Build artifacts indist
directory:
# This will create files in the `dist` directorynpm run build
Add anindex.html
file to yourdist
directory
<html><head><scriptsrc="elastic_app_search.umd.js"></script></head><body></body></html>
Run dev server:
# This will serve files in the `dist` directorynpm run dev
Navigate tohttp://127.0.0.1:8080 and execute JavaScript commands through the browser Dev Console.
nvm usenpm run build
nvm usenpm run publish
App Search has a first-partyNode.js client which supports write operations like indexing.
If something is not working as expected, please open anissue.
Your best bet is to read thedocumentation.
You can checkout theElastic App Search community discuss forums.
We welcome contributors to the project. Before you begin, a couple notes...
- Prior to opening a pull request, please create an issue todiscuss the scope of your proposal.
- Please write simple code and concise documentation, when appropriate.
Thank you to all thecontributors!
About
Elastic App Search Official JavaScript Client