I am basically trying to show all records of an index type. Now, if you use match_all() in query elasticsearch shows 10 results by default. One can show all results using scroll. I am trying to implement scroll api, but can't get it to work. It is showing only 10 results, my code:
module.exports.searchAll = function (searchData, callback) {
client.search({
index: 'test',
type: 'records',
scroll: '10s',
//search_type: 'scan', //if I use search_type then it requires size otherwise it shows 0 result
body: {
query: {
"match_all": {}
}
}
}, function (err, resp) {
client.scroll({
scrollId: resp._scroll_id,
scroll: '10s'
}, callback(resp.hits.hits));
});
}
Can anyone help, please?
If a search request results in more than ten hits, ElasticSearch will, by default, only return the first ten hits. To override that default value in order to retrieve more or fewer hits, we can add a size parameter to the search request body.
To perform a scroll search, you need to add the scroll parameter to a search query and specify how long Elasticsearch should keep the search context viable. This query will return a maximum of 5000 hits. If the scroll is idle for more than 40 seconds, it will be deleted.
By default, Elasticsearch limits the number of results to 10, so if you can have more than 10 results, look at the value of total for the precise number of documents that match your search criteria. As you saw previously, to change the number of results returned, use the size parameter.
Elasticsearch lets you search through vast amounts of data, whether you're implementing real-time search experiences or doing in-depth data analysis. In this tutorial, you'll learn how to integrate Elasticsearch into your Node. js app.
You need to repeatedly call client.scroll
until no more records are returned. There's a good example in the elasticsearch documentation. I've reproduced their example code below, slightly modified to match your question
var allRecords = [];
// first we do a search, and specify a scroll timeout
client.search({
index: 'test',
type: 'records',
scroll: '10s',
body: {
query: {
"match_all": {}
}
}
}, function getMoreUntilDone(error, response) {
// collect all the records
response.hits.hits.forEach(function (hit) {
allRecords.push(hit);
});
if (response.hits.total !== allRecords.length) {
// now we can call scroll over and over
client.scroll({
scrollId: response._scroll_id,
scroll: '10s'
}, getMoreUntilDone);
} else {
console.log('all done', allRecords);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With