Repository files navigation

AddSearch Search API Client for JavaScript

AddSearch is a Search-as-a-Service for all your search needs. This API Client lets you easily use the Search API and Indexing API with JavaScript.

Quick Start

The library is available on the global CDN jsDelivr:

<scriptsrc="https://cdn.jsdelivr.net/npm/addsearch-js-client@0.6/dist/addsearch-js-client.min.js"></script>

Or install the library locally to use it with Node.js:

npm install addsearch-js-client --save

After installation, add the library to your JS code

varAddSearchClient=require('addsearch-js-client');

Or use import in ES6

importAddSearchClientfrom'addsearch-js-client';

Execute the first search query

// Create client with your 32-character SITEKEYvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY');// Callback functionvarcb=function(res){// Print results to consoleconsole.log(res);};// Execute search. Callback function will be called with search resultsclient.search('keyword',cb);

Search API

The client provides following functions to execute search queries. To use the client library for indexing, see Indexing API.

Fetch search results

// Search with a specific keywordclient.search('keyword',callback);// Search with the previously used keyword or execute a "match all" queryclient.search(callback);// Search with the previously used keyword and callback (e.g. after modifying filters)client.search();

Fetch search suggestions

Search suggestions are keywords and search phrases that real users have used in your search. Configure Search suggestions on AddSearch Dashboard before using this function.

// Get suggestions starting with a specific prefixclient.suggestions('a',callback);

Set the number of search suggestions to fetch

// Number of search suggestions to fetch (default 10)client.setSuggestionsSize(20);

Custom field autocompletion

Custom fields autocomplete can be used for predictive search. For example, product names or categories can be suggested as the keyword is being typed in.

// Fetch custom field values starting with a specific prefix In this example, fetch records// starting with *a* from the *custom_fields.brand* field. Results could be "adidas, apple, azure"client.autocomplete('custom_fields.brand','a',callback);

Set the number of custom field autocompletion results to fetch

// Number of autocompletion results to fetch (default 10)client.setAutocompleteSize(20);

Search with fuzzy matching

Fuzzy matching is used for typo tolerance. There are four options:

  • false: No typo tolerance
  • true: Exact matches and fuzzy matches are equal
  • "auto": Exact matches first, followed by fuzzy matches
  • "retry": Show exact matches only. If none were found, show fuzzy matches
// Control fuzzy matching used for typo-tolerance// Possible values true/false/"auto"/"retry" (default: "auto")client.setFuzzyMatch(false);

Search operator

When a user searches with multiple keywords, we return only documents that contain all the terms which means applying the logical operator AND for the query. It is possible to choose which logical operator to use for fuzzy results when the fuzzy parameter is set to auto. There are two options:

  • "or": makes fuzzy results broader and includes partial matches of a few search terms
  • "and": makes fuzzy results stricter and includes only mistyped search terms
// Possible values "and"/"or" (default: "or")client.setSearchOperator('and');

Postfix wildcard

Enable or disable postfix wildcard. I.e. should keyword "add" match to "addsearch" or should it just match to the term add

// Possible values true/false (default: true)client.setPostfixWildcard(false);

Set enableLogicalOperators

// (default: false)// enableLogicalOperators(true) = Support user specified logical operators (and/or/not) in the search query like "cat and dog"// enableLogicalOperators(false) = Treat logical operators in the search query as literal stringsclient.enableLogicalOperators(true);

Set cacheResponseTime

Caching the response, define the time-to-live of the cache.

// Specify time-to-live value in secondsclient.setCacheResponseTime(3600);

Please contact our Support team to active Response Caching for your index.

Pagination

Set page number, page size and sorting parameters. It's possible to order results by:

  • relevance (descending)
  • date (ascending or descending)
  • custom field value (ascending or descending. E.g. custom_fields.price)

Type of sortBy and sortOrder: string or array. They must have the same type, in case type is array, sortBy and sortOrder must have the same size. For example:

sortBy='date';sortOrder='desc';or;sortBy=['date','custom_fields.price'];sortOrder=['desc','asc'];
// Defaults: page: 1, pageSize: 10, sortBy: "relevance", sortOrder: "desc"client.setPaging(page,pageSize,sortBy,sortOrder);

Other functions.

// Next page (call search function to fetch results)client.nextPage();// Previous pageclient.previousPage();

Filters

Define language filter

// Fetch documents in specific language (e.g. "en" or "de" or "en-GB")client.setLanguage('en');

Define publishing date filter

// Documents published between specific date rangeclient.setDateFilter('2019-01-01','2019-01-31');

Define price range filter

// Products in specific price range (in cents. e.g. 100,00 - 200,00)client.setPriceRangeFilter('10000','20000');

Define category filters

Filter by URL patterns, document types or addsearch-category meta tag values. See the full documentation.

// Only PDF files or productsclient.setCategoryFilters('doctype_pdf,products');

Custom field filters

Filter by custom fields. Custon fields can be defined in meta tags or AddSearch crawler can pick them up from your HTML or JSON data. See the full documentation.

// Search by specific city (Berlin, Paris or Boston)client.addCustomFieldFilter('city','berlin');client.addCustomFieldFilter('city','paris');client.addCustomFieldFilter('city','boston');// Remove Paris (Berlin and Boston remaining)client.removeCustomFieldFilter('city','paris');// Remove all citiesclient.removeCustomFieldFilter('city');

Set filtering object

Set complex filtering object that can contain nested and, or, not, and range filters.

// Find results where brand is apple, color is not white, and price is between 200 and 500varfilter={and: [{'custom_fields.brand': 'apple'},{not: {'custom_fields.color': 'white'}},{range: {'custom_fields.price': {gt: 200,lt: 500}}}]};client.setFilterObject(filter);

Set result type

// By default, fetch all search results// If "organic", Pinned results and Promotions are left outclient.setResultType('organic');

Facets

// Declare fields for faceting. Number of hits found from// these fields will be returnedclient.addFacetField('category');client.addFacetField('custom_fields.genre');

Facet values are returned in alphabetical order, 10 values per field by default. Use the following function to get more or less facets.

client.setNumberOfFacets(20);

Note: if a field has more values than the defined limit, the returned values are the first N in alphabetical order, not the N with most hits. Increase the limit if you need more values.

Numerical range facets

Group numerical custom fields into range buckets.

// Define ranges. E.g. products with price $0-$100, $100-$200, and over $200.// From value is inclusive, to value is exclusivevarranges=[{to: 100},{from: 100,to: 200},{from: 200}];// Parameters: field name, range arrayclient.addRangeFacet('custom_fields.price',ranges);

Field statistics

Get minimum, maximum, and average values of a numerical or date-based custom field. The information is handy for applications like range filtering.

// Search response will have a fieldStats element with information like// custom_fields.price: {min: 1230, max: 1590, avg: 1382}client.addStatsField('custom_fields.price');

Recommendations

Frequently bought together items

Get frequently bought together items, given "configurationKey" and "itemId"

// fetch frequently bought together itemsclient.recommendations({configurationKey: 'config1',itemId: '1065921'});

Search analytics

Send search event to analytics

When search is executed, send the event to your AddSearch Analytics Dashboard.

// If the numberOfResults is 0, the search is shown in the list of "queries with no hits"client.sendStatsEvent('search',keyword,{numberOfResults: n});

Send click event to analytics

When a search results is clicked, send the event to your AddSearch Analytics Dashboard. Click information is shown in your statistics and used by the self-learning search algorithm.

// documentId is the 32-character long id that is part of each hit in search results.// position is the position of the document that was clicked, the first result being 1client.sendStatsEvent('click',keyword,{documentId: id,position: n});

Set or get stats session ID

Control the search session ID manually. Search queries with the same ID are grouped on the Analytics Dashboard. For example, in a search-as-you-type implementation the final keyword of a given session is shown.

client.getStatsSessionId();client.setStatsSessionId(id);

Collect search events automatically

Send search events automatically to the Analytics Dashboard. Not recommended in search-as-you-type implementations, as every keystroke would fire a statistics event

// Control whether search queries are sent to your AddSearch Analytics Dashboard automatically or not (default: true)client.setCollectAnalytics(false);

Set a tag for analytics events

Defines a tag associated with all analytics events reported by the client. These tags will be available as filters in the AddSearch Analytics Dashboard. You can use tags, for instance, in A/B testing to compare which search UIs are most effective. Splitting the analytics with tags may also provide insights to the behaviour of audiences on different websites.

// Specify a tag for analytics events (the maximum length is 50 characters)client.setAnalyticsTag('Navigation search');

Personalization

Enable personalization tracking

Enable personalization tracking, user token will be included in every stat events as "session ID".

Set stats session ID if user token is generated by your site.

client.setStatsSessionId(userToken);

If session is not set, a UUID is generated and stored in a cookie named 'addsearchUserToken`. Specify the expiration date of the cookie. Default is 180.

// Defaults - isEnabled: false, expirationDates: 180client.enablePersonalizationTracking(isEnabled,expirationDates);

Allow storing AddSearch's user token in cookie

By default, the value is false. Set it to false when users reject cookie (AddSearch's cookie can be categorized as functional/analytics cookie), or set to true when user accepts cookie.

// Default: falseclient.consentAddSearchCookie(true);

Set user token to search query (for personalized search results)

// Add a user token to the search request (if personalization in use)client.setUserToken(userToken);

Get user token from AddSearch cookie

Get the user token which is stored in AddSearch cookie (if available).

// Get a user tokenclient.getUserTokenInPersonalization();

Send personalization events with search query - deprecated

In personalized search, user events are typically sent to AddSearch via API and a user token is passed with the search query (see setUserToken function). An alternative way is to send user events needed for personalization with the search query.

// Events depend on the personalization strategy// Contact AddSearch for more informationvarevents=[{favorite_genre: 'rock'},{favorite_band: 'Red Hot Chili Peppers'},{least_favorite_genre: 'country'}];client.setPersonalizationEvents(events);

Other

Set JSON Web Token (for authentication)

// Add JWT to the search request (if protected search index)client.setJWT(token);

Set API throttling

// Set Search API throttle time in milliseconds. Default is 200.client.setThrottleTime(500);

Set API hostname

option is an object with the following properties, all of which are optional. If option is not defined, host name will be applied for all requests.

  • searchApiRequestOnly: If true, the new host name is only applied for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the new host name is only applied for statsApi requests (default: false)
// Set API hostname (e.g. for dedicated environments)client.setApiHostname('api.addsearch.com',option);

Set API request interceptor

configurationObject contains 2 keys: url and headers. Modify the configurationObject before it is sent.

option is an object with the following properties, all of which are optional. If option is not defined, the interceptor will be used for all requests.

  • searchApiRequestOnly: If true, the interceptor is only used for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the interceptor is only used for statsApi requests (default: false)
functioncallback(configurationObject){configurationObject.headers['X-Api-Key']='YOUR API KEY';returnconfigurationObject;}client.setApiRequestInterceptor(callback,option);

AI Answers API

Fetch AI answers

// Get AI generated answer with a questionclient.aiAnswers('A question to get AI generated answers',callback);

Example of callback function and how the response looks like:

callbackFn=function(response){console.log(response);// response object contains the answer// {// "answer": "The answer to the question",// "conversation_id": "31f33b53-1fe1-4734-884f-fefa470f1389",// "ids": <array of ids belonging to source documents>, for example ['073010f023db7c6d558123f73a9b4f82', '821f7bea12daf0eda17ba2755979f7a5'],// "source_documents": <documents that provide context for AI generated answers, the object of this field looks similarly to the response of regular SearchApi result>// }};

Send Sentiment Analysis

// possible sentiment_value: positive, negativeclient.putSentimentClick('conversation_id','sentiment_value');

Set AI-answers filtering object

Set complex filtering object that can contain nested and, or, not. Key filterable properties include: category, custom_fields.<your_field_name>, language, doc_date

// Find results where region is en-us, color is not whitevaraiAnswersFilter={and: [{'custom_fields.region': 'en-us'},{not: {'custom_fields.color': 'white'}}]};client.setAiAnswersFilterObject(aiAnswersFilter);

POST API

❗ POST API is not fully supported. If you need to use some methods in the library, please contact our support.

Fetch AI answers

// default method: "GET"client.setApiMethod('POST');

Indexing API

With the Indexing API, you can fetch, create, update, and delete single documents or batches of documents.

Indexing API functions are meant to be used with Node.js. Never expose secret key in your website code.

// Create client with your keysvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY','YOUR SECRET KEY');

The secret key can be found from AddSearch Dashboard's "Setup" > "Keys and installation" page. Always keep the key secret.

All Indexing API functions are Promise-based.

Document structure

Documents can contain a set of pre-defined fields, as well as any number of custom fields defined under the custom_fields key.

Using pre-defined fields is optional, but default Search UI components display them by default, so pre-defined field give you visible results a bit faster.

Pre-defined fields are: url, title, and main_content.

Example document:

constdoc={id: '1234',url: 'https://www.example-store.com/product-x',title: 'Example product',main_content: 'Lorem ipsum',custom_fields: {name: 'Example product',description: 'Description for the example product',price_cents: 599,average_customer_rating: 4.5,release_date: 1589200255}};

Data types for custom fields are automatically detected from the content. Supported data types are:

  • text
  • integer
  • double

Dates should be defined as UNIX timestamps with integer values.

Document ID

If the id is not defined in the document at indexing time, it is generated automatically either randomly or from the url field.

// ID defined by the userconstdocWithDefinedId={id: '1234',custom_fields: {}};
// ID created from the URL field (md5 of the url)constdocWithURL={url: 'https://..',custom_fields: {}};
// ID generated randomlyconstdocWithAutogeneratedId={// No id or url fieldscustom_fields: {}};

Save document

Add a document to the index, or update a document.

constdoc={id: '1234',custom_fields: {name: 'Example product'}};// Save documentclient.saveDocument(doc).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Get document by ID

Fetch a specific document by ID.

client.getDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete document by ID

Delete a specific document by ID.

client.deleteDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Save batch of documents

Add or update bunch of documents defined in an array.

constbatch={documents: [{id: '1234',custom_fields: {name: 'Product 1'}},{id: '5678',custom_fields: {name: 'Product 2'}}]};// Save batch of documentsclient.saveDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete batch of documents

Delete multiple documents with an array of document IDs.

// Array of document IDsconstbatch={documents: ['1234','5678']};// Delete batch of documentsclient.deleteDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Supported browsers

The client is tested on

  • Chrome
  • Firefox
  • Edge
  • Safari 6.1+
  • Internet Explorer 10+
  • Node.js

Development

To modify this client library, clone this repository to your computer and execute following commands.

Install dependencies

npm install

Code

Re-compile automatically when source files are changed

npm run watch

Run tests

npm test

Build

npm run build

Built bundle is saved under the dist/ folder

Support

Feel free to send any questions, ideas, and suggestions at support@addsearch.com or visit addsearch.com for more information.

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

AddSearch Search API Client for JavaScript

AddSearch is a Search-as-a-Service for all your search needs. This API Client lets you easily use the Search API and Indexing API with JavaScript.

Quick Start

The library is available on the global CDN jsDelivr:

<scriptsrc="https://cdn.jsdelivr.net/npm/addsearch-js-client@0.6/dist/addsearch-js-client.min.js"></script>

Or install the library locally to use it with Node.js:

npm install addsearch-js-client --save

After installation, add the library to your JS code

varAddSearchClient=require('addsearch-js-client');

Or use import in ES6

importAddSearchClientfrom'addsearch-js-client';

Execute the first search query

// Create client with your 32-character SITEKEYvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY');// Callback functionvarcb=function(res){// Print results to consoleconsole.log(res);};// Execute search. Callback function will be called with search resultsclient.search('keyword',cb);

Search API

The client provides following functions to execute search queries. To use the client library for indexing, see Indexing API.

Fetch search results

// Search with a specific keywordclient.search('keyword',callback);// Search with the previously used keyword or execute a "match all" queryclient.search(callback);// Search with the previously used keyword and callback (e.g. after modifying filters)client.search();

Fetch search suggestions

Search suggestions are keywords and search phrases that real users have used in your search. Configure Search suggestions on AddSearch Dashboard before using this function.

// Get suggestions starting with a specific prefixclient.suggestions('a',callback);

Set the number of search suggestions to fetch

// Number of search suggestions to fetch (default 10)client.setSuggestionsSize(20);

Custom field autocompletion

Custom fields autocomplete can be used for predictive search. For example, product names or categories can be suggested as the keyword is being typed in.

// Fetch custom field values starting with a specific prefix In this example, fetch records// starting with *a* from the *custom_fields.brand* field. Results could be "adidas, apple, azure"client.autocomplete('custom_fields.brand','a',callback);

Set the number of custom field autocompletion results to fetch

// Number of autocompletion results to fetch (default 10)client.setAutocompleteSize(20);

Search with fuzzy matching

Fuzzy matching is used for typo tolerance. There are four options:

  • false: No typo tolerance
  • true: Exact matches and fuzzy matches are equal
  • "auto": Exact matches first, followed by fuzzy matches
  • "retry": Show exact matches only. If none were found, show fuzzy matches
// Control fuzzy matching used for typo-tolerance// Possible values true/false/"auto"/"retry" (default: "auto")client.setFuzzyMatch(false);

Search operator

When a user searches with multiple keywords, we return only documents that contain all the terms which means applying the logical operator AND for the query. It is possible to choose which logical operator to use for fuzzy results when the fuzzy parameter is set to auto. There are two options:

  • "or": makes fuzzy results broader and includes partial matches of a few search terms
  • "and": makes fuzzy results stricter and includes only mistyped search terms
// Possible values "and"/"or" (default: "or")client.setSearchOperator('and');

Postfix wildcard

Enable or disable postfix wildcard. I.e. should keyword "add" match to "addsearch" or should it just match to the term add

// Possible values true/false (default: true)client.setPostfixWildcard(false);

Set enableLogicalOperators

// (default: false)// enableLogicalOperators(true) = Support user specified logical operators (and/or/not) in the search query like "cat and dog"// enableLogicalOperators(false) = Treat logical operators in the search query as literal stringsclient.enableLogicalOperators(true);

Set cacheResponseTime

Caching the response, define the time-to-live of the cache.

// Specify time-to-live value in secondsclient.setCacheResponseTime(3600);

Please contact our Support team to active Response Caching for your index.

Pagination

Set page number, page size and sorting parameters. It's possible to order results by:

  • relevance (descending)
  • date (ascending or descending)
  • custom field value (ascending or descending. E.g. custom_fields.price)

Type of sortBy and sortOrder: string or array. They must have the same type, in case type is array, sortBy and sortOrder must have the same size. For example:

sortBy='date';sortOrder='desc';or;sortBy=['date','custom_fields.price'];sortOrder=['desc','asc'];
// Defaults: page: 1, pageSize: 10, sortBy: "relevance", sortOrder: "desc"client.setPaging(page,pageSize,sortBy,sortOrder);

Other functions.

// Next page (call search function to fetch results)client.nextPage();// Previous pageclient.previousPage();

Filters

Define language filter

// Fetch documents in specific language (e.g. "en" or "de" or "en-GB")client.setLanguage('en');

Define publishing date filter

// Documents published between specific date rangeclient.setDateFilter('2019-01-01','2019-01-31');

Define price range filter

// Products in specific price range (in cents. e.g. 100,00 - 200,00)client.setPriceRangeFilter('10000','20000');

Define category filters

Filter by URL patterns, document types or addsearch-category meta tag values. See the full documentation.

// Only PDF files or productsclient.setCategoryFilters('doctype_pdf,products');

Custom field filters

Filter by custom fields. Custon fields can be defined in meta tags or AddSearch crawler can pick them up from your HTML or JSON data. See the full documentation.

// Search by specific city (Berlin, Paris or Boston)client.addCustomFieldFilter('city','berlin');client.addCustomFieldFilter('city','paris');client.addCustomFieldFilter('city','boston');// Remove Paris (Berlin and Boston remaining)client.removeCustomFieldFilter('city','paris');// Remove all citiesclient.removeCustomFieldFilter('city');

Set filtering object

Set complex filtering object that can contain nested and, or, not, and range filters.

// Find results where brand is apple, color is not white, and price is between 200 and 500varfilter={and: [{'custom_fields.brand': 'apple'},{not: {'custom_fields.color': 'white'}},{range: {'custom_fields.price': {gt: 200,lt: 500}}}]};client.setFilterObject(filter);

Set result type

// By default, fetch all search results// If "organic", Pinned results and Promotions are left outclient.setResultType('organic');

Facets

// Declare fields for faceting. Number of hits found from// these fields will be returnedclient.addFacetField('category');client.addFacetField('custom_fields.genre');

Facet values are returned in alphabetical order, 10 values per field by default. Use the following function to get more or less facets.

client.setNumberOfFacets(20);

Note: if a field has more values than the defined limit, the returned values are the first N in alphabetical order, not the N with most hits. Increase the limit if you need more values.

Numerical range facets

Group numerical custom fields into range buckets.

// Define ranges. E.g. products with price $0-$100, $100-$200, and over $200.// From value is inclusive, to value is exclusivevarranges=[{to: 100},{from: 100,to: 200},{from: 200}];// Parameters: field name, range arrayclient.addRangeFacet('custom_fields.price',ranges);

Field statistics

Get minimum, maximum, and average values of a numerical or date-based custom field. The information is handy for applications like range filtering.

// Search response will have a fieldStats element with information like// custom_fields.price: {min: 1230, max: 1590, avg: 1382}client.addStatsField('custom_fields.price');

Recommendations

Frequently bought together items

Get frequently bought together items, given "configurationKey" and "itemId"

// fetch frequently bought together itemsclient.recommendations({configurationKey: 'config1',itemId: '1065921'});

Search analytics

Send search event to analytics

When search is executed, send the event to your AddSearch Analytics Dashboard.

// If the numberOfResults is 0, the search is shown in the list of "queries with no hits"client.sendStatsEvent('search',keyword,{numberOfResults: n});

Send click event to analytics

When a search results is clicked, send the event to your AddSearch Analytics Dashboard. Click information is shown in your statistics and used by the self-learning search algorithm.

// documentId is the 32-character long id that is part of each hit in search results.// position is the position of the document that was clicked, the first result being 1client.sendStatsEvent('click',keyword,{documentId: id,position: n});

Set or get stats session ID

Control the search session ID manually. Search queries with the same ID are grouped on the Analytics Dashboard. For example, in a search-as-you-type implementation the final keyword of a given session is shown.

client.getStatsSessionId();client.setStatsSessionId(id);

Collect search events automatically

Send search events automatically to the Analytics Dashboard. Not recommended in search-as-you-type implementations, as every keystroke would fire a statistics event

// Control whether search queries are sent to your AddSearch Analytics Dashboard automatically or not (default: true)client.setCollectAnalytics(false);

Set a tag for analytics events

Defines a tag associated with all analytics events reported by the client. These tags will be available as filters in the AddSearch Analytics Dashboard. You can use tags, for instance, in A/B testing to compare which search UIs are most effective. Splitting the analytics with tags may also provide insights to the behaviour of audiences on different websites.

// Specify a tag for analytics events (the maximum length is 50 characters)client.setAnalyticsTag('Navigation search');

Personalization

Enable personalization tracking

Enable personalization tracking, user token will be included in every stat events as "session ID".

Set stats session ID if user token is generated by your site.

client.setStatsSessionId(userToken);

If session is not set, a UUID is generated and stored in a cookie named 'addsearchUserToken`. Specify the expiration date of the cookie. Default is 180.

// Defaults - isEnabled: false, expirationDates: 180client.enablePersonalizationTracking(isEnabled,expirationDates);

Allow storing AddSearch's user token in cookie

By default, the value is false. Set it to false when users reject cookie (AddSearch's cookie can be categorized as functional/analytics cookie), or set to true when user accepts cookie.

// Default: falseclient.consentAddSearchCookie(true);

Set user token to search query (for personalized search results)

// Add a user token to the search request (if personalization in use)client.setUserToken(userToken);

Get user token from AddSearch cookie

Get the user token which is stored in AddSearch cookie (if available).

// Get a user tokenclient.getUserTokenInPersonalization();

Send personalization events with search query - deprecated

In personalized search, user events are typically sent to AddSearch via API and a user token is passed with the search query (see setUserToken function). An alternative way is to send user events needed for personalization with the search query.

// Events depend on the personalization strategy// Contact AddSearch for more informationvarevents=[{favorite_genre: 'rock'},{favorite_band: 'Red Hot Chili Peppers'},{least_favorite_genre: 'country'}];client.setPersonalizationEvents(events);

Other

Set JSON Web Token (for authentication)

// Add JWT to the search request (if protected search index)client.setJWT(token);

Set API throttling

// Set Search API throttle time in milliseconds. Default is 200.client.setThrottleTime(500);

Set API hostname

option is an object with the following properties, all of which are optional. If option is not defined, host name will be applied for all requests.

  • searchApiRequestOnly: If true, the new host name is only applied for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the new host name is only applied for statsApi requests (default: false)
// Set API hostname (e.g. for dedicated environments)client.setApiHostname('api.addsearch.com',option);

Set API request interceptor

configurationObject contains 2 keys: url and headers. Modify the configurationObject before it is sent.

option is an object with the following properties, all of which are optional. If option is not defined, the interceptor will be used for all requests.

  • searchApiRequestOnly: If true, the interceptor is only used for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the interceptor is only used for statsApi requests (default: false)
functioncallback(configurationObject){configurationObject.headers['X-Api-Key']='YOUR API KEY';returnconfigurationObject;}client.setApiRequestInterceptor(callback,option);

AI Answers API

Fetch AI answers

// Get AI generated answer with a questionclient.aiAnswers('A question to get AI generated answers',callback);

Example of callback function and how the response looks like:

callbackFn=function(response){console.log(response);// response object contains the answer// {// "answer": "The answer to the question",// "conversation_id": "31f33b53-1fe1-4734-884f-fefa470f1389",// "ids": <array of ids belonging to source documents>, for example ['073010f023db7c6d558123f73a9b4f82', '821f7bea12daf0eda17ba2755979f7a5'],// "source_documents": <documents that provide context for AI generated answers, the object of this field looks similarly to the response of regular SearchApi result>// }};

Send Sentiment Analysis

// possible sentiment_value: positive, negativeclient.putSentimentClick('conversation_id','sentiment_value');

Set AI-answers filtering object

Set complex filtering object that can contain nested and, or, not. Key filterable properties include: category, custom_fields.<your_field_name>, language, doc_date

// Find results where region is en-us, color is not whitevaraiAnswersFilter={and: [{'custom_fields.region': 'en-us'},{not: {'custom_fields.color': 'white'}}]};client.setAiAnswersFilterObject(aiAnswersFilter);

POST API

❗ POST API is not fully supported. If you need to use some methods in the library, please contact our support.

Fetch AI answers

// default method: "GET"client.setApiMethod('POST');

Indexing API

With the Indexing API, you can fetch, create, update, and delete single documents or batches of documents.

Indexing API functions are meant to be used with Node.js. Never expose secret key in your website code.

// Create client with your keysvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY','YOUR SECRET KEY');

The secret key can be found from AddSearch Dashboard's "Setup" > "Keys and installation" page. Always keep the key secret.

All Indexing API functions are Promise-based.

Document structure

Documents can contain a set of pre-defined fields, as well as any number of custom fields defined under the custom_fields key.

Using pre-defined fields is optional, but default Search UI components display them by default, so pre-defined field give you visible results a bit faster.

Pre-defined fields are: url, title, and main_content.

Example document:

constdoc={id: '1234',url: 'https://www.example-store.com/product-x',title: 'Example product',main_content: 'Lorem ipsum',custom_fields: {name: 'Example product',description: 'Description for the example product',price_cents: 599,average_customer_rating: 4.5,release_date: 1589200255}};

Data types for custom fields are automatically detected from the content. Supported data types are:

  • text
  • integer
  • double

Dates should be defined as UNIX timestamps with integer values.

Document ID

If the id is not defined in the document at indexing time, it is generated automatically either randomly or from the url field.

// ID defined by the userconstdocWithDefinedId={id: '1234',custom_fields: {}};
// ID created from the URL field (md5 of the url)constdocWithURL={url: 'https://..',custom_fields: {}};
// ID generated randomlyconstdocWithAutogeneratedId={// No id or url fieldscustom_fields: {}};

Save document

Add a document to the index, or update a document.

constdoc={id: '1234',custom_fields: {name: 'Example product'}};// Save documentclient.saveDocument(doc).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Get document by ID

Fetch a specific document by ID.

client.getDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete document by ID

Delete a specific document by ID.

client.deleteDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Save batch of documents

Add or update bunch of documents defined in an array.

constbatch={documents: [{id: '1234',custom_fields: {name: 'Product 1'}},{id: '5678',custom_fields: {name: 'Product 2'}}]};// Save batch of documentsclient.saveDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete batch of documents

Delete multiple documents with an array of document IDs.

// Array of document IDsconstbatch={documents: ['1234','5678']};// Delete batch of documentsclient.deleteDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Supported browsers

The client is tested on

  • Chrome
  • Firefox
  • Edge
  • Safari 6.1+
  • Internet Explorer 10+
  • Node.js

Development

To modify this client library, clone this repository to your computer and execute following commands.

Install dependencies

npm install

Code

Re-compile automatically when source files are changed

npm run watch

Run tests

npm test

Build

npm run build

Built bundle is saved under the dist/ folder

Support

Feel free to send any questions, ideas, and suggestions at support@addsearch.com or visit addsearch.com for more information.

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

AddSearch Search API Client for JavaScript

AddSearch is a Search-as-a-Service for all your search needs. This API Client lets you easily use the Search API and Indexing API with JavaScript.

Quick Start

The library is available on the global CDN jsDelivr:

<scriptsrc="https://cdn.jsdelivr.net/npm/addsearch-js-client@0.6/dist/addsearch-js-client.min.js"></script>

Or install the library locally to use it with Node.js:

npm install addsearch-js-client --save

After installation, add the library to your JS code

varAddSearchClient=require('addsearch-js-client');

Or use import in ES6

importAddSearchClientfrom'addsearch-js-client';

Execute the first search query

// Create client with your 32-character SITEKEYvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY');// Callback functionvarcb=function(res){// Print results to consoleconsole.log(res);};// Execute search. Callback function will be called with search resultsclient.search('keyword',cb);

Search API

The client provides following functions to execute search queries. To use the client library for indexing, see Indexing API.

Fetch search results

// Search with a specific keywordclient.search('keyword',callback);// Search with the previously used keyword or execute a "match all" queryclient.search(callback);// Search with the previously used keyword and callback (e.g. after modifying filters)client.search();

Fetch search suggestions

Search suggestions are keywords and search phrases that real users have used in your search. Configure Search suggestions on AddSearch Dashboard before using this function.

// Get suggestions starting with a specific prefixclient.suggestions('a',callback);

Set the number of search suggestions to fetch

// Number of search suggestions to fetch (default 10)client.setSuggestionsSize(20);

Custom field autocompletion

Custom fields autocomplete can be used for predictive search. For example, product names or categories can be suggested as the keyword is being typed in.

// Fetch custom field values starting with a specific prefix In this example, fetch records// starting with *a* from the *custom_fields.brand* field. Results could be "adidas, apple, azure"client.autocomplete('custom_fields.brand','a',callback);

Set the number of custom field autocompletion results to fetch

// Number of autocompletion results to fetch (default 10)client.setAutocompleteSize(20);

Search with fuzzy matching

Fuzzy matching is used for typo tolerance. There are four options:

  • false: No typo tolerance
  • true: Exact matches and fuzzy matches are equal
  • "auto": Exact matches first, followed by fuzzy matches
  • "retry": Show exact matches only. If none were found, show fuzzy matches
// Control fuzzy matching used for typo-tolerance// Possible values true/false/"auto"/"retry" (default: "auto")client.setFuzzyMatch(false);

Search operator

When a user searches with multiple keywords, we return only documents that contain all the terms which means applying the logical operator AND for the query. It is possible to choose which logical operator to use for fuzzy results when the fuzzy parameter is set to auto. There are two options:

  • "or": makes fuzzy results broader and includes partial matches of a few search terms
  • "and": makes fuzzy results stricter and includes only mistyped search terms
// Possible values "and"/"or" (default: "or")client.setSearchOperator('and');

Postfix wildcard

Enable or disable postfix wildcard. I.e. should keyword "add" match to "addsearch" or should it just match to the term add

// Possible values true/false (default: true)client.setPostfixWildcard(false);

Set enableLogicalOperators

// (default: false)// enableLogicalOperators(true) = Support user specified logical operators (and/or/not) in the search query like "cat and dog"// enableLogicalOperators(false) = Treat logical operators in the search query as literal stringsclient.enableLogicalOperators(true);

Set cacheResponseTime

Caching the response, define the time-to-live of the cache.

// Specify time-to-live value in secondsclient.setCacheResponseTime(3600);

Please contact our Support team to active Response Caching for your index.

Pagination

Set page number, page size and sorting parameters. It's possible to order results by:

  • relevance (descending)
  • date (ascending or descending)
  • custom field value (ascending or descending. E.g. custom_fields.price)

Type of sortBy and sortOrder: string or array. They must have the same type, in case type is array, sortBy and sortOrder must have the same size. For example:

sortBy='date';sortOrder='desc';or;sortBy=['date','custom_fields.price'];sortOrder=['desc','asc'];
// Defaults: page: 1, pageSize: 10, sortBy: "relevance", sortOrder: "desc"client.setPaging(page,pageSize,sortBy,sortOrder);

Other functions.

// Next page (call search function to fetch results)client.nextPage();// Previous pageclient.previousPage();

Filters

Define language filter

// Fetch documents in specific language (e.g. "en" or "de" or "en-GB")client.setLanguage('en');

Define publishing date filter

// Documents published between specific date rangeclient.setDateFilter('2019-01-01','2019-01-31');

Define price range filter

// Products in specific price range (in cents. e.g. 100,00 - 200,00)client.setPriceRangeFilter('10000','20000');

Define category filters

Filter by URL patterns, document types or addsearch-category meta tag values. See the full documentation.

// Only PDF files or productsclient.setCategoryFilters('doctype_pdf,products');

Custom field filters

Filter by custom fields. Custon fields can be defined in meta tags or AddSearch crawler can pick them up from your HTML or JSON data. See the full documentation.

// Search by specific city (Berlin, Paris or Boston)client.addCustomFieldFilter('city','berlin');client.addCustomFieldFilter('city','paris');client.addCustomFieldFilter('city','boston');// Remove Paris (Berlin and Boston remaining)client.removeCustomFieldFilter('city','paris');// Remove all citiesclient.removeCustomFieldFilter('city');

Set filtering object

Set complex filtering object that can contain nested and, or, not, and range filters.

// Find results where brand is apple, color is not white, and price is between 200 and 500varfilter={and: [{'custom_fields.brand': 'apple'},{not: {'custom_fields.color': 'white'}},{range: {'custom_fields.price': {gt: 200,lt: 500}}}]};client.setFilterObject(filter);

Set result type

// By default, fetch all search results// If "organic", Pinned results and Promotions are left outclient.setResultType('organic');

Facets

// Declare fields for faceting. Number of hits found from// these fields will be returnedclient.addFacetField('category');client.addFacetField('custom_fields.genre');

Facet values are returned in alphabetical order, 10 values per field by default. Use the following function to get more or less facets.

client.setNumberOfFacets(20);

Note: if a field has more values than the defined limit, the returned values are the first N in alphabetical order, not the N with most hits. Increase the limit if you need more values.

Numerical range facets

Group numerical custom fields into range buckets.

// Define ranges. E.g. products with price $0-$100, $100-$200, and over $200.// From value is inclusive, to value is exclusivevarranges=[{to: 100},{from: 100,to: 200},{from: 200}];// Parameters: field name, range arrayclient.addRangeFacet('custom_fields.price',ranges);

Field statistics

Get minimum, maximum, and average values of a numerical or date-based custom field. The information is handy for applications like range filtering.

// Search response will have a fieldStats element with information like// custom_fields.price: {min: 1230, max: 1590, avg: 1382}client.addStatsField('custom_fields.price');

Recommendations

Frequently bought together items

Get frequently bought together items, given "configurationKey" and "itemId"

// fetch frequently bought together itemsclient.recommendations({configurationKey: 'config1',itemId: '1065921'});

Search analytics

Send search event to analytics

When search is executed, send the event to your AddSearch Analytics Dashboard.

// If the numberOfResults is 0, the search is shown in the list of "queries with no hits"client.sendStatsEvent('search',keyword,{numberOfResults: n});

Send click event to analytics

When a search results is clicked, send the event to your AddSearch Analytics Dashboard. Click information is shown in your statistics and used by the self-learning search algorithm.

// documentId is the 32-character long id that is part of each hit in search results.// position is the position of the document that was clicked, the first result being 1client.sendStatsEvent('click',keyword,{documentId: id,position: n});

Set or get stats session ID

Control the search session ID manually. Search queries with the same ID are grouped on the Analytics Dashboard. For example, in a search-as-you-type implementation the final keyword of a given session is shown.

client.getStatsSessionId();client.setStatsSessionId(id);

Collect search events automatically

Send search events automatically to the Analytics Dashboard. Not recommended in search-as-you-type implementations, as every keystroke would fire a statistics event

// Control whether search queries are sent to your AddSearch Analytics Dashboard automatically or not (default: true)client.setCollectAnalytics(false);

Set a tag for analytics events

Defines a tag associated with all analytics events reported by the client. These tags will be available as filters in the AddSearch Analytics Dashboard. You can use tags, for instance, in A/B testing to compare which search UIs are most effective. Splitting the analytics with tags may also provide insights to the behaviour of audiences on different websites.

// Specify a tag for analytics events (the maximum length is 50 characters)client.setAnalyticsTag('Navigation search');

Personalization

Enable personalization tracking

Enable personalization tracking, user token will be included in every stat events as "session ID".

Set stats session ID if user token is generated by your site.

client.setStatsSessionId(userToken);

If session is not set, a UUID is generated and stored in a cookie named 'addsearchUserToken`. Specify the expiration date of the cookie. Default is 180.

// Defaults - isEnabled: false, expirationDates: 180client.enablePersonalizationTracking(isEnabled,expirationDates);

Allow storing AddSearch's user token in cookie

By default, the value is false. Set it to false when users reject cookie (AddSearch's cookie can be categorized as functional/analytics cookie), or set to true when user accepts cookie.

// Default: falseclient.consentAddSearchCookie(true);

Set user token to search query (for personalized search results)

// Add a user token to the search request (if personalization in use)client.setUserToken(userToken);

Get user token from AddSearch cookie

Get the user token which is stored in AddSearch cookie (if available).

// Get a user tokenclient.getUserTokenInPersonalization();

Send personalization events with search query - deprecated

In personalized search, user events are typically sent to AddSearch via API and a user token is passed with the search query (see setUserToken function). An alternative way is to send user events needed for personalization with the search query.

// Events depend on the personalization strategy// Contact AddSearch for more informationvarevents=[{favorite_genre: 'rock'},{favorite_band: 'Red Hot Chili Peppers'},{least_favorite_genre: 'country'}];client.setPersonalizationEvents(events);

Other

Set JSON Web Token (for authentication)

// Add JWT to the search request (if protected search index)client.setJWT(token);

Set API throttling

// Set Search API throttle time in milliseconds. Default is 200.client.setThrottleTime(500);

Set API hostname

option is an object with the following properties, all of which are optional. If option is not defined, host name will be applied for all requests.

  • searchApiRequestOnly: If true, the new host name is only applied for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the new host name is only applied for statsApi requests (default: false)
// Set API hostname (e.g. for dedicated environments)client.setApiHostname('api.addsearch.com',option);

Set API request interceptor

configurationObject contains 2 keys: url and headers. Modify the configurationObject before it is sent.

option is an object with the following properties, all of which are optional. If option is not defined, the interceptor will be used for all requests.

  • searchApiRequestOnly: If true, the interceptor is only used for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the interceptor is only used for statsApi requests (default: false)
functioncallback(configurationObject){configurationObject.headers['X-Api-Key']='YOUR API KEY';returnconfigurationObject;}client.setApiRequestInterceptor(callback,option);

AI Answers API

Fetch AI answers

// Get AI generated answer with a questionclient.aiAnswers('A question to get AI generated answers',callback);

Example of callback function and how the response looks like:

callbackFn=function(response){console.log(response);// response object contains the answer// {// "answer": "The answer to the question",// "conversation_id": "31f33b53-1fe1-4734-884f-fefa470f1389",// "ids": <array of ids belonging to source documents>, for example ['073010f023db7c6d558123f73a9b4f82', '821f7bea12daf0eda17ba2755979f7a5'],// "source_documents": <documents that provide context for AI generated answers, the object of this field looks similarly to the response of regular SearchApi result>// }};

Send Sentiment Analysis

// possible sentiment_value: positive, negativeclient.putSentimentClick('conversation_id','sentiment_value');

Set AI-answers filtering object

Set complex filtering object that can contain nested and, or, not. Key filterable properties include: category, custom_fields.<your_field_name>, language, doc_date

// Find results where region is en-us, color is not whitevaraiAnswersFilter={and: [{'custom_fields.region': 'en-us'},{not: {'custom_fields.color': 'white'}}]};client.setAiAnswersFilterObject(aiAnswersFilter);

POST API

❗ POST API is not fully supported. If you need to use some methods in the library, please contact our support.

Fetch AI answers

// default method: "GET"client.setApiMethod('POST');

Indexing API

With the Indexing API, you can fetch, create, update, and delete single documents or batches of documents.

Indexing API functions are meant to be used with Node.js. Never expose secret key in your website code.

// Create client with your keysvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY','YOUR SECRET KEY');

The secret key can be found from AddSearch Dashboard's "Setup" > "Keys and installation" page. Always keep the key secret.

All Indexing API functions are Promise-based.

Document structure

Documents can contain a set of pre-defined fields, as well as any number of custom fields defined under the custom_fields key.

Using pre-defined fields is optional, but default Search UI components display them by default, so pre-defined field give you visible results a bit faster.

Pre-defined fields are: url, title, and main_content.

Example document:

constdoc={id: '1234',url: 'https://www.example-store.com/product-x',title: 'Example product',main_content: 'Lorem ipsum',custom_fields: {name: 'Example product',description: 'Description for the example product',price_cents: 599,average_customer_rating: 4.5,release_date: 1589200255}};

Data types for custom fields are automatically detected from the content. Supported data types are:

  • text
  • integer
  • double

Dates should be defined as UNIX timestamps with integer values.

Document ID

If the id is not defined in the document at indexing time, it is generated automatically either randomly or from the url field.

// ID defined by the userconstdocWithDefinedId={id: '1234',custom_fields: {}};
// ID created from the URL field (md5 of the url)constdocWithURL={url: 'https://..',custom_fields: {}};
// ID generated randomlyconstdocWithAutogeneratedId={// No id or url fieldscustom_fields: {}};

Save document

Add a document to the index, or update a document.

constdoc={id: '1234',custom_fields: {name: 'Example product'}};// Save documentclient.saveDocument(doc).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Get document by ID

Fetch a specific document by ID.

client.getDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete document by ID

Delete a specific document by ID.

client.deleteDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Save batch of documents

Add or update bunch of documents defined in an array.

constbatch={documents: [{id: '1234',custom_fields: {name: 'Product 1'}},{id: '5678',custom_fields: {name: 'Product 2'}}]};// Save batch of documentsclient.saveDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete batch of documents

Delete multiple documents with an array of document IDs.

// Array of document IDsconstbatch={documents: ['1234','5678']};// Delete batch of documentsclient.deleteDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Supported browsers

The client is tested on

  • Chrome
  • Firefox
  • Edge
  • Safari 6.1+
  • Internet Explorer 10+
  • Node.js

Development

To modify this client library, clone this repository to your computer and execute following commands.

Install dependencies

npm install

Code

Re-compile automatically when source files are changed

npm run watch

Run tests

npm test

Build

npm run build

Built bundle is saved under the dist/ folder

Support

Feel free to send any questions, ideas, and suggestions at support@addsearch.com or visit addsearch.com for more information.

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

AddSearch Search API Client for JavaScript

AddSearch is a Search-as-a-Service for all your search needs. This API Client lets you easily use the Search API and Indexing API with JavaScript.

Quick Start

The library is available on the global CDN jsDelivr:

<scriptsrc="https://cdn.jsdelivr.net/npm/addsearch-js-client@0.6/dist/addsearch-js-client.min.js"></script>

Or install the library locally to use it with Node.js:

npm install addsearch-js-client --save

After installation, add the library to your JS code

varAddSearchClient=require('addsearch-js-client');

Or use import in ES6

importAddSearchClientfrom'addsearch-js-client';

Execute the first search query

// Create client with your 32-character SITEKEYvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY');// Callback functionvarcb=function(res){// Print results to consoleconsole.log(res);};// Execute search. Callback function will be called with search resultsclient.search('keyword',cb);

Search API

The client provides following functions to execute search queries. To use the client library for indexing, see Indexing API.

Fetch search results

// Search with a specific keywordclient.search('keyword',callback);// Search with the previously used keyword or execute a "match all" queryclient.search(callback);// Search with the previously used keyword and callback (e.g. after modifying filters)client.search();

Fetch search suggestions

Search suggestions are keywords and search phrases that real users have used in your search. Configure Search suggestions on AddSearch Dashboard before using this function.

// Get suggestions starting with a specific prefixclient.suggestions('a',callback);

Set the number of search suggestions to fetch

// Number of search suggestions to fetch (default 10)client.setSuggestionsSize(20);

Custom field autocompletion

Custom fields autocomplete can be used for predictive search. For example, product names or categories can be suggested as the keyword is being typed in.

// Fetch custom field values starting with a specific prefix In this example, fetch records// starting with *a* from the *custom_fields.brand* field. Results could be "adidas, apple, azure"client.autocomplete('custom_fields.brand','a',callback);

Set the number of custom field autocompletion results to fetch

// Number of autocompletion results to fetch (default 10)client.setAutocompleteSize(20);

Search with fuzzy matching

Fuzzy matching is used for typo tolerance. There are four options:

  • false: No typo tolerance
  • true: Exact matches and fuzzy matches are equal
  • "auto": Exact matches first, followed by fuzzy matches
  • "retry": Show exact matches only. If none were found, show fuzzy matches
// Control fuzzy matching used for typo-tolerance// Possible values true/false/"auto"/"retry" (default: "auto")client.setFuzzyMatch(false);

Search operator

When a user searches with multiple keywords, we return only documents that contain all the terms which means applying the logical operator AND for the query. It is possible to choose which logical operator to use for fuzzy results when the fuzzy parameter is set to auto. There are two options:

  • "or": makes fuzzy results broader and includes partial matches of a few search terms
  • "and": makes fuzzy results stricter and includes only mistyped search terms
// Possible values "and"/"or" (default: "or")client.setSearchOperator('and');

Postfix wildcard

Enable or disable postfix wildcard. I.e. should keyword "add" match to "addsearch" or should it just match to the term add

// Possible values true/false (default: true)client.setPostfixWildcard(false);

Set enableLogicalOperators

// (default: false)// enableLogicalOperators(true) = Support user specified logical operators (and/or/not) in the search query like "cat and dog"// enableLogicalOperators(false) = Treat logical operators in the search query as literal stringsclient.enableLogicalOperators(true);

Set cacheResponseTime

Caching the response, define the time-to-live of the cache.

// Specify time-to-live value in secondsclient.setCacheResponseTime(3600);

Please contact our Support team to active Response Caching for your index.

Pagination

Set page number, page size and sorting parameters. It's possible to order results by:

  • relevance (descending)
  • date (ascending or descending)
  • custom field value (ascending or descending. E.g. custom_fields.price)

Type of sortBy and sortOrder: string or array. They must have the same type, in case type is array, sortBy and sortOrder must have the same size. For example:

sortBy='date';sortOrder='desc';or;sortBy=['date','custom_fields.price'];sortOrder=['desc','asc'];
// Defaults: page: 1, pageSize: 10, sortBy: "relevance", sortOrder: "desc"client.setPaging(page,pageSize,sortBy,sortOrder);

Other functions.

// Next page (call search function to fetch results)client.nextPage();// Previous pageclient.previousPage();

Filters

Define language filter

// Fetch documents in specific language (e.g. "en" or "de" or "en-GB")client.setLanguage('en');

Define publishing date filter

// Documents published between specific date rangeclient.setDateFilter('2019-01-01','2019-01-31');

Define price range filter

// Products in specific price range (in cents. e.g. 100,00 - 200,00)client.setPriceRangeFilter('10000','20000');

Define category filters

Filter by URL patterns, document types or addsearch-category meta tag values. See the full documentation.

// Only PDF files or productsclient.setCategoryFilters('doctype_pdf,products');

Custom field filters

Filter by custom fields. Custon fields can be defined in meta tags or AddSearch crawler can pick them up from your HTML or JSON data. See the full documentation.

// Search by specific city (Berlin, Paris or Boston)client.addCustomFieldFilter('city','berlin');client.addCustomFieldFilter('city','paris');client.addCustomFieldFilter('city','boston');// Remove Paris (Berlin and Boston remaining)client.removeCustomFieldFilter('city','paris');// Remove all citiesclient.removeCustomFieldFilter('city');

Set filtering object

Set complex filtering object that can contain nested and, or, not, and range filters.

// Find results where brand is apple, color is not white, and price is between 200 and 500varfilter={and: [{'custom_fields.brand': 'apple'},{not: {'custom_fields.color': 'white'}},{range: {'custom_fields.price': {gt: 200,lt: 500}}}]};client.setFilterObject(filter);

Set result type

// By default, fetch all search results// If "organic", Pinned results and Promotions are left outclient.setResultType('organic');

Facets

// Declare fields for faceting. Number of hits found from// these fields will be returnedclient.addFacetField('category');client.addFacetField('custom_fields.genre');

Facet values are returned in alphabetical order, 10 values per field by default. Use the following function to get more or less facets.

client.setNumberOfFacets(20);

Note: if a field has more values than the defined limit, the returned values are the first N in alphabetical order, not the N with most hits. Increase the limit if you need more values.

Numerical range facets

Group numerical custom fields into range buckets.

// Define ranges. E.g. products with price $0-$100, $100-$200, and over $200.// From value is inclusive, to value is exclusivevarranges=[{to: 100},{from: 100,to: 200},{from: 200}];// Parameters: field name, range arrayclient.addRangeFacet('custom_fields.price',ranges);

Field statistics

Get minimum, maximum, and average values of a numerical or date-based custom field. The information is handy for applications like range filtering.

// Search response will have a fieldStats element with information like// custom_fields.price: {min: 1230, max: 1590, avg: 1382}client.addStatsField('custom_fields.price');

Recommendations

Frequently bought together items

Get frequently bought together items, given "configurationKey" and "itemId"

// fetch frequently bought together itemsclient.recommendations({configurationKey: 'config1',itemId: '1065921'});

Search analytics

Send search event to analytics

When search is executed, send the event to your AddSearch Analytics Dashboard.

// If the numberOfResults is 0, the search is shown in the list of "queries with no hits"client.sendStatsEvent('search',keyword,{numberOfResults: n});

Send click event to analytics

When a search results is clicked, send the event to your AddSearch Analytics Dashboard. Click information is shown in your statistics and used by the self-learning search algorithm.

// documentId is the 32-character long id that is part of each hit in search results.// position is the position of the document that was clicked, the first result being 1client.sendStatsEvent('click',keyword,{documentId: id,position: n});

Set or get stats session ID

Control the search session ID manually. Search queries with the same ID are grouped on the Analytics Dashboard. For example, in a search-as-you-type implementation the final keyword of a given session is shown.

client.getStatsSessionId();client.setStatsSessionId(id);

Collect search events automatically

Send search events automatically to the Analytics Dashboard. Not recommended in search-as-you-type implementations, as every keystroke would fire a statistics event

// Control whether search queries are sent to your AddSearch Analytics Dashboard automatically or not (default: true)client.setCollectAnalytics(false);

Set a tag for analytics events

Defines a tag associated with all analytics events reported by the client. These tags will be available as filters in the AddSearch Analytics Dashboard. You can use tags, for instance, in A/B testing to compare which search UIs are most effective. Splitting the analytics with tags may also provide insights to the behaviour of audiences on different websites.

// Specify a tag for analytics events (the maximum length is 50 characters)client.setAnalyticsTag('Navigation search');

Personalization

Enable personalization tracking

Enable personalization tracking, user token will be included in every stat events as "session ID".

Set stats session ID if user token is generated by your site.

client.setStatsSessionId(userToken);

If session is not set, a UUID is generated and stored in a cookie named 'addsearchUserToken`. Specify the expiration date of the cookie. Default is 180.

// Defaults - isEnabled: false, expirationDates: 180client.enablePersonalizationTracking(isEnabled,expirationDates);

Allow storing AddSearch's user token in cookie

By default, the value is false. Set it to false when users reject cookie (AddSearch's cookie can be categorized as functional/analytics cookie), or set to true when user accepts cookie.

// Default: falseclient.consentAddSearchCookie(true);

Set user token to search query (for personalized search results)

// Add a user token to the search request (if personalization in use)client.setUserToken(userToken);

Get user token from AddSearch cookie

Get the user token which is stored in AddSearch cookie (if available).

// Get a user tokenclient.getUserTokenInPersonalization();

Send personalization events with search query - deprecated

In personalized search, user events are typically sent to AddSearch via API and a user token is passed with the search query (see setUserToken function). An alternative way is to send user events needed for personalization with the search query.

// Events depend on the personalization strategy// Contact AddSearch for more informationvarevents=[{favorite_genre: 'rock'},{favorite_band: 'Red Hot Chili Peppers'},{least_favorite_genre: 'country'}];client.setPersonalizationEvents(events);

Other

Set JSON Web Token (for authentication)

// Add JWT to the search request (if protected search index)client.setJWT(token);

Set API throttling

// Set Search API throttle time in milliseconds. Default is 200.client.setThrottleTime(500);

Set API hostname

option is an object with the following properties, all of which are optional. If option is not defined, host name will be applied for all requests.

  • searchApiRequestOnly: If true, the new host name is only applied for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the new host name is only applied for statsApi requests (default: false)
// Set API hostname (e.g. for dedicated environments)client.setApiHostname('api.addsearch.com',option);

Set API request interceptor

configurationObject contains 2 keys: url and headers. Modify the configurationObject before it is sent.

option is an object with the following properties, all of which are optional. If option is not defined, the interceptor will be used for all requests.

  • searchApiRequestOnly: If true, the interceptor is only used for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the interceptor is only used for statsApi requests (default: false)
functioncallback(configurationObject){configurationObject.headers['X-Api-Key']='YOUR API KEY';returnconfigurationObject;}client.setApiRequestInterceptor(callback,option);

AI Answers API

Fetch AI answers

// Get AI generated answer with a questionclient.aiAnswers('A question to get AI generated answers',callback);

Example of callback function and how the response looks like:

callbackFn=function(response){console.log(response);// response object contains the answer// {// "answer": "The answer to the question",// "conversation_id": "31f33b53-1fe1-4734-884f-fefa470f1389",// "ids": <array of ids belonging to source documents>, for example ['073010f023db7c6d558123f73a9b4f82', '821f7bea12daf0eda17ba2755979f7a5'],// "source_documents": <documents that provide context for AI generated answers, the object of this field looks similarly to the response of regular SearchApi result>// }};

Send Sentiment Analysis

// possible sentiment_value: positive, negativeclient.putSentimentClick('conversation_id','sentiment_value');

Set AI-answers filtering object

Set complex filtering object that can contain nested and, or, not. Key filterable properties include: category, custom_fields.<your_field_name>, language, doc_date

// Find results where region is en-us, color is not whitevaraiAnswersFilter={and: [{'custom_fields.region': 'en-us'},{not: {'custom_fields.color': 'white'}}]};client.setAiAnswersFilterObject(aiAnswersFilter);

POST API

❗ POST API is not fully supported. If you need to use some methods in the library, please contact our support.

Fetch AI answers

// default method: "GET"client.setApiMethod('POST');

Indexing API

With the Indexing API, you can fetch, create, update, and delete single documents or batches of documents.

Indexing API functions are meant to be used with Node.js. Never expose secret key in your website code.

// Create client with your keysvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY','YOUR SECRET KEY');

The secret key can be found from AddSearch Dashboard's "Setup" > "Keys and installation" page. Always keep the key secret.

All Indexing API functions are Promise-based.

Document structure

Documents can contain a set of pre-defined fields, as well as any number of custom fields defined under the custom_fields key.

Using pre-defined fields is optional, but default Search UI components display them by default, so pre-defined field give you visible results a bit faster.

Pre-defined fields are: url, title, and main_content.

Example document:

constdoc={id: '1234',url: 'https://www.example-store.com/product-x',title: 'Example product',main_content: 'Lorem ipsum',custom_fields: {name: 'Example product',description: 'Description for the example product',price_cents: 599,average_customer_rating: 4.5,release_date: 1589200255}};

Data types for custom fields are automatically detected from the content. Supported data types are:

  • text
  • integer
  • double

Dates should be defined as UNIX timestamps with integer values.

Document ID

If the id is not defined in the document at indexing time, it is generated automatically either randomly or from the url field.

// ID defined by the userconstdocWithDefinedId={id: '1234',custom_fields: {}};
// ID created from the URL field (md5 of the url)constdocWithURL={url: 'https://..',custom_fields: {}};
// ID generated randomlyconstdocWithAutogeneratedId={// No id or url fieldscustom_fields: {}};

Save document

Add a document to the index, or update a document.

constdoc={id: '1234',custom_fields: {name: 'Example product'}};// Save documentclient.saveDocument(doc).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Get document by ID

Fetch a specific document by ID.

client.getDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete document by ID

Delete a specific document by ID.

client.deleteDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Save batch of documents

Add or update bunch of documents defined in an array.

constbatch={documents: [{id: '1234',custom_fields: {name: 'Product 1'}},{id: '5678',custom_fields: {name: 'Product 2'}}]};// Save batch of documentsclient.saveDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete batch of documents

Delete multiple documents with an array of document IDs.

// Array of document IDsconstbatch={documents: ['1234','5678']};// Delete batch of documentsclient.deleteDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Supported browsers

The client is tested on

  • Chrome
  • Firefox
  • Edge
  • Safari 6.1+
  • Internet Explorer 10+
  • Node.js

Development

To modify this client library, clone this repository to your computer and execute following commands.

Install dependencies

npm install

Code

Re-compile automatically when source files are changed

npm run watch

Run tests

npm test

Build

npm run build

Built bundle is saved under the dist/ folder

Support

Feel free to send any questions, ideas, and suggestions at support@addsearch.com or visit addsearch.com for more information.

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

AddSearch Search API Client for JavaScript

AddSearch is a Search-as-a-Service for all your search needs. This API Client lets you easily use the Search API and Indexing API with JavaScript.

Quick Start

The library is available on the global CDN jsDelivr:

<scriptsrc="https://cdn.jsdelivr.net/npm/addsearch-js-client@0.6/dist/addsearch-js-client.min.js"></script>

Or install the library locally to use it with Node.js:

npm install addsearch-js-client --save

After installation, add the library to your JS code

varAddSearchClient=require('addsearch-js-client');

Or use import in ES6

importAddSearchClientfrom'addsearch-js-client';

Execute the first search query

// Create client with your 32-character SITEKEYvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY');// Callback functionvarcb=function(res){// Print results to consoleconsole.log(res);};// Execute search. Callback function will be called with search resultsclient.search('keyword',cb);

Search API

The client provides following functions to execute search queries. To use the client library for indexing, see Indexing API.

Fetch search results

// Search with a specific keywordclient.search('keyword',callback);// Search with the previously used keyword or execute a "match all" queryclient.search(callback);// Search with the previously used keyword and callback (e.g. after modifying filters)client.search();

Fetch search suggestions

Search suggestions are keywords and search phrases that real users have used in your search. Configure Search suggestions on AddSearch Dashboard before using this function.

// Get suggestions starting with a specific prefixclient.suggestions('a',callback);

Set the number of search suggestions to fetch

// Number of search suggestions to fetch (default 10)client.setSuggestionsSize(20);

Custom field autocompletion

Custom fields autocomplete can be used for predictive search. For example, product names or categories can be suggested as the keyword is being typed in.

// Fetch custom field values starting with a specific prefix In this example, fetch records// starting with *a* from the *custom_fields.brand* field. Results could be "adidas, apple, azure"client.autocomplete('custom_fields.brand','a',callback);

Set the number of custom field autocompletion results to fetch

// Number of autocompletion results to fetch (default 10)client.setAutocompleteSize(20);

Search with fuzzy matching

Fuzzy matching is used for typo tolerance. There are four options:

  • false: No typo tolerance
  • true: Exact matches and fuzzy matches are equal
  • "auto": Exact matches first, followed by fuzzy matches
  • "retry": Show exact matches only. If none were found, show fuzzy matches
// Control fuzzy matching used for typo-tolerance// Possible values true/false/"auto"/"retry" (default: "auto")client.setFuzzyMatch(false);

Search operator

When a user searches with multiple keywords, we return only documents that contain all the terms which means applying the logical operator AND for the query. It is possible to choose which logical operator to use for fuzzy results when the fuzzy parameter is set to auto. There are two options:

  • "or": makes fuzzy results broader and includes partial matches of a few search terms
  • "and": makes fuzzy results stricter and includes only mistyped search terms
// Possible values "and"/"or" (default: "or")client.setSearchOperator('and');

Postfix wildcard

Enable or disable postfix wildcard. I.e. should keyword "add" match to "addsearch" or should it just match to the term add

// Possible values true/false (default: true)client.setPostfixWildcard(false);

Set enableLogicalOperators

// (default: false)// enableLogicalOperators(true) = Support user specified logical operators (and/or/not) in the search query like "cat and dog"// enableLogicalOperators(false) = Treat logical operators in the search query as literal stringsclient.enableLogicalOperators(true);

Set cacheResponseTime

Caching the response, define the time-to-live of the cache.

// Specify time-to-live value in secondsclient.setCacheResponseTime(3600);

Please contact our Support team to active Response Caching for your index.

Pagination

Set page number, page size and sorting parameters. It's possible to order results by:

  • relevance (descending)
  • date (ascending or descending)
  • custom field value (ascending or descending. E.g. custom_fields.price)

Type of sortBy and sortOrder: string or array. They must have the same type, in case type is array, sortBy and sortOrder must have the same size. For example:

sortBy='date';sortOrder='desc';or;sortBy=['date','custom_fields.price'];sortOrder=['desc','asc'];
// Defaults: page: 1, pageSize: 10, sortBy: "relevance", sortOrder: "desc"client.setPaging(page,pageSize,sortBy,sortOrder);

Other functions.

// Next page (call search function to fetch results)client.nextPage();// Previous pageclient.previousPage();

Filters

Define language filter

// Fetch documents in specific language (e.g. "en" or "de" or "en-GB")client.setLanguage('en');

Define publishing date filter

// Documents published between specific date rangeclient.setDateFilter('2019-01-01','2019-01-31');

Define price range filter

// Products in specific price range (in cents. e.g. 100,00 - 200,00)client.setPriceRangeFilter('10000','20000');

Define category filters

Filter by URL patterns, document types or addsearch-category meta tag values. See the full documentation.

// Only PDF files or productsclient.setCategoryFilters('doctype_pdf,products');

Custom field filters

Filter by custom fields. Custon fields can be defined in meta tags or AddSearch crawler can pick them up from your HTML or JSON data. See the full documentation.

// Search by specific city (Berlin, Paris or Boston)client.addCustomFieldFilter('city','berlin');client.addCustomFieldFilter('city','paris');client.addCustomFieldFilter('city','boston');// Remove Paris (Berlin and Boston remaining)client.removeCustomFieldFilter('city','paris');// Remove all citiesclient.removeCustomFieldFilter('city');

Set filtering object

Set complex filtering object that can contain nested and, or, not, and range filters.

// Find results where brand is apple, color is not white, and price is between 200 and 500varfilter={and: [{'custom_fields.brand': 'apple'},{not: {'custom_fields.color': 'white'}},{range: {'custom_fields.price': {gt: 200,lt: 500}}}]};client.setFilterObject(filter);

Set result type

// By default, fetch all search results// If "organic", Pinned results and Promotions are left outclient.setResultType('organic');

Facets

// Declare fields for faceting. Number of hits found from// these fields will be returnedclient.addFacetField('category');client.addFacetField('custom_fields.genre');

Facet values are returned in alphabetical order, 10 values per field by default. Use the following function to get more or less facets.

client.setNumberOfFacets(20);

Note: if a field has more values than the defined limit, the returned values are the first N in alphabetical order, not the N with most hits. Increase the limit if you need more values.

Numerical range facets

Group numerical custom fields into range buckets.

// Define ranges. E.g. products with price $0-$100, $100-$200, and over $200.// From value is inclusive, to value is exclusivevarranges=[{to: 100},{from: 100,to: 200},{from: 200}];// Parameters: field name, range arrayclient.addRangeFacet('custom_fields.price',ranges);

Field statistics

Get minimum, maximum, and average values of a numerical or date-based custom field. The information is handy for applications like range filtering.

// Search response will have a fieldStats element with information like// custom_fields.price: {min: 1230, max: 1590, avg: 1382}client.addStatsField('custom_fields.price');

Recommendations

Frequently bought together items

Get frequently bought together items, given "configurationKey" and "itemId"

// fetch frequently bought together itemsclient.recommendations({configurationKey: 'config1',itemId: '1065921'});

Search analytics

Send search event to analytics

When search is executed, send the event to your AddSearch Analytics Dashboard.

// If the numberOfResults is 0, the search is shown in the list of "queries with no hits"client.sendStatsEvent('search',keyword,{numberOfResults: n});

Send click event to analytics

When a search results is clicked, send the event to your AddSearch Analytics Dashboard. Click information is shown in your statistics and used by the self-learning search algorithm.

// documentId is the 32-character long id that is part of each hit in search results.// position is the position of the document that was clicked, the first result being 1client.sendStatsEvent('click',keyword,{documentId: id,position: n});

Set or get stats session ID

Control the search session ID manually. Search queries with the same ID are grouped on the Analytics Dashboard. For example, in a search-as-you-type implementation the final keyword of a given session is shown.

client.getStatsSessionId();client.setStatsSessionId(id);

Collect search events automatically

Send search events automatically to the Analytics Dashboard. Not recommended in search-as-you-type implementations, as every keystroke would fire a statistics event

// Control whether search queries are sent to your AddSearch Analytics Dashboard automatically or not (default: true)client.setCollectAnalytics(false);

Set a tag for analytics events

Defines a tag associated with all analytics events reported by the client. These tags will be available as filters in the AddSearch Analytics Dashboard. You can use tags, for instance, in A/B testing to compare which search UIs are most effective. Splitting the analytics with tags may also provide insights to the behaviour of audiences on different websites.

// Specify a tag for analytics events (the maximum length is 50 characters)client.setAnalyticsTag('Navigation search');

Personalization

Enable personalization tracking

Enable personalization tracking, user token will be included in every stat events as "session ID".

Set stats session ID if user token is generated by your site.

client.setStatsSessionId(userToken);

If session is not set, a UUID is generated and stored in a cookie named 'addsearchUserToken`. Specify the expiration date of the cookie. Default is 180.

// Defaults - isEnabled: false, expirationDates: 180client.enablePersonalizationTracking(isEnabled,expirationDates);

Allow storing AddSearch's user token in cookie

By default, the value is false. Set it to false when users reject cookie (AddSearch's cookie can be categorized as functional/analytics cookie), or set to true when user accepts cookie.

// Default: falseclient.consentAddSearchCookie(true);

Set user token to search query (for personalized search results)

// Add a user token to the search request (if personalization in use)client.setUserToken(userToken);

Get user token from AddSearch cookie

Get the user token which is stored in AddSearch cookie (if available).

// Get a user tokenclient.getUserTokenInPersonalization();

Send personalization events with search query - deprecated

In personalized search, user events are typically sent to AddSearch via API and a user token is passed with the search query (see setUserToken function). An alternative way is to send user events needed for personalization with the search query.

// Events depend on the personalization strategy// Contact AddSearch for more informationvarevents=[{favorite_genre: 'rock'},{favorite_band: 'Red Hot Chili Peppers'},{least_favorite_genre: 'country'}];client.setPersonalizationEvents(events);

Other

Set JSON Web Token (for authentication)

// Add JWT to the search request (if protected search index)client.setJWT(token);

Set API throttling

// Set Search API throttle time in milliseconds. Default is 200.client.setThrottleTime(500);

Set API hostname

option is an object with the following properties, all of which are optional. If option is not defined, host name will be applied for all requests.

  • searchApiRequestOnly: If true, the new host name is only applied for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the new host name is only applied for statsApi requests (default: false)
// Set API hostname (e.g. for dedicated environments)client.setApiHostname('api.addsearch.com',option);

Set API request interceptor

configurationObject contains 2 keys: url and headers. Modify the configurationObject before it is sent.

option is an object with the following properties, all of which are optional. If option is not defined, the interceptor will be used for all requests.

  • searchApiRequestOnly: If true, the interceptor is only used for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the interceptor is only used for statsApi requests (default: false)
functioncallback(configurationObject){configurationObject.headers['X-Api-Key']='YOUR API KEY';returnconfigurationObject;}client.setApiRequestInterceptor(callback,option);

AI Answers API

Fetch AI answers

// Get AI generated answer with a questionclient.aiAnswers('A question to get AI generated answers',callback);

Example of callback function and how the response looks like:

callbackFn=function(response){console.log(response);// response object contains the answer// {// "answer": "The answer to the question",// "conversation_id": "31f33b53-1fe1-4734-884f-fefa470f1389",// "ids": <array of ids belonging to source documents>, for example ['073010f023db7c6d558123f73a9b4f82', '821f7bea12daf0eda17ba2755979f7a5'],// "source_documents": <documents that provide context for AI generated answers, the object of this field looks similarly to the response of regular SearchApi result>// }};

Send Sentiment Analysis

// possible sentiment_value: positive, negativeclient.putSentimentClick('conversation_id','sentiment_value');

Set AI-answers filtering object

Set complex filtering object that can contain nested and, or, not. Key filterable properties include: category, custom_fields.<your_field_name>, language, doc_date

// Find results where region is en-us, color is not whitevaraiAnswersFilter={and: [{'custom_fields.region': 'en-us'},{not: {'custom_fields.color': 'white'}}]};client.setAiAnswersFilterObject(aiAnswersFilter);

POST API

❗ POST API is not fully supported. If you need to use some methods in the library, please contact our support.

Fetch AI answers

// default method: "GET"client.setApiMethod('POST');

Indexing API

With the Indexing API, you can fetch, create, update, and delete single documents or batches of documents.

Indexing API functions are meant to be used with Node.js. Never expose secret key in your website code.

// Create client with your keysvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY','YOUR SECRET KEY');

The secret key can be found from AddSearch Dashboard's "Setup" > "Keys and installation" page. Always keep the key secret.

All Indexing API functions are Promise-based.

Document structure

Documents can contain a set of pre-defined fields, as well as any number of custom fields defined under the custom_fields key.

Using pre-defined fields is optional, but default Search UI components display them by default, so pre-defined field give you visible results a bit faster.

Pre-defined fields are: url, title, and main_content.

Example document:

constdoc={id: '1234',url: 'https://www.example-store.com/product-x',title: 'Example product',main_content: 'Lorem ipsum',custom_fields: {name: 'Example product',description: 'Description for the example product',price_cents: 599,average_customer_rating: 4.5,release_date: 1589200255}};

Data types for custom fields are automatically detected from the content. Supported data types are:

  • text
  • integer
  • double

Dates should be defined as UNIX timestamps with integer values.

Document ID

If the id is not defined in the document at indexing time, it is generated automatically either randomly or from the url field.

// ID defined by the userconstdocWithDefinedId={id: '1234',custom_fields: {}};
// ID created from the URL field (md5 of the url)constdocWithURL={url: 'https://..',custom_fields: {}};
// ID generated randomlyconstdocWithAutogeneratedId={// No id or url fieldscustom_fields: {}};

Save document

Add a document to the index, or update a document.

constdoc={id: '1234',custom_fields: {name: 'Example product'}};// Save documentclient.saveDocument(doc).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Get document by ID

Fetch a specific document by ID.

client.getDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete document by ID

Delete a specific document by ID.

client.deleteDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Save batch of documents

Add or update bunch of documents defined in an array.

constbatch={documents: [{id: '1234',custom_fields: {name: 'Product 1'}},{id: '5678',custom_fields: {name: 'Product 2'}}]};// Save batch of documentsclient.saveDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete batch of documents

Delete multiple documents with an array of document IDs.

// Array of document IDsconstbatch={documents: ['1234','5678']};// Delete batch of documentsclient.deleteDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Supported browsers

The client is tested on

  • Chrome
  • Firefox
  • Edge
  • Safari 6.1+
  • Internet Explorer 10+
  • Node.js

Development

To modify this client library, clone this repository to your computer and execute following commands.

Install dependencies

npm install

Code

Re-compile automatically when source files are changed

npm run watch

Run tests

npm test

Build

npm run build

Built bundle is saved under the dist/ folder

Support

Feel free to send any questions, ideas, and suggestions at support@addsearch.com or visit addsearch.com for more information.

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

AddSearch Search API Client for JavaScript

AddSearch is a Search-as-a-Service for all your search needs. This API Client lets you easily use the Search API and Indexing API with JavaScript.

Quick Start

The library is available on the global CDN jsDelivr:

<scriptsrc="https://cdn.jsdelivr.net/npm/addsearch-js-client@0.6/dist/addsearch-js-client.min.js"></script>

Or install the library locally to use it with Node.js:

npm install addsearch-js-client --save

After installation, add the library to your JS code

varAddSearchClient=require('addsearch-js-client');

Or use import in ES6

importAddSearchClientfrom'addsearch-js-client';

Execute the first search query

// Create client with your 32-character SITEKEYvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY');// Callback functionvarcb=function(res){// Print results to consoleconsole.log(res);};// Execute search. Callback function will be called with search resultsclient.search('keyword',cb);

Search API

The client provides following functions to execute search queries. To use the client library for indexing, see Indexing API.

Fetch search results

// Search with a specific keywordclient.search('keyword',callback);// Search with the previously used keyword or execute a "match all" queryclient.search(callback);// Search with the previously used keyword and callback (e.g. after modifying filters)client.search();

Fetch search suggestions

Search suggestions are keywords and search phrases that real users have used in your search. Configure Search suggestions on AddSearch Dashboard before using this function.

// Get suggestions starting with a specific prefixclient.suggestions('a',callback);

Set the number of search suggestions to fetch

// Number of search suggestions to fetch (default 10)client.setSuggestionsSize(20);

Custom field autocompletion

Custom fields autocomplete can be used for predictive search. For example, product names or categories can be suggested as the keyword is being typed in.

// Fetch custom field values starting with a specific prefix In this example, fetch records// starting with *a* from the *custom_fields.brand* field. Results could be "adidas, apple, azure"client.autocomplete('custom_fields.brand','a',callback);

Set the number of custom field autocompletion results to fetch

// Number of autocompletion results to fetch (default 10)client.setAutocompleteSize(20);

Search with fuzzy matching

Fuzzy matching is used for typo tolerance. There are four options:

  • false: No typo tolerance
  • true: Exact matches and fuzzy matches are equal
  • "auto": Exact matches first, followed by fuzzy matches
  • "retry": Show exact matches only. If none were found, show fuzzy matches
// Control fuzzy matching used for typo-tolerance// Possible values true/false/"auto"/"retry" (default: "auto")client.setFuzzyMatch(false);

Search operator

When a user searches with multiple keywords, we return only documents that contain all the terms which means applying the logical operator AND for the query. It is possible to choose which logical operator to use for fuzzy results when the fuzzy parameter is set to auto. There are two options:

  • "or": makes fuzzy results broader and includes partial matches of a few search terms
  • "and": makes fuzzy results stricter and includes only mistyped search terms
// Possible values "and"/"or" (default: "or")client.setSearchOperator('and');

Postfix wildcard

Enable or disable postfix wildcard. I.e. should keyword "add" match to "addsearch" or should it just match to the term add

// Possible values true/false (default: true)client.setPostfixWildcard(false);

Set enableLogicalOperators

// (default: false)// enableLogicalOperators(true) = Support user specified logical operators (and/or/not) in the search query like "cat and dog"// enableLogicalOperators(false) = Treat logical operators in the search query as literal stringsclient.enableLogicalOperators(true);

Set cacheResponseTime

Caching the response, define the time-to-live of the cache.

// Specify time-to-live value in secondsclient.setCacheResponseTime(3600);

Please contact our Support team to active Response Caching for your index.

Pagination

Set page number, page size and sorting parameters. It's possible to order results by:

  • relevance (descending)
  • date (ascending or descending)
  • custom field value (ascending or descending. E.g. custom_fields.price)

Type of sortBy and sortOrder: string or array. They must have the same type, in case type is array, sortBy and sortOrder must have the same size. For example:

sortBy='date';sortOrder='desc';or;sortBy=['date','custom_fields.price'];sortOrder=['desc','asc'];
// Defaults: page: 1, pageSize: 10, sortBy: "relevance", sortOrder: "desc"client.setPaging(page,pageSize,sortBy,sortOrder);

Other functions.

// Next page (call search function to fetch results)client.nextPage();// Previous pageclient.previousPage();

Filters

Define language filter

// Fetch documents in specific language (e.g. "en" or "de" or "en-GB")client.setLanguage('en');

Define publishing date filter

// Documents published between specific date rangeclient.setDateFilter('2019-01-01','2019-01-31');

Define price range filter

// Products in specific price range (in cents. e.g. 100,00 - 200,00)client.setPriceRangeFilter('10000','20000');

Define category filters

Filter by URL patterns, document types or addsearch-category meta tag values. See the full documentation.

// Only PDF files or productsclient.setCategoryFilters('doctype_pdf,products');

Custom field filters

Filter by custom fields. Custon fields can be defined in meta tags or AddSearch crawler can pick them up from your HTML or JSON data. See the full documentation.

// Search by specific city (Berlin, Paris or Boston)client.addCustomFieldFilter('city','berlin');client.addCustomFieldFilter('city','paris');client.addCustomFieldFilter('city','boston');// Remove Paris (Berlin and Boston remaining)client.removeCustomFieldFilter('city','paris');// Remove all citiesclient.removeCustomFieldFilter('city');

Set filtering object

Set complex filtering object that can contain nested and, or, not, and range filters.

// Find results where brand is apple, color is not white, and price is between 200 and 500varfilter={and: [{'custom_fields.brand': 'apple'},{not: {'custom_fields.color': 'white'}},{range: {'custom_fields.price': {gt: 200,lt: 500}}}]};client.setFilterObject(filter);

Set result type

// By default, fetch all search results// If "organic", Pinned results and Promotions are left outclient.setResultType('organic');

Facets

// Declare fields for faceting. Number of hits found from// these fields will be returnedclient.addFacetField('category');client.addFacetField('custom_fields.genre');

Facet values are returned in alphabetical order, 10 values per field by default. Use the following function to get more or less facets.

client.setNumberOfFacets(20);

Note: if a field has more values than the defined limit, the returned values are the first N in alphabetical order, not the N with most hits. Increase the limit if you need more values.

Numerical range facets

Group numerical custom fields into range buckets.

// Define ranges. E.g. products with price $0-$100, $100-$200, and over $200.// From value is inclusive, to value is exclusivevarranges=[{to: 100},{from: 100,to: 200},{from: 200}];// Parameters: field name, range arrayclient.addRangeFacet('custom_fields.price',ranges);

Field statistics

Get minimum, maximum, and average values of a numerical or date-based custom field. The information is handy for applications like range filtering.

// Search response will have a fieldStats element with information like// custom_fields.price: {min: 1230, max: 1590, avg: 1382}client.addStatsField('custom_fields.price');

Recommendations

Frequently bought together items

Get frequently bought together items, given "configurationKey" and "itemId"

// fetch frequently bought together itemsclient.recommendations({configurationKey: 'config1',itemId: '1065921'});

Search analytics

Send search event to analytics

When search is executed, send the event to your AddSearch Analytics Dashboard.

// If the numberOfResults is 0, the search is shown in the list of "queries with no hits"client.sendStatsEvent('search',keyword,{numberOfResults: n});

Send click event to analytics

When a search results is clicked, send the event to your AddSearch Analytics Dashboard. Click information is shown in your statistics and used by the self-learning search algorithm.

// documentId is the 32-character long id that is part of each hit in search results.// position is the position of the document that was clicked, the first result being 1client.sendStatsEvent('click',keyword,{documentId: id,position: n});

Set or get stats session ID

Control the search session ID manually. Search queries with the same ID are grouped on the Analytics Dashboard. For example, in a search-as-you-type implementation the final keyword of a given session is shown.

client.getStatsSessionId();client.setStatsSessionId(id);

Collect search events automatically

Send search events automatically to the Analytics Dashboard. Not recommended in search-as-you-type implementations, as every keystroke would fire a statistics event

// Control whether search queries are sent to your AddSearch Analytics Dashboard automatically or not (default: true)client.setCollectAnalytics(false);

Set a tag for analytics events

Defines a tag associated with all analytics events reported by the client. These tags will be available as filters in the AddSearch Analytics Dashboard. You can use tags, for instance, in A/B testing to compare which search UIs are most effective. Splitting the analytics with tags may also provide insights to the behaviour of audiences on different websites.

// Specify a tag for analytics events (the maximum length is 50 characters)client.setAnalyticsTag('Navigation search');

Personalization

Enable personalization tracking

Enable personalization tracking, user token will be included in every stat events as "session ID".

Set stats session ID if user token is generated by your site.

client.setStatsSessionId(userToken);

If session is not set, a UUID is generated and stored in a cookie named 'addsearchUserToken`. Specify the expiration date of the cookie. Default is 180.

// Defaults - isEnabled: false, expirationDates: 180client.enablePersonalizationTracking(isEnabled,expirationDates);

Allow storing AddSearch's user token in cookie

By default, the value is false. Set it to false when users reject cookie (AddSearch's cookie can be categorized as functional/analytics cookie), or set to true when user accepts cookie.

// Default: falseclient.consentAddSearchCookie(true);

Set user token to search query (for personalized search results)

// Add a user token to the search request (if personalization in use)client.setUserToken(userToken);

Get user token from AddSearch cookie

Get the user token which is stored in AddSearch cookie (if available).

// Get a user tokenclient.getUserTokenInPersonalization();

Send personalization events with search query - deprecated

In personalized search, user events are typically sent to AddSearch via API and a user token is passed with the search query (see setUserToken function). An alternative way is to send user events needed for personalization with the search query.

// Events depend on the personalization strategy// Contact AddSearch for more informationvarevents=[{favorite_genre: 'rock'},{favorite_band: 'Red Hot Chili Peppers'},{least_favorite_genre: 'country'}];client.setPersonalizationEvents(events);

Other

Set JSON Web Token (for authentication)

// Add JWT to the search request (if protected search index)client.setJWT(token);

Set API throttling

// Set Search API throttle time in milliseconds. Default is 200.client.setThrottleTime(500);

Set API hostname

option is an object with the following properties, all of which are optional. If option is not defined, host name will be applied for all requests.

  • searchApiRequestOnly: If true, the new host name is only applied for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the new host name is only applied for statsApi requests (default: false)
// Set API hostname (e.g. for dedicated environments)client.setApiHostname('api.addsearch.com',option);

Set API request interceptor

configurationObject contains 2 keys: url and headers. Modify the configurationObject before it is sent.

option is an object with the following properties, all of which are optional. If option is not defined, the interceptor will be used for all requests.

  • searchApiRequestOnly: If true, the interceptor is only used for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the interceptor is only used for statsApi requests (default: false)
functioncallback(configurationObject){configurationObject.headers['X-Api-Key']='YOUR API KEY';returnconfigurationObject;}client.setApiRequestInterceptor(callback,option);

AI Answers API

Fetch AI answers

// Get AI generated answer with a questionclient.aiAnswers('A question to get AI generated answers',callback);

Example of callback function and how the response looks like:

callbackFn=function(response){console.log(response);// response object contains the answer// {// "answer": "The answer to the question",// "conversation_id": "31f33b53-1fe1-4734-884f-fefa470f1389",// "ids": <array of ids belonging to source documents>, for example ['073010f023db7c6d558123f73a9b4f82', '821f7bea12daf0eda17ba2755979f7a5'],// "source_documents": <documents that provide context for AI generated answers, the object of this field looks similarly to the response of regular SearchApi result>// }};

Send Sentiment Analysis

// possible sentiment_value: positive, negativeclient.putSentimentClick('conversation_id','sentiment_value');

Set AI-answers filtering object

Set complex filtering object that can contain nested and, or, not. Key filterable properties include: category, custom_fields.<your_field_name>, language, doc_date

// Find results where region is en-us, color is not whitevaraiAnswersFilter={and: [{'custom_fields.region': 'en-us'},{not: {'custom_fields.color': 'white'}}]};client.setAiAnswersFilterObject(aiAnswersFilter);

POST API

❗ POST API is not fully supported. If you need to use some methods in the library, please contact our support.

Fetch AI answers

// default method: "GET"client.setApiMethod('POST');

Indexing API

With the Indexing API, you can fetch, create, update, and delete single documents or batches of documents.

Indexing API functions are meant to be used with Node.js. Never expose secret key in your website code.

// Create client with your keysvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY','YOUR SECRET KEY');

The secret key can be found from AddSearch Dashboard's "Setup" > "Keys and installation" page. Always keep the key secret.

All Indexing API functions are Promise-based.

Document structure

Documents can contain a set of pre-defined fields, as well as any number of custom fields defined under the custom_fields key.

Using pre-defined fields is optional, but default Search UI components display them by default, so pre-defined field give you visible results a bit faster.

Pre-defined fields are: url, title, and main_content.

Example document:

constdoc={id: '1234',url: 'https://www.example-store.com/product-x',title: 'Example product',main_content: 'Lorem ipsum',custom_fields: {name: 'Example product',description: 'Description for the example product',price_cents: 599,average_customer_rating: 4.5,release_date: 1589200255}};

Data types for custom fields are automatically detected from the content. Supported data types are:

  • text
  • integer
  • double

Dates should be defined as UNIX timestamps with integer values.

Document ID

If the id is not defined in the document at indexing time, it is generated automatically either randomly or from the url field.

// ID defined by the userconstdocWithDefinedId={id: '1234',custom_fields: {}};
// ID created from the URL field (md5 of the url)constdocWithURL={url: 'https://..',custom_fields: {}};
// ID generated randomlyconstdocWithAutogeneratedId={// No id or url fieldscustom_fields: {}};

Save document

Add a document to the index, or update a document.

constdoc={id: '1234',custom_fields: {name: 'Example product'}};// Save documentclient.saveDocument(doc).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Get document by ID

Fetch a specific document by ID.

client.getDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete document by ID

Delete a specific document by ID.

client.deleteDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Save batch of documents

Add or update bunch of documents defined in an array.

constbatch={documents: [{id: '1234',custom_fields: {name: 'Product 1'}},{id: '5678',custom_fields: {name: 'Product 2'}}]};// Save batch of documentsclient.saveDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete batch of documents

Delete multiple documents with an array of document IDs.

// Array of document IDsconstbatch={documents: ['1234','5678']};// Delete batch of documentsclient.deleteDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Supported browsers

The client is tested on

  • Chrome
  • Firefox
  • Edge
  • Safari 6.1+
  • Internet Explorer 10+
  • Node.js

Development

To modify this client library, clone this repository to your computer and execute following commands.

Install dependencies

npm install

Code

Re-compile automatically when source files are changed

npm run watch

Run tests

npm test

Build

npm run build

Built bundle is saved under the dist/ folder

Support

Feel free to send any questions, ideas, and suggestions at support@addsearch.com or visit addsearch.com for more information.

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

AddSearch Search API Client for JavaScript

AddSearch is a Search-as-a-Service for all your search needs. This API Client lets you easily use the Search API and Indexing API with JavaScript.

Quick Start

The library is available on the global CDN jsDelivr:

<scriptsrc="https://cdn.jsdelivr.net/npm/addsearch-js-client@0.6/dist/addsearch-js-client.min.js"></script>

Or install the library locally to use it with Node.js:

npm install addsearch-js-client --save

After installation, add the library to your JS code

varAddSearchClient=require('addsearch-js-client');

Or use import in ES6

importAddSearchClientfrom'addsearch-js-client';

Execute the first search query

// Create client with your 32-character SITEKEYvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY');// Callback functionvarcb=function(res){// Print results to consoleconsole.log(res);};// Execute search. Callback function will be called with search resultsclient.search('keyword',cb);

Search API

The client provides following functions to execute search queries. To use the client library for indexing, see Indexing API.

Fetch search results

// Search with a specific keywordclient.search('keyword',callback);// Search with the previously used keyword or execute a "match all" queryclient.search(callback);// Search with the previously used keyword and callback (e.g. after modifying filters)client.search();

Fetch search suggestions

Search suggestions are keywords and search phrases that real users have used in your search. Configure Search suggestions on AddSearch Dashboard before using this function.

// Get suggestions starting with a specific prefixclient.suggestions('a',callback);

Set the number of search suggestions to fetch

// Number of search suggestions to fetch (default 10)client.setSuggestionsSize(20);

Custom field autocompletion

Custom fields autocomplete can be used for predictive search. For example, product names or categories can be suggested as the keyword is being typed in.

// Fetch custom field values starting with a specific prefix In this example, fetch records// starting with *a* from the *custom_fields.brand* field. Results could be "adidas, apple, azure"client.autocomplete('custom_fields.brand','a',callback);

Set the number of custom field autocompletion results to fetch

// Number of autocompletion results to fetch (default 10)client.setAutocompleteSize(20);

Search with fuzzy matching

Fuzzy matching is used for typo tolerance. There are four options:

  • false: No typo tolerance
  • true: Exact matches and fuzzy matches are equal
  • "auto": Exact matches first, followed by fuzzy matches
  • "retry": Show exact matches only. If none were found, show fuzzy matches
// Control fuzzy matching used for typo-tolerance// Possible values true/false/"auto"/"retry" (default: "auto")client.setFuzzyMatch(false);

Search operator

When a user searches with multiple keywords, we return only documents that contain all the terms which means applying the logical operator AND for the query. It is possible to choose which logical operator to use for fuzzy results when the fuzzy parameter is set to auto. There are two options:

  • "or": makes fuzzy results broader and includes partial matches of a few search terms
  • "and": makes fuzzy results stricter and includes only mistyped search terms
// Possible values "and"/"or" (default: "or")client.setSearchOperator('and');

Postfix wildcard

Enable or disable postfix wildcard. I.e. should keyword "add" match to "addsearch" or should it just match to the term add

// Possible values true/false (default: true)client.setPostfixWildcard(false);

Set enableLogicalOperators

// (default: false)// enableLogicalOperators(true) = Support user specified logical operators (and/or/not) in the search query like "cat and dog"// enableLogicalOperators(false) = Treat logical operators in the search query as literal stringsclient.enableLogicalOperators(true);

Set cacheResponseTime

Caching the response, define the time-to-live of the cache.

// Specify time-to-live value in secondsclient.setCacheResponseTime(3600);

Please contact our Support team to active Response Caching for your index.

Pagination

Set page number, page size and sorting parameters. It's possible to order results by:

  • relevance (descending)
  • date (ascending or descending)
  • custom field value (ascending or descending. E.g. custom_fields.price)

Type of sortBy and sortOrder: string or array. They must have the same type, in case type is array, sortBy and sortOrder must have the same size. For example:

sortBy='date';sortOrder='desc';or;sortBy=['date','custom_fields.price'];sortOrder=['desc','asc'];
// Defaults: page: 1, pageSize: 10, sortBy: "relevance", sortOrder: "desc"client.setPaging(page,pageSize,sortBy,sortOrder);

Other functions.

// Next page (call search function to fetch results)client.nextPage();// Previous pageclient.previousPage();

Filters

Define language filter

// Fetch documents in specific language (e.g. "en" or "de" or "en-GB")client.setLanguage('en');

Define publishing date filter

// Documents published between specific date rangeclient.setDateFilter('2019-01-01','2019-01-31');

Define price range filter

// Products in specific price range (in cents. e.g. 100,00 - 200,00)client.setPriceRangeFilter('10000','20000');

Define category filters

Filter by URL patterns, document types or addsearch-category meta tag values. See the full documentation.

// Only PDF files or productsclient.setCategoryFilters('doctype_pdf,products');

Custom field filters

Filter by custom fields. Custon fields can be defined in meta tags or AddSearch crawler can pick them up from your HTML or JSON data. See the full documentation.

// Search by specific city (Berlin, Paris or Boston)client.addCustomFieldFilter('city','berlin');client.addCustomFieldFilter('city','paris');client.addCustomFieldFilter('city','boston');// Remove Paris (Berlin and Boston remaining)client.removeCustomFieldFilter('city','paris');// Remove all citiesclient.removeCustomFieldFilter('city');

Set filtering object

Set complex filtering object that can contain nested and, or, not, and range filters.

// Find results where brand is apple, color is not white, and price is between 200 and 500varfilter={and: [{'custom_fields.brand': 'apple'},{not: {'custom_fields.color': 'white'}},{range: {'custom_fields.price': {gt: 200,lt: 500}}}]};client.setFilterObject(filter);

Set result type

// By default, fetch all search results// If "organic", Pinned results and Promotions are left outclient.setResultType('organic');

Facets

// Declare fields for faceting. Number of hits found from// these fields will be returnedclient.addFacetField('category');client.addFacetField('custom_fields.genre');

Facet values are returned in alphabetical order, 10 values per field by default. Use the following function to get more or less facets.

client.setNumberOfFacets(20);

Note: if a field has more values than the defined limit, the returned values are the first N in alphabetical order, not the N with most hits. Increase the limit if you need more values.

Numerical range facets

Group numerical custom fields into range buckets.

// Define ranges. E.g. products with price $0-$100, $100-$200, and over $200.// From value is inclusive, to value is exclusivevarranges=[{to: 100},{from: 100,to: 200},{from: 200}];// Parameters: field name, range arrayclient.addRangeFacet('custom_fields.price',ranges);

Field statistics

Get minimum, maximum, and average values of a numerical or date-based custom field. The information is handy for applications like range filtering.

// Search response will have a fieldStats element with information like// custom_fields.price: {min: 1230, max: 1590, avg: 1382}client.addStatsField('custom_fields.price');

Recommendations

Frequently bought together items

Get frequently bought together items, given "configurationKey" and "itemId"

// fetch frequently bought together itemsclient.recommendations({configurationKey: 'config1',itemId: '1065921'});

Search analytics

Send search event to analytics

When search is executed, send the event to your AddSearch Analytics Dashboard.

// If the numberOfResults is 0, the search is shown in the list of "queries with no hits"client.sendStatsEvent('search',keyword,{numberOfResults: n});

Send click event to analytics

When a search results is clicked, send the event to your AddSearch Analytics Dashboard. Click information is shown in your statistics and used by the self-learning search algorithm.

// documentId is the 32-character long id that is part of each hit in search results.// position is the position of the document that was clicked, the first result being 1client.sendStatsEvent('click',keyword,{documentId: id,position: n});

Set or get stats session ID

Control the search session ID manually. Search queries with the same ID are grouped on the Analytics Dashboard. For example, in a search-as-you-type implementation the final keyword of a given session is shown.

client.getStatsSessionId();client.setStatsSessionId(id);

Collect search events automatically

Send search events automatically to the Analytics Dashboard. Not recommended in search-as-you-type implementations, as every keystroke would fire a statistics event

// Control whether search queries are sent to your AddSearch Analytics Dashboard automatically or not (default: true)client.setCollectAnalytics(false);

Set a tag for analytics events

Defines a tag associated with all analytics events reported by the client. These tags will be available as filters in the AddSearch Analytics Dashboard. You can use tags, for instance, in A/B testing to compare which search UIs are most effective. Splitting the analytics with tags may also provide insights to the behaviour of audiences on different websites.

// Specify a tag for analytics events (the maximum length is 50 characters)client.setAnalyticsTag('Navigation search');

Personalization

Enable personalization tracking

Enable personalization tracking, user token will be included in every stat events as "session ID".

Set stats session ID if user token is generated by your site.

client.setStatsSessionId(userToken);

If session is not set, a UUID is generated and stored in a cookie named 'addsearchUserToken`. Specify the expiration date of the cookie. Default is 180.

// Defaults - isEnabled: false, expirationDates: 180client.enablePersonalizationTracking(isEnabled,expirationDates);

Allow storing AddSearch's user token in cookie

By default, the value is false. Set it to false when users reject cookie (AddSearch's cookie can be categorized as functional/analytics cookie), or set to true when user accepts cookie.

// Default: falseclient.consentAddSearchCookie(true);

Set user token to search query (for personalized search results)

// Add a user token to the search request (if personalization in use)client.setUserToken(userToken);

Get user token from AddSearch cookie

Get the user token which is stored in AddSearch cookie (if available).

// Get a user tokenclient.getUserTokenInPersonalization();

Send personalization events with search query - deprecated

In personalized search, user events are typically sent to AddSearch via API and a user token is passed with the search query (see setUserToken function). An alternative way is to send user events needed for personalization with the search query.

// Events depend on the personalization strategy// Contact AddSearch for more informationvarevents=[{favorite_genre: 'rock'},{favorite_band: 'Red Hot Chili Peppers'},{least_favorite_genre: 'country'}];client.setPersonalizationEvents(events);

Other

Set JSON Web Token (for authentication)

// Add JWT to the search request (if protected search index)client.setJWT(token);

Set API throttling

// Set Search API throttle time in milliseconds. Default is 200.client.setThrottleTime(500);

Set API hostname

option is an object with the following properties, all of which are optional. If option is not defined, host name will be applied for all requests.

  • searchApiRequestOnly: If true, the new host name is only applied for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the new host name is only applied for statsApi requests (default: false)
// Set API hostname (e.g. for dedicated environments)client.setApiHostname('api.addsearch.com',option);

Set API request interceptor

configurationObject contains 2 keys: url and headers. Modify the configurationObject before it is sent.

option is an object with the following properties, all of which are optional. If option is not defined, the interceptor will be used for all requests.

  • searchApiRequestOnly: If true, the interceptor is only used for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the interceptor is only used for statsApi requests (default: false)
functioncallback(configurationObject){configurationObject.headers['X-Api-Key']='YOUR API KEY';returnconfigurationObject;}client.setApiRequestInterceptor(callback,option);

AI Answers API

Fetch AI answers

// Get AI generated answer with a questionclient.aiAnswers('A question to get AI generated answers',callback);

Example of callback function and how the response looks like:

callbackFn=function(response){console.log(response);// response object contains the answer// {// "answer": "The answer to the question",// "conversation_id": "31f33b53-1fe1-4734-884f-fefa470f1389",// "ids": <array of ids belonging to source documents>, for example ['073010f023db7c6d558123f73a9b4f82', '821f7bea12daf0eda17ba2755979f7a5'],// "source_documents": <documents that provide context for AI generated answers, the object of this field looks similarly to the response of regular SearchApi result>// }};

Send Sentiment Analysis

// possible sentiment_value: positive, negativeclient.putSentimentClick('conversation_id','sentiment_value');

Set AI-answers filtering object

Set complex filtering object that can contain nested and, or, not. Key filterable properties include: category, custom_fields.<your_field_name>, language, doc_date

// Find results where region is en-us, color is not whitevaraiAnswersFilter={and: [{'custom_fields.region': 'en-us'},{not: {'custom_fields.color': 'white'}}]};client.setAiAnswersFilterObject(aiAnswersFilter);

POST API

❗ POST API is not fully supported. If you need to use some methods in the library, please contact our support.

Fetch AI answers

// default method: "GET"client.setApiMethod('POST');

Indexing API

With the Indexing API, you can fetch, create, update, and delete single documents or batches of documents.

Indexing API functions are meant to be used with Node.js. Never expose secret key in your website code.

// Create client with your keysvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY','YOUR SECRET KEY');

The secret key can be found from AddSearch Dashboard's "Setup" > "Keys and installation" page. Always keep the key secret.

All Indexing API functions are Promise-based.

Document structure

Documents can contain a set of pre-defined fields, as well as any number of custom fields defined under the custom_fields key.

Using pre-defined fields is optional, but default Search UI components display them by default, so pre-defined field give you visible results a bit faster.

Pre-defined fields are: url, title, and main_content.

Example document:

constdoc={id: '1234',url: 'https://www.example-store.com/product-x',title: 'Example product',main_content: 'Lorem ipsum',custom_fields: {name: 'Example product',description: 'Description for the example product',price_cents: 599,average_customer_rating: 4.5,release_date: 1589200255}};

Data types for custom fields are automatically detected from the content. Supported data types are:

  • text
  • integer
  • double

Dates should be defined as UNIX timestamps with integer values.

Document ID

If the id is not defined in the document at indexing time, it is generated automatically either randomly or from the url field.

// ID defined by the userconstdocWithDefinedId={id: '1234',custom_fields: {}};
// ID created from the URL field (md5 of the url)constdocWithURL={url: 'https://..',custom_fields: {}};
// ID generated randomlyconstdocWithAutogeneratedId={// No id or url fieldscustom_fields: {}};

Save document

Add a document to the index, or update a document.

constdoc={id: '1234',custom_fields: {name: 'Example product'}};// Save documentclient.saveDocument(doc).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Get document by ID

Fetch a specific document by ID.

client.getDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete document by ID

Delete a specific document by ID.

client.deleteDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Save batch of documents

Add or update bunch of documents defined in an array.

constbatch={documents: [{id: '1234',custom_fields: {name: 'Product 1'}},{id: '5678',custom_fields: {name: 'Product 2'}}]};// Save batch of documentsclient.saveDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete batch of documents

Delete multiple documents with an array of document IDs.

// Array of document IDsconstbatch={documents: ['1234','5678']};// Delete batch of documentsclient.deleteDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Supported browsers

The client is tested on

  • Chrome
  • Firefox
  • Edge
  • Safari 6.1+
  • Internet Explorer 10+
  • Node.js

Development

To modify this client library, clone this repository to your computer and execute following commands.

Install dependencies

npm install

Code

Re-compile automatically when source files are changed

npm run watch

Run tests

npm test

Build

npm run build

Built bundle is saved under the dist/ folder

Support

Feel free to send any questions, ideas, and suggestions at support@addsearch.com or visit addsearch.com for more information.

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

AddSearch Search API Client for JavaScript

AddSearch is a Search-as-a-Service for all your search needs. This API Client lets you easily use the Search API and Indexing API with JavaScript.

Quick Start

The library is available on the global CDN jsDelivr:

<scriptsrc="https://cdn.jsdelivr.net/npm/addsearch-js-client@0.6/dist/addsearch-js-client.min.js"></script>

Or install the library locally to use it with Node.js:

npm install addsearch-js-client --save

After installation, add the library to your JS code

varAddSearchClient=require('addsearch-js-client');

Or use import in ES6

importAddSearchClientfrom'addsearch-js-client';

Execute the first search query

// Create client with your 32-character SITEKEYvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY');// Callback functionvarcb=function(res){// Print results to consoleconsole.log(res);};// Execute search. Callback function will be called with search resultsclient.search('keyword',cb);

Search API

The client provides following functions to execute search queries. To use the client library for indexing, see Indexing API.

Fetch search results

// Search with a specific keywordclient.search('keyword',callback);// Search with the previously used keyword or execute a "match all" queryclient.search(callback);// Search with the previously used keyword and callback (e.g. after modifying filters)client.search();

Fetch search suggestions

Search suggestions are keywords and search phrases that real users have used in your search. Configure Search suggestions on AddSearch Dashboard before using this function.

// Get suggestions starting with a specific prefixclient.suggestions('a',callback);

Set the number of search suggestions to fetch

// Number of search suggestions to fetch (default 10)client.setSuggestionsSize(20);

Custom field autocompletion

Custom fields autocomplete can be used for predictive search. For example, product names or categories can be suggested as the keyword is being typed in.

// Fetch custom field values starting with a specific prefix In this example, fetch records// starting with *a* from the *custom_fields.brand* field. Results could be "adidas, apple, azure"client.autocomplete('custom_fields.brand','a',callback);

Set the number of custom field autocompletion results to fetch

// Number of autocompletion results to fetch (default 10)client.setAutocompleteSize(20);

Search with fuzzy matching

Fuzzy matching is used for typo tolerance. There are four options:

  • false: No typo tolerance
  • true: Exact matches and fuzzy matches are equal
  • "auto": Exact matches first, followed by fuzzy matches
  • "retry": Show exact matches only. If none were found, show fuzzy matches
// Control fuzzy matching used for typo-tolerance// Possible values true/false/"auto"/"retry" (default: "auto")client.setFuzzyMatch(false);

Search operator

When a user searches with multiple keywords, we return only documents that contain all the terms which means applying the logical operator AND for the query. It is possible to choose which logical operator to use for fuzzy results when the fuzzy parameter is set to auto. There are two options:

  • "or": makes fuzzy results broader and includes partial matches of a few search terms
  • "and": makes fuzzy results stricter and includes only mistyped search terms
// Possible values "and"/"or" (default: "or")client.setSearchOperator('and');

Postfix wildcard

Enable or disable postfix wildcard. I.e. should keyword "add" match to "addsearch" or should it just match to the term add

// Possible values true/false (default: true)client.setPostfixWildcard(false);

Set enableLogicalOperators

// (default: false)// enableLogicalOperators(true) = Support user specified logical operators (and/or/not) in the search query like "cat and dog"// enableLogicalOperators(false) = Treat logical operators in the search query as literal stringsclient.enableLogicalOperators(true);

Set cacheResponseTime

Caching the response, define the time-to-live of the cache.

// Specify time-to-live value in secondsclient.setCacheResponseTime(3600);

Please contact our Support team to active Response Caching for your index.

Pagination

Set page number, page size and sorting parameters. It's possible to order results by:

  • relevance (descending)
  • date (ascending or descending)
  • custom field value (ascending or descending. E.g. custom_fields.price)

Type of sortBy and sortOrder: string or array. They must have the same type, in case type is array, sortBy and sortOrder must have the same size. For example:

sortBy='date';sortOrder='desc';or;sortBy=['date','custom_fields.price'];sortOrder=['desc','asc'];
// Defaults: page: 1, pageSize: 10, sortBy: "relevance", sortOrder: "desc"client.setPaging(page,pageSize,sortBy,sortOrder);

Other functions.

// Next page (call search function to fetch results)client.nextPage();// Previous pageclient.previousPage();

Filters

Define language filter

// Fetch documents in specific language (e.g. "en" or "de" or "en-GB")client.setLanguage('en');

Define publishing date filter

// Documents published between specific date rangeclient.setDateFilter('2019-01-01','2019-01-31');

Define price range filter

// Products in specific price range (in cents. e.g. 100,00 - 200,00)client.setPriceRangeFilter('10000','20000');

Define category filters

Filter by URL patterns, document types or addsearch-category meta tag values. See the full documentation.

// Only PDF files or productsclient.setCategoryFilters('doctype_pdf,products');

Custom field filters

Filter by custom fields. Custon fields can be defined in meta tags or AddSearch crawler can pick them up from your HTML or JSON data. See the full documentation.

// Search by specific city (Berlin, Paris or Boston)client.addCustomFieldFilter('city','berlin');client.addCustomFieldFilter('city','paris');client.addCustomFieldFilter('city','boston');// Remove Paris (Berlin and Boston remaining)client.removeCustomFieldFilter('city','paris');// Remove all citiesclient.removeCustomFieldFilter('city');

Set filtering object

Set complex filtering object that can contain nested and, or, not, and range filters.

// Find results where brand is apple, color is not white, and price is between 200 and 500varfilter={and: [{'custom_fields.brand': 'apple'},{not: {'custom_fields.color': 'white'}},{range: {'custom_fields.price': {gt: 200,lt: 500}}}]};client.setFilterObject(filter);

Set result type

// By default, fetch all search results// If "organic", Pinned results and Promotions are left outclient.setResultType('organic');

Facets

// Declare fields for faceting. Number of hits found from// these fields will be returnedclient.addFacetField('category');client.addFacetField('custom_fields.genre');

Facet values are returned in alphabetical order, 10 values per field by default. Use the following function to get more or less facets.

client.setNumberOfFacets(20);

Note: if a field has more values than the defined limit, the returned values are the first N in alphabetical order, not the N with most hits. Increase the limit if you need more values.

Numerical range facets

Group numerical custom fields into range buckets.

// Define ranges. E.g. products with price $0-$100, $100-$200, and over $200.// From value is inclusive, to value is exclusivevarranges=[{to: 100},{from: 100,to: 200},{from: 200}];// Parameters: field name, range arrayclient.addRangeFacet('custom_fields.price',ranges);

Field statistics

Get minimum, maximum, and average values of a numerical or date-based custom field. The information is handy for applications like range filtering.

// Search response will have a fieldStats element with information like// custom_fields.price: {min: 1230, max: 1590, avg: 1382}client.addStatsField('custom_fields.price');

Recommendations

Frequently bought together items

Get frequently bought together items, given "configurationKey" and "itemId"

// fetch frequently bought together itemsclient.recommendations({configurationKey: 'config1',itemId: '1065921'});

Search analytics

Send search event to analytics

When search is executed, send the event to your AddSearch Analytics Dashboard.

// If the numberOfResults is 0, the search is shown in the list of "queries with no hits"client.sendStatsEvent('search',keyword,{numberOfResults: n});

Send click event to analytics

When a search results is clicked, send the event to your AddSearch Analytics Dashboard. Click information is shown in your statistics and used by the self-learning search algorithm.

// documentId is the 32-character long id that is part of each hit in search results.// position is the position of the document that was clicked, the first result being 1client.sendStatsEvent('click',keyword,{documentId: id,position: n});

Set or get stats session ID

Control the search session ID manually. Search queries with the same ID are grouped on the Analytics Dashboard. For example, in a search-as-you-type implementation the final keyword of a given session is shown.

client.getStatsSessionId();client.setStatsSessionId(id);

Collect search events automatically

Send search events automatically to the Analytics Dashboard. Not recommended in search-as-you-type implementations, as every keystroke would fire a statistics event

// Control whether search queries are sent to your AddSearch Analytics Dashboard automatically or not (default: true)client.setCollectAnalytics(false);

Set a tag for analytics events

Defines a tag associated with all analytics events reported by the client. These tags will be available as filters in the AddSearch Analytics Dashboard. You can use tags, for instance, in A/B testing to compare which search UIs are most effective. Splitting the analytics with tags may also provide insights to the behaviour of audiences on different websites.

// Specify a tag for analytics events (the maximum length is 50 characters)client.setAnalyticsTag('Navigation search');

Personalization

Enable personalization tracking

Enable personalization tracking, user token will be included in every stat events as "session ID".

Set stats session ID if user token is generated by your site.

client.setStatsSessionId(userToken);

If session is not set, a UUID is generated and stored in a cookie named 'addsearchUserToken`. Specify the expiration date of the cookie. Default is 180.

// Defaults - isEnabled: false, expirationDates: 180client.enablePersonalizationTracking(isEnabled,expirationDates);

Allow storing AddSearch's user token in cookie

By default, the value is false. Set it to false when users reject cookie (AddSearch's cookie can be categorized as functional/analytics cookie), or set to true when user accepts cookie.

// Default: falseclient.consentAddSearchCookie(true);

Set user token to search query (for personalized search results)

// Add a user token to the search request (if personalization in use)client.setUserToken(userToken);

Get user token from AddSearch cookie

Get the user token which is stored in AddSearch cookie (if available).

// Get a user tokenclient.getUserTokenInPersonalization();

Send personalization events with search query - deprecated

In personalized search, user events are typically sent to AddSearch via API and a user token is passed with the search query (see setUserToken function). An alternative way is to send user events needed for personalization with the search query.

// Events depend on the personalization strategy// Contact AddSearch for more informationvarevents=[{favorite_genre: 'rock'},{favorite_band: 'Red Hot Chili Peppers'},{least_favorite_genre: 'country'}];client.setPersonalizationEvents(events);

Other

Set JSON Web Token (for authentication)

// Add JWT to the search request (if protected search index)client.setJWT(token);

Set API throttling

// Set Search API throttle time in milliseconds. Default is 200.client.setThrottleTime(500);

Set API hostname

option is an object with the following properties, all of which are optional. If option is not defined, host name will be applied for all requests.

  • searchApiRequestOnly: If true, the new host name is only applied for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the new host name is only applied for statsApi requests (default: false)
// Set API hostname (e.g. for dedicated environments)client.setApiHostname('api.addsearch.com',option);

Set API request interceptor

configurationObject contains 2 keys: url and headers. Modify the configurationObject before it is sent.

option is an object with the following properties, all of which are optional. If option is not defined, the interceptor will be used for all requests.

  • searchApiRequestOnly: If true, the interceptor is only used for searchApi requests (default: false)
  • statsApiRequestOnly: If true, the interceptor is only used for statsApi requests (default: false)
functioncallback(configurationObject){configurationObject.headers['X-Api-Key']='YOUR API KEY';returnconfigurationObject;}client.setApiRequestInterceptor(callback,option);

AI Answers API

Fetch AI answers

// Get AI generated answer with a questionclient.aiAnswers('A question to get AI generated answers',callback);

Example of callback function and how the response looks like:

callbackFn=function(response){console.log(response);// response object contains the answer// {// "answer": "The answer to the question",// "conversation_id": "31f33b53-1fe1-4734-884f-fefa470f1389",// "ids": <array of ids belonging to source documents>, for example ['073010f023db7c6d558123f73a9b4f82', '821f7bea12daf0eda17ba2755979f7a5'],// "source_documents": <documents that provide context for AI generated answers, the object of this field looks similarly to the response of regular SearchApi result>// }};

Send Sentiment Analysis

// possible sentiment_value: positive, negativeclient.putSentimentClick('conversation_id','sentiment_value');

Set AI-answers filtering object

Set complex filtering object that can contain nested and, or, not. Key filterable properties include: category, custom_fields.<your_field_name>, language, doc_date

// Find results where region is en-us, color is not whitevaraiAnswersFilter={and: [{'custom_fields.region': 'en-us'},{not: {'custom_fields.color': 'white'}}]};client.setAiAnswersFilterObject(aiAnswersFilter);

POST API

❗ POST API is not fully supported. If you need to use some methods in the library, please contact our support.

Fetch AI answers

// default method: "GET"client.setApiMethod('POST');

Indexing API

With the Indexing API, you can fetch, create, update, and delete single documents or batches of documents.

Indexing API functions are meant to be used with Node.js. Never expose secret key in your website code.

// Create client with your keysvarclient=newAddSearchClient('YOUR PUBLIC SITEKEY','YOUR SECRET KEY');

The secret key can be found from AddSearch Dashboard's "Setup" > "Keys and installation" page. Always keep the key secret.

All Indexing API functions are Promise-based.

Document structure

Documents can contain a set of pre-defined fields, as well as any number of custom fields defined under the custom_fields key.

Using pre-defined fields is optional, but default Search UI components display them by default, so pre-defined field give you visible results a bit faster.

Pre-defined fields are: url, title, and main_content.

Example document:

constdoc={id: '1234',url: 'https://www.example-store.com/product-x',title: 'Example product',main_content: 'Lorem ipsum',custom_fields: {name: 'Example product',description: 'Description for the example product',price_cents: 599,average_customer_rating: 4.5,release_date: 1589200255}};

Data types for custom fields are automatically detected from the content. Supported data types are:

  • text
  • integer
  • double

Dates should be defined as UNIX timestamps with integer values.

Document ID

If the id is not defined in the document at indexing time, it is generated automatically either randomly or from the url field.

// ID defined by the userconstdocWithDefinedId={id: '1234',custom_fields: {}};
// ID created from the URL field (md5 of the url)constdocWithURL={url: 'https://..',custom_fields: {}};
// ID generated randomlyconstdocWithAutogeneratedId={// No id or url fieldscustom_fields: {}};

Save document

Add a document to the index, or update a document.

constdoc={id: '1234',custom_fields: {name: 'Example product'}};// Save documentclient.saveDocument(doc).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Get document by ID

Fetch a specific document by ID.

client.getDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete document by ID

Delete a specific document by ID.

client.deleteDocument(id).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Save batch of documents

Add or update bunch of documents defined in an array.

constbatch={documents: [{id: '1234',custom_fields: {name: 'Product 1'}},{id: '5678',custom_fields: {name: 'Product 2'}}]};// Save batch of documentsclient.saveDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Delete batch of documents

Delete multiple documents with an array of document IDs.

// Array of document IDsconstbatch={documents: ['1234','5678']};// Delete batch of documentsclient.deleteDocumentsBatch(batch).then((response)=>{console.log(response);}).catch((error)=>{console.log(error);});

Supported browsers

The client is tested on

  • Chrome
  • Firefox
  • Edge
  • Safari 6.1+
  • Internet Explorer 10+
  • Node.js

Development

To modify this client library, clone this repository to your computer and execute following commands.

Install dependencies

npm install

Code

Re-compile automatically when source files are changed

npm run watch

Run tests

npm test

Build

npm run build

Built bundle is saved under the dist/ folder

Support

Feel free to send any questions, ideas, and suggestions at support@addsearch.com or visit addsearch.com for more information.

Releases

Packages

Used by

Contributors

Languages