Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute multiple search query in node.js using elastic search and promises?

Elastic Search Code :

POST /_msearch
{ "index": "INDEX_NAME_1", "type": "TYPE_NAME_1" }
{ "query": { "match_all": {}}}
{ "index": "INDEX_NAME_2", "type": "TYPE_NAME_2" }
{ "query": { "match_all": {}}}

Reference link http://teknosrc.com/execute-multiple-search-query-elasticsearch/#comment-8578 (Refer example 1)

Node js code :

return new Promise(function (resolve, reject) {
        elasticClient.search({
             index: '*:logstash-prod-*',
             type: 'callEnd',
             size: 10000,
             body: {
                 query: {

                     range: {
                         "@timestamp": {
                             "gte": startTime,
                             "lte": endTime
                         }
                     }
                 }
             },
         }, function (error, response, status) {
             if (error) {
                    reject(error);
             }
             else {
                     console.log("show the response" + JSON.stringify(response));
                     let elasticResponse=response.hits.hits;
                     resolve(response);
             }
         })
     });

Above node js query works for one type:"callEnd". Please help in converting the Elastic code (two types) to node js code.

like image 433
praveen jasso Avatar asked Sep 18 '25 07:09

praveen jasso


1 Answers

Here is msearch documentation.

In your case it'll be something like this:

const queryBody = [
    { index: '*:logstash-prod-*', type: 'callEnd1' },
    {
        query: {
            range: {
                '@timestamp': {
                    'gte': startTime,
                    'lte': endTime
                }
            }
        },
        size: 10000
    },
    { index: '*:logstash-prod-*', type: 'callEnd2' },
    {
        query: {
            range: {
                '@timestamp': {
                    'gte': startTime,
                    'lte': endTime
                }
            }
        },
        size: 10000
    }
];

return elasticClient
    .msearch({ body: queryBody })
    .then(result => {
        console.log('show the response' + JSON.stringify(result));

        return result;
    })
    .catch(error => {
        // TODO Handle error here.
    });

Note that msearch returns promise itself, so no need to create it yourself.

like image 72
Filipp Shestakov Avatar answered Sep 19 '25 23:09

Filipp Shestakov