一尘不染

用Elasticsearch搜索/滚动异步等待

elasticsearch

我正在将其await用作搜索的一部分,但必须使用+30000个项scroll

问题在于,搜索的初始部分是在搜索之前完成的scroll,因此await触发和功能将继续进行。我应该怎么做才能阻止这种情况?

var allTitles = [];
try {
    await client.search({
        index: 'myindex',
        scroll: '30s',
        source: ['title'], 
        q: 'title:test'
    }, function getMoreUntilDone(error, response) { 
        response.hits.hits.forEach(function (hit) {
            allTitles.push(hit._source.title);
    });
    if (response.hits.total > allTitles.length) {
        client.scroll({
            scrollId: response._scroll_id,
            scroll: '30s'
        }, getMoreUntilDone);
    } else {
        console.log('every "test" title', allTitles);
       }
    });
} catch (err) {
    console.log(err)
}

阅读 353

收藏
2020-06-22

共1个答案

一尘不染

所以,我已经重新编写了它,以便在这里帮助任何需要它的人。

var stuff = []
const q = {params}

const searchstuff = (q) => {
    return new Promise((resolve, reject) => {
        const get = x => {
            stuff = stuff.concat(x.hits.hits)
            if (x.hits.total > stuff.length) {
                this.client.scroll({ scrollId: x._scrollId, scroll: '10s'}).then(get)
            } else {
                resolve(stuff)
            }
        }
        this.client.search(q).then(get).catch(reject)        
    })
}

const search = await searchstuff(q)
if (search) console.log('Searched')
2020-06-22