Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
algoliasearch
Advanced tools
The algoliasearch npm package is a JavaScript client for Algolia, a hosted search API that provides a fast and accurate search experience for websites and mobile applications. The package allows developers to integrate Algolia's search capabilities into their JavaScript applications, enabling features such as full-text search, faceting, filtering, and geolocation queries.
Search
Perform a search query on an Algolia index and retrieve the results.
const algoliasearch = require('algoliasearch');
const client = algoliasearch('YourApplicationID', 'YourAdminAPIKey');
const index = client.initIndex('your_index_name');
index.search('query string').then(({ hits }) => {
console.log(hits);
});
Indexing
Add or update a record in an Algolia index.
const algoliasearch = require('algoliasearch');
const client = algoliasearch('YourApplicationID', 'YourAdminAPIKey');
const index = client.initIndex('your_index_name');
index.saveObject({ objectID: '1', name: 'Foo' }).then(() => {
console.log('Object indexed');
});
Configure Index Settings
Configure settings of an Algolia index to define ranking, attributes for faceting, etc.
const algoliasearch = require('algoliasearch');
const client = algoliasearch('YourApplicationID', 'YourAdminAPIKey');
const index = client.initIndex('your_index_name');
index.setSettings({
searchableAttributes: ['name', 'description'],
customRanking: ['desc(popularity)']
}).then(() => {
console.log('Settings updated');
});
Manage Indices
List all indices in your Algolia application and manage them.
const algoliasearch = require('algoliasearch');
const client = algoliasearch('YourApplicationID', 'YourAdminAPIKey');
client.listIndices().then(({ items }) => {
console.log(items);
});
Elasticsearch is a distributed, RESTful search and analytics engine capable of solving a growing number of use cases. The elasticsearch npm package is the official Elasticsearch client for Node.js. It provides similar search capabilities but is typically self-hosted, unlike Algolia which is a managed service.
Solr-node is a client library for interacting with Apache Solr, which is an open-source search platform. Similar to Algolia, it provides full-text search, but it requires self-hosting and manual scaling, whereas Algolia offers a fully managed service.
Typesense is an open-source, typo-tolerant search engine that provides a similar developer experience to Algolia. The typesense npm package allows you to integrate Typesense into your JavaScript applications. It is designed to be easy to use and deploy, offering an alternative to Algolia with a focus on simplicity and speed.
Algolia Search is a hosted full-text, numerical, and faceted search engine capable of delivering realtime results from the first keystroke. Algolia's Search API makes it easy to deliver a great search experience in your websites and mobile applications by providing:
Our JavaScript client lets you easily use the Algolia Search API in a browser.
It works and has been tested in all the major browsers.
Our JavaScript client uses either:
The JavaScript API client is dedicated to web apps searching directly from the browser. To add, remove or delete your objects please consider using a backend API client.
Getting Started
Commands Reference
To setup your project, follow these steps:
bower install algoliasearch
Both jsDelivr and cdnjs are offering global CDN delivery for our JavaScript client.
<script src="//cdn.jsdelivr.net/algoliasearch/{VERSION}/algoliasearch.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/algoliasearch/{VERSION}/algoliasearch.min.js"></script>
Please do not use latest
as the {VERSION} tag, you can find the latest tag.
The current stable version of our JavaScript client is
We have specific builds for jQuery and Angular.js.
<script src="//cdn.jsdelivr.net/algoliasearch/{VERSION}/algoliasearch.jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/algoliasearch/{VERSION}/algoliasearch.angular.min.js"></script>
<script src="http://domain/path-to/algoliasearch.min.js"></script>
<script>
var client = new AlgoliaSearch('ApplicationID', 'Search-Only-API-Key');
var index = client.initIndex('indexName');
index.search('something', function(success, hits) {
console.log(success, hits)
});
</script>
You must have jQuery loaded in your page.
<script src="http://domain/path/to/algoliasearch.jquery.min.js"></script>
<script>
var client = $.algolia.Client('ApplicationID', 'Search-Only-API-Key');
var index = client.initIndex('indexName');
index.search('something', function(success, hits) {
console.log(success, hits)
});
</script>
You must have Angular loaded in your page.
<script src="http://domain/path/to/algoliasearch.angular.min.js"></script>
<script>
angular
.module('myapp', ['algoliasearch'])
.controller('SearchCtrl', ['$scope', 'algolia', function($scope, algolia) {
$scope.query = '';
$scope.hits = [];
var client = algolia.Client('ApplicationID', 'Search-Only-API-Key');
// ...
}]);
</script>
We also provide runnable examples for you to try.
We have easy to run examples for you to try. First, setup the repository:
git clone https://github.com/algolia/algoliasearch-client-js.git
cd algoliasearch-client-js
npm install
npm run examples
Then open either:
To hack and use your own indexes and data, open one of the example file and replace:
var client = new AlgoliaSearch(ApplicationID, Search-Only-API-Key);
var index = client.initIndex(indexName);
All API calls will return the result in a callback that takes two arguments:
content.message
)Queries will be stored in a cache
inside your JavaScript Index
and AlgoliaSearch
objects to avoid performing the same API calls twice. It's particularly useful when your users are deleting characters or words from the current query but has a chance of ending up with outdated results if the page isn't refreshed for some time.
To address this issue, be sure to clear the cache every X minutes to ensure you have up to date results:
// clear the queries cache
index.clearCache();
// if you're performing multi-queries using the API client instead of the index
// you'll need to use the following code
algoliaClient.clearCache();
Check our online documentation:
Check out our tutorials:
To perform a search, you only need to initialize the index and perform a call to the search function.
You can use the following optional arguments:
attributesToIndex
index setting). Attributes are separated with a comma such as "name,address"
. You can also use JSON string array encoding such as encodeURIComponent("[\"name\",\"address\"]")
. By default, all attributes specified in attributesToIndex
settings are used to search."
. For example, "search engine"
will retrieve records having search
next to engine
only. Typo tolerance is disabled on phrase queries.-
symbol. For example, search -engine
will retrieve records containing search
but not engine
.page=9
.aroundLatLng: Search for entries around a given latitude/longitude (specified as two floats separated by a comma).
For example, aroundLatLng=47.316669,5.016670
.
You can specify the maximum distance in meters with the aroundRadius parameter and the precision for ranking with aroundPrecision. For example, if you set aroundPrecision=100, two objects that are a distance of less than 100 meters will be considered as identical for the "geo" ranking parameter).
At indexing, you should specify the geo location of an object with the _geoloc
attribute in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}
.
aroundLatLngViaIP: Search for entries around a given latitude/longitude automatically computed from user IP address.
For example, aroundLatLng=47.316669,5.016670
.
You can specify the maximum distance in meters with the aroundRadius parameter and the precision for ranking with aroundPrecision. For example, if you set aroundPrecision=100, two objects that are a distance of less than 100 meters will be considered as identical for the "geo" ranking parameter.
At indexing, you should specify the geo location of an object with the _geoloc
attribute in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}
.
insideBoundingBox: Search entries inside a given area defined by the two extreme points of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
For example, insideBoundingBox=47.3165,4.9665,47.3424,5.0201
).
At indexing, you should specify the geo location of an object with the _geoloc attribute in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}
.
"name,address"
). You can also use a string array encoding (for example ["name","address"]
). By default, all attributes are retrieved. You can also use *
to retrieve all values when an attributesToRetrieve setting is specified for your index.["name","address"]
). If an attribute has no match for the query, the raw value is returned. By default all indexed text attributes are highlighted. You can use *
if you want to highlight all textual attributes. Numerical attributes are not highlighted. A matchLevel is returned for each highlighted attribute and can contain:attributeName:nbWords
). Attributes are separated by commas (Example: attributesToSnippet=name:10,content:10
). attributesToSnippet: ["name:10","content:10"]
). By default, no snippet is computed.attributeName
followed by operand
followed by value
. Supported operands are <
, <=
, =
, >
and >=
.You can easily perform range queries via the :
operator. This is equivalent to combining a >=
and <=
operand. For example, numericFilters=price:10 to 1000
.
You can also mix OR and AND operators. The OR operator is defined with a parenthesis syntax. For example, (code=1 AND (price:[0-100] OR price:[1000-2000]))
translates to encodeURIComponent("code=1,(price:0 to 10,price:1000 to 2000)")
.
You can also use a string array encoding (for example numericFilters: ["price>100","price<1000"]
).
tags=tag1,(tag2,tag3)
means tag1 AND (tag2 OR tag3). You can also use a string array encoding. For example, tagFilters: ["tag1",["tag2","tag3"]]
means tag1 AND (tag2 OR tag3).{"_tags":["tag1","tag2"]}
.attributeName:value
. To OR facets, you must add parentheses. For example: facetFilters=(category:Book,category:Movie),author:John%20Doe
. You can also use a string array encoding. For example, [["category:Book","category:Movie"],"author:John%20Doe"]
."category,author"
. You can also use JSON string array encoding. For example, ["category","author"]
. Only the attributes that have been added in attributesForFaceting index setting can be used in this parameter. You can also use *
to perform faceting on all attributes specified in attributesForFaceting.maxValuesPerFacet=10
will retrieve a maximum of 10 values per facet.attributeForDistinct
index setting is set. This feature is similar to the SQL "distinct" keyword. When enabled in a query with the distinct=1
parameter, all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. For example, if the chosen attribute is show_name
and several hits have the same value for show_name
, then only the best one is kept and the others are removed.
Note: This feature is disabled if the query string is empty and there aren't any tagFilters
, facetFilters
, nor numericFilters
parameters.index = client.initIndex('contacts');
index.search('query string', function(success, content) {
if (!success) {
console.log('Error: ' + content.message);
return;
}
for (var h in content.hits) {
console.log('Hit(' + content.hits[h].objectID + '): ' + content.hits[h].toString());
}
});
index.search('query string', function(success, content) {
if (!success) {
console.log('Error: ' + content.message);
return;
}
for (var h in content.hits) {
console.log('Hit(' + content.hits[h].objectID + '): ' + content.hits[h].toString());
}
}, {attributesToRetrieve: 'firstname,lastname', hitsPerPage: 50});
index = client.initIndex('contacts');
index.search('query string')
.done(function(content) {
for (var h in content.hits) {
console.log('Hit(' + content.hits[h].objectID + '): ' + content.hits[h].toString());
}
})
.fail(function(content) {
console.log('Error: ' + content.message);
});
index.search('query string', { attributesToRetrieve: 'firstname,lastname', hitsPerPage: 50})
.done(function(content) {
for (var h in content.hits) {
console.log('Hit(' + content.hits[h].objectID + '): ' + content.hits[h].toString());
}
})
.fail(function(content) {
console.log('Error: ' + content.message);
});
index = client.initIndex('contacts');
index.search('query string')
.then(function(content) {
$scope.hits = content.hits;
}, function(content) {
console.log('Error: ' + content.message);
});
index.search('query string', { attributesToRetrieve: 'firstname,lastname', hitsPerPage: 50})
.then(function(content) {
$scope.hits = content.hits;
}, function(content) {
console.log('Error: ' + content.message);
});
The server response will look like:
{
"hits": [
{
"firstname": "Jimmie",
"lastname": "Barninger",
"objectID": "433",
"_highlightResult": {
"firstname": {
"value": "<em>Jimmie</em>",
"matchLevel": "partial"
},
"lastname": {
"value": "Barninger",
"matchLevel": "none"
},
"company": {
"value": "California <em>Paint</em> & Wlpaper Str",
"matchLevel": "partial"
}
}
}
],
"page": 0,
"nbHits": 1,
"nbPages": 1,
"hitsPerPage": 20,
"processingTimeMS": 1,
"query": "jimmie paint",
"params": "query=jimmie+paint&attributesToRetrieve=firstname,lastname&hitsPerPage=50"
}
You can send multiple queries with a single API call using a batch of queries:
// perform 3 queries in a single API call:
// - 1st query targets index `categories`
// - 2nd and 3rd queries target index `products`
client.startQueriesBatch();
client.addQueryInBatch('categories', $('#q').val(), { hitsPerPage: 3 });
client.addQueryInBatch('products', $('#q').val(), { hitsPerPage: 3, tagFilters: 'promotion' });
client.addQueryInBatch('products', $('#q').val(), { hitsPerPage: 10 });
client.sendQueriesBatch(searchMultiCallback);
function searchMultiCallback(success, content) {
if (success) {
var categories = content.results[0];
for (var i = 0; i < categories.hits.length; ++i) {
console.log(categories.hits[i]);
}
var products_promotion = content.results[1];
for (var i = 0; i < products_promotion.hits.length; ++i) {
console.log(products_promotion.hits[i]);
}
var products = content.results[2];
for (var i = 0; i < products.hits.length; ++i) {
console.log(products.hits[i]);
}
}
}
// perform 3 queries in a single API call:
// - 1st query targets index `categories`
// - 2nd and 3rd queries target index `products`
client.startQueriesBatch();
client.addQueryInBatch('categories', $('#q').val(), { hitsPerPage: 3 });
client.addQueryInBatch('products', $('#q').val(), { hitsPerPage: 3, tagFilters: 'promotion' });
client.addQueryInBatch('products', $('#q').val(), { hitsPerPage: 10 });
client.sendQueriesBatch().done(function(content) {
var categories = content.results[0];
for (var i = 0; i < categories.hits.length; ++i) {
console.log(categories.hits[i]);
}
var products_promotion = content.results[1];
for (var i = 0; i < products_promotion.hits.length; ++i) {
console.log(products_promotion.hits[i]);
}
var products = content.results[2];
for (var i = 0; i < products.hits.length; ++i) {
console.log(products.hits[i]);
}
});
// perform 3 queries in a single API call:
// - 1st query targets index `categories`
// - 2nd and 3rd queries target index `products`
client.startQueriesBatch();
client.addQueryInBatch('categories', $('#q').val(), { hitsPerPage: 3 });
client.addQueryInBatch('products', $('#q').val(), { hitsPerPage: 3, tagFilters: 'promotion' });
client.addQueryInBatch('products', $('#q').val(), { hitsPerPage: 10 });
client.sendQueriesBatch().then(function(content) {
var categories = content.results[0];
for (var i = 0; i < categories.hits.length; ++i) {
console.log(categories.hits[i]);
}
var products_promotion = content.results[1];
for (var i = 0; i < products_promotion.hits.length; ++i) {
console.log(products_promotion.hits[i]);
}
var products = content.results[2];
for (var i = 0; i < products.hits.length; ++i) {
console.log(products.hits[i]);
}
});
You can easily retrieve an object using its objectID
and optionally specify a comma separated list of attributes you want:
// Retrieves all attributes
index.getObject('myID', function(success, content) {
console.log(content.objectID + ": ", content);
});
// Retrieves firstname and lastname attributes
index.getObject('myID', function(success, content) {
console.log(content.objectID + ": ", content);
}, "firstname,lastname");
// Retrieves only the firstname attribute
index.getObject('myID', function(success, content) {
console.log(content.objectID + ": ", content);
}, "firstname");
// Retrieves all attributes
index.getObject('myID').done(function(content) {
console.log(content.objectID + ": ", content);
});
// Retrieves firstname and lastname attributes
index.getObject('myID', "firstname,lastname").done(function(content) {
console.log(content.objectID + ": ", content);
});
// Retrieves all attributes
index.getObject('myID').then(function(content) {
console.log(content.objectID + ": ", content);
});
// Retrieves firstname and lastname attributes
index.getObject('myID', "firstname,lastname").then(function(content) {
console.log(content.objectID + ": ", content);
});
You can also retrieve a set of objects:
index.getObjects(['myObj1', 'myObj2'], function(success, content) {
// iterate over content
});
index.getObjects(['myObj1', 'myObj2']).done(function(content) {
// iterate over content
});
index.getObjects(['myObj1', 'myObj2']).then(function(content) {
// iterate over content
});
If you're using a secured API Key (see backend client documentation), you need to set the associated tags
:
var algolia = new AlgoliaSearch('YourApplicationID', 'YourPublicSecuredAPIKey');
algolia.setSecurityTags('(public,user_42)'); // must be same than those used at generation-time
If you've specified a userToken
while generating your secured API key, you must also specified it at query-time:
var algolia = new AlgoliaSearch('YourApplicationID', 'YourPublicSecuredAPIKey');
algolia.setSecurityTags('(public,user_42)'); // must be the same as the ones used at generation-time
algolia.setUserToken('user_42') // must be the same as the one used at generation-time
In some use cases, such as an HTML5 mobile application, it may be necessary to perform updates to the index directly in JavaScript. Therefore, just like other languages, the JavaScript client is able to add, update & delete objects, and modify index settings. For more details about updating an index from JavaScript, take a look at the algoliasearch.js source file to see details about each function. If you use the JavaScript client to update the index, you need to specify https
as the protocol during client initialization:
<script src="algoliasearch.min.js"></script>
<script>
client = new AlgoliaSearch('ApplicationID', 'API-Key', { method: 'https' });
...
FAQs
A fully-featured and blazing-fast JavaScript API client to interact with Algolia API.
The npm package algoliasearch receives a total of 1,664,751 weekly downloads. As such, algoliasearch popularity was classified as popular.
We found that algoliasearch demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 10 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.