-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[util/getAllDocs] extract getAllDocs to util
- Loading branch information
Showing
2 changed files
with
54 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import client from 'util/client'; | ||
|
||
/** | ||
* A generator that fetches all docs in the specified index and yield 1 doc at a time. | ||
* | ||
* @param {String} index The name of the index to fetch | ||
* @param {Object} query The elasticsearch query. Fetches all doc in the specified index if not given. | ||
* @param {Object} settings Query param settings in ES. | ||
* @param {number} settings.size Number of docs per batch. Default to 1000. | ||
* @param {string} settings.scroll The scroll timeout setting. Default to 30s. | ||
* @yields {Object} the document | ||
*/ | ||
async function* getAllDocs( | ||
index, | ||
query = { match_all: {} }, | ||
{ scroll = '30s', size = 1000 } = {} | ||
) { | ||
let resp = await client.search({ | ||
index, | ||
scroll, | ||
size, | ||
body: { | ||
query, | ||
}, | ||
}); | ||
|
||
while (true) { | ||
const docs = resp.body.hits.hits; | ||
if (docs.length === 0) break; | ||
for (const doc of docs) { | ||
yield doc; | ||
} | ||
|
||
if (!resp.body._scroll_id) { | ||
break; | ||
} | ||
|
||
resp = await client.scroll({ | ||
scroll, | ||
scrollId: resp.body._scroll_id, | ||
}); | ||
} | ||
} | ||
|
||
export default getAllDocs; |