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:
<script src="https://cdn.jsdelivr.net/npm/addsearch-js-client@0.5/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
var AddSearchClient = require('addsearch-js-client');
Or use import in ES6
import AddSearchClient from 'addsearch-js-client';
Execute the first search query
var client = new AddSearchClient('YOUR PUBLIC SITEKEY');
var cb = function(res) {
console.log(res);
}
client.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
client.search('keyword', callback);
client.search(callback);
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.
client.suggestions('a', callback);
Set the number of search suggestions to fetch
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.
client.autocomplete('custom_fields.brand', 'a', callback);
Set the number of custom field autocompletion results to fetch
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
client.setFuzzyMatch(false);
Postfix wildcard
Enable or disable postfix wildcard. I.e. should keyword "add" match to "addsearch" or should it just match to the
term add
client.setPostfixWildcard(false);
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)
client.setPaging(page, pageSize, sortBy, sortOrder);
Other functions.
client.nextPage();
client.previousPage();
Filters
Define language filter
client.setLanguage('en');
Define publishing date filter
client.setDateFilter('2019-01-01', '2019-01-31');
Define price range filter
client.setPriceRangeFilter('10000', '20000');
Define category filters
Filter by URL patterns, document types or addsearch-category meta tag values.
See the full documentation.
client.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.
client.addCustomFieldFilter('city','berlin');
client.addCustomFieldFilter('city','paris');
client.addCustomFieldFilter('city','boston');
client.removeCustomFieldFilter('city','paris');
client.removeCustomFieldFilter('city');
Set filtering object
Set complex filtering object that can contain nested and, or, not, and range filters.
var filter = {
'and':[
{'custom_fields.brand': 'apple'},
{'not': {'custom_fields.color': 'white'}},
{'range': {'custom_fields.price': {'gt': 200, 'lt':500}}}
]
};
client.setFilterObject(filter);
Set result type
client.setResultType('organic');
Facets
client.addFacetField('category');
client.addFacetField('custom_fields.genre');
By default, 10 facets with most hits are returned per field.
Use the following function to get more or less facets.
client.setNumberOfFacets(20);
Numerical range facets
Group numerical custom fields into range buckets.
var ranges = [
{'to': 100},
{'from': 100, 'to': 200},
{'from': 200}
];
client.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.
client.addStatsField('custom_fields.price');
Search analytics
Send search event to analytics
When search is executed, send the event to your AddSearch Analytics Dashboard.
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.
client.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
client.setCollectAnalytics(false);
Personalization
Set user token (for personalized search results)
client.setUserToken('uuid');
Send personalization events with search query
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.
var events = [
{favorite_genre: 'rock'},
{favorite_band: 'Red Hot Chili Peppers'},
{least_favorite_genre: 'country'}
];
client.setPersonalizationEvents(events);
Other
Set JSON Web Token (for authentication)
client.setJWT(token);
Set API throttling
client.setThrottleTime(500);
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.
var client = new AddSearchClient('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:
const doc = {
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:
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.
const docWithDefinedId = {
id: '1234',
custom_fields: {}
}
const docWithURL= {
url: 'https://..',
custom_fields: {}
}
const docWithAutogeneratedId = {
custom_fields: {}
}
Save document
Add a document to the index, or update a document.
const doc = {
id: '1234',
custom_fields: {
'name': 'Example product'
}
};
client.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.
const batch = {
documents: [
{
id: '1234',
custom_fields: {
'name': 'Product 1'
}
},
{
id: '5678',
custom_fields: {
'name': 'Product 2'
}
}
]
};
client.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.
const batch = {
documents: ["1234", "5678"]
};
client.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.